2
0

draw.rs 187 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226
  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. if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 {
  1086. return match self.roots_ref(compute).get(usize::from(slot)) {
  1087. Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32,
  1088. Some(&Root::View(address)) => (address >> 32) as u32,
  1089. _ => 0,
  1090. };
  1091. }
  1092. if kind == USER_VIEW_BIAS {
  1093. // The view begins on 16 bytes of the copy the address finds
  1094. // (`root_uav`, `root_srv_table`).
  1095. // shortcut: found again here, not taken from the list's slot.
  1096. return match self.roots_ref(compute).get(usize::from(slot)) {
  1097. Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| {
  1098. // SAFETY: a live buffer.
  1099. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1100. ((s.gpu(address) - base) & 15) as u32
  1101. }),
  1102. _ => 0,
  1103. };
  1104. }
  1105. if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 {
  1106. once!(kind, "a shader reads a host value this build does not know");
  1107. return 0;
  1108. }
  1109. let address = self.view_address(compute, slot, dword);
  1110. if address == 0 {
  1111. // The first few say what lies there instead.
  1112. static SAID: AtomicU64 = AtomicU64::new(0);
  1113. if SAID.fetch_add(1, Ordering::Relaxed) < 8 {
  1114. let view = match self.roots_ref(compute).get(usize::from(slot)) {
  1115. Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4),
  1116. _ => None,
  1117. };
  1118. tracing::warn!(slot, dword, ?view, "a shader takes the address of a buffer view that is not there: it reads 0");
  1119. }
  1120. }
  1121. if kind == USER_VIEW_ADDRESS {
  1122. address as u32
  1123. } else {
  1124. (address >> 32) as u32
  1125. }
  1126. }
  1127. /// The title address the view at dword `dword` of the table in root
  1128. /// slot `slot` starts at, 0 without one.
  1129. fn view_address(&self, compute: bool, slot: u8, dword: u32) -> u64 {
  1130. match self.roots_ref(compute).get(usize::from(slot)) {
  1131. Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4)
  1132. .and_then(|view| crate::descriptor::host::view_address(&view))
  1133. .unwrap_or(0),
  1134. _ => 0,
  1135. }
  1136. }
  1137. /// For a shader that reads title memory by address
  1138. /// ([`crate::memory`]): its directory, fault notes and view slots,
  1139. /// with the pages made ready of the root views the list has set and of
  1140. /// the views whose addresses it takes (`t`: the ray-tracing structures
  1141. /// it walks).
  1142. fn memory_ready(
  1143. &self,
  1144. list: &HostList,
  1145. t: &crate::pipeline::Translated,
  1146. compute: bool,
  1147. use_: crate::memory::Use,
  1148. ) -> Option<crate::memory::Ready> {
  1149. let heap = match self.heaps[0] {
  1150. 0 => None,
  1151. h => crate::descriptor::heap(h as This).host(),
  1152. }?;
  1153. let (mut addresses, mut constants) = (Vec::new(), Vec::new());
  1154. // (What it may write: its root views of unordered access.)
  1155. let written: Vec<u64> = t
  1156. .used
  1157. .iter()
  1158. .filter(|u| u.kind == ResourceType::Uav && u.root == RootType::Descriptor)
  1159. .filter_map(|u| match self.roots_ref(compute).get(usize::from(u.slot)) {
  1160. Some(&Root::View(address)) => Some(address),
  1161. _ => None,
  1162. })
  1163. .collect();
  1164. for root in self.roots_ref(compute) {
  1165. match root {
  1166. // (Of a program that only walks structures, the structures'
  1167. // views below: its root views are constants and tables.)
  1168. Root::View(address) if use_ != crate::memory::Use::Reads => addresses.push(*address),
  1169. Root::Constants(values) => constants.extend_from_slice(values),
  1170. _ => {}
  1171. }
  1172. }
  1173. for u in &t.host.user_data {
  1174. if u.root == RootType::Other(victory_shader::emit::USER_VIEW_ADDRESS) {
  1175. addresses.push(self.view_address(compute, u.slot, u.dword));
  1176. }
  1177. }
  1178. crate::memory::ready(list, heap, &addresses, &written, &constants, use_)
  1179. }
  1180. /// The bound heap holding `handle`.
  1181. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
  1182. self.heaps
  1183. .iter()
  1184. .filter(|&&h| h != 0)
  1185. .map(|&h| crate::descriptor::heap(h as This))
  1186. .find(|h| h.index(handle).is_some())
  1187. }
  1188. /// Brings the host list up to date for a draw; false if the draw cannot
  1189. /// run on the host.
  1190. fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
  1191. self.prepare_for(list, indexed, false)
  1192. }
  1193. /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
  1194. fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
  1195. #[cfg(feature = "diagnostics")]
  1196. if crate::pipeline::is_skipped(self.pipeline as This) {
  1197. return false;
  1198. }
  1199. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  1200. return false;
  1201. };
  1202. if p.compute || p.mesh != mesh {
  1203. once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
  1204. return false;
  1205. }
  1206. if p.rects && self.topology != RECTANGLES {
  1207. // Its geometry stage would turn each triangle into a rectangle.
  1208. once!("a rectangle pipeline drawn with another topology");
  1209. }
  1210. if !self.bind(list, p, false) {
  1211. return false;
  1212. }
  1213. let l = &list.list;
  1214. // Vertex buffers the input layout reads.
  1215. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
  1216. let mut count = 0;
  1217. for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
  1218. if p.slots & 1 << slot == 0 {
  1219. continue;
  1220. }
  1221. count = slot + 1;
  1222. if v.address == 0 || v.size == 0 {
  1223. continue;
  1224. }
  1225. let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
  1226. continue;
  1227. };
  1228. shadow.refresh(list, v.address, u64::from(v.size));
  1229. *view = D3D12_VERTEX_BUFFER_VIEW {
  1230. BufferLocation: shadow.gpu(v.address),
  1231. SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)),
  1232. StrideInBytes: v.stride,
  1233. };
  1234. }
  1235. // SAFETY: an open list; the views name live host buffers.
  1236. unsafe {
  1237. if count > 0 {
  1238. l.IASetVertexBuffers(0, Some(&views[..count]));
  1239. }
  1240. }
  1241. if indexed {
  1242. let v = self.index;
  1243. let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
  1244. return false;
  1245. };
  1246. shadow.refresh(list, v.address, u64::from(v.size));
  1247. let view = D3D12_INDEX_BUFFER_VIEW {
  1248. BufferLocation: shadow.gpu(v.address),
  1249. SizeInBytes: v.size.min(u32::try_from(shadow.left(v.address)).unwrap_or(u32::MAX)),
  1250. Format: DXGI_FORMAT(v.format as i32),
  1251. };
  1252. // SAFETY: an open list; the view names a live host buffer.
  1253. unsafe { l.IASetIndexBuffer(Some(&view)) };
  1254. }
  1255. const RENDER_TARGET: u32 = 0x4;
  1256. for &t in &self.targets {
  1257. crate::list::ensure_state(list, t as This, RENDER_TARGET);
  1258. }
  1259. if self.depth != 0 {
  1260. // A depth texture shaders also write: what they wrote, first.
  1261. list.twin_use(self.depth as This, false, true);
  1262. // A view that writes neither plane keeps the texture readable:
  1263. // the depth read state, together with the shader read states
  1264. // if this draw's shaders read the same texture (the write state
  1265. // put it out of the state those views need, and a move to it
  1266. // and back for every such draw).
  1267. let state = if self.depth_state == DEPTH_READ {
  1268. let (tested, read) = TESTED_DEPTH.get();
  1269. if read && tested == self.depth {
  1270. DEPTH_READ | SHADER_RESOURCE
  1271. } else {
  1272. DEPTH_READ
  1273. }
  1274. } else {
  1275. DEPTH_WRITE
  1276. };
  1277. crate::list::ensure_state(list, self.depth as This, state);
  1278. }
  1279. true
  1280. }
  1281. /// A descriptor a shader reads through a table: its host slot made if
  1282. /// it changed, constant data copied, textures made readable.
  1283. /// What draws and dispatches share: heaps, our root signature, the
  1284. /// pipeline, and per stage the user data, root views and the
  1285. /// descriptors its tables hold.
  1286. /// False if the draw or dispatch must not run: a root SRV it reads
  1287. /// could not be given a view.
  1288. pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool {
  1289. let l = &list.list;
  1290. // Textures picked by index, before anything asks for them.
  1291. self.early_textures(list, p, compute);
  1292. if crate::host::walls_trace() {
  1293. self.walls_census(p, compute);
  1294. }
  1295. // A list without a view heap: one of the title's for the views the
  1296. // host itself puts into heap slots.
  1297. if self.heaps[0] == 0
  1298. && p.stages.iter().any(|s| !s.root_uavs.is_empty() || !s.root_srvs.is_empty())
  1299. && let Some(heap) = crate::descriptor::lent_heap()
  1300. {
  1301. once!("a dispatch without a view heap that needs one gets the title's");
  1302. self.heaps[0] = heap;
  1303. }
  1304. // Heaps first: a root signature with directly indexed heaps must be
  1305. // set after them.
  1306. if self.host_heaps != self.heaps {
  1307. let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
  1308. .heaps
  1309. .iter()
  1310. .filter(|&&h| h != 0)
  1311. .filter_map(|&h| crate::descriptor::heap(h as This).host())
  1312. .map(|h| Some(h.heap.clone()))
  1313. .collect();
  1314. heaps.iter().flatten().for_each(|h| list.keep(h));
  1315. // SAFETY: an open list and shader-visible heaps.
  1316. unsafe { l.SetDescriptorHeaps(&heaps) };
  1317. self.host_heaps = self.heaps;
  1318. self.host_roots = [0; 2];
  1319. }
  1320. // The depth target a draw only tests, for the views of it that the
  1321. // draw's shaders read (`readable`).
  1322. let tested = if !compute && self.depth_state == DEPTH_READ {
  1323. self.depth
  1324. } else {
  1325. 0
  1326. };
  1327. TESTED_DEPTH.set((tested, false));
  1328. let root = p.root.as_raw() as usize;
  1329. if self.host_roots[usize::from(compute)] != root {
  1330. // SAFETY: an open list and a live root signature.
  1331. unsafe {
  1332. if compute {
  1333. l.SetComputeRootSignature(&p.root);
  1334. } else {
  1335. l.SetGraphicsRootSignature(&p.root);
  1336. }
  1337. }
  1338. self.host_roots[usize::from(compute)] = root;
  1339. }
  1340. // By host object: a title pipeline released and another made at its
  1341. // address is another host pipeline (the list keeps the old one).
  1342. if self.host_pipeline != p.pso.as_raw() as usize {
  1343. // SAFETY: an open list and a live pipeline.
  1344. unsafe { l.SetPipelineState(&p.pso) };
  1345. self.host_pipeline = p.pso.as_raw() as usize;
  1346. list.used_pipeline(&p.name);
  1347. // The title may release the pipeline before it submits the list.
  1348. list.keep(&p.pso);
  1349. list.keep(&p.root);
  1350. }
  1351. for stage in &p.stages {
  1352. let t = stage.translated();
  1353. STORES.set(t.stores);
  1354. if t.stores && crate::picked::on() && crate::picked::picks(&stage.shader, &t.picks) {
  1355. crate::picked::runs_in(list);
  1356. }
  1357. let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute);
  1358. STORES.set(true);
  1359. if made.iter().any(|m| m.1 == u32::MAX) {
  1360. once!("a draw whose descriptor table found no free slots is dropped");
  1361. return false;
  1362. }
  1363. // What the shader stores through root views and raw addresses is
  1364. // copied back into title memory afterwards.
  1365. let writes = (t.stores || !write_skip())
  1366. && !crate::pipeline::builder_quarantined(self.pipeline as This);
  1367. // Title memory by address: what the shader finds it by.
  1368. let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) {
  1369. // Only through a store by address: what it stores through
  1370. // views is declared with them.
  1371. let use_ = if crate::pipeline::is_builder(self.pipeline as This) || writes && t.stores_by_address {
  1372. crate::memory::Use::Builds { back: writes }
  1373. } else {
  1374. crate::memory::Use::Reads
  1375. };
  1376. let Some(ready) = self.memory_ready(list, &t, compute, use_) else {
  1377. once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped");
  1378. return false;
  1379. };
  1380. Some(ready)
  1381. } else {
  1382. None
  1383. };
  1384. if let Some((param, dwords)) = stage.user_data {
  1385. // (A root signature holds 64 dwords.)
  1386. let mut room = [0u32; 64];
  1387. let mut more = Vec::new();
  1388. let values: &mut [u32] = match room.get_mut(..dwords as usize) {
  1389. Some(values) => values,
  1390. None => {
  1391. more.resize(dwords as usize, 0);
  1392. &mut more
  1393. }
  1394. };
  1395. for u in &t.host.user_data {
  1396. if let RootType::Other(kind) = u.root {
  1397. values[u.index as usize] =
  1398. self.host_word(compute, kind, u.slot, u.dword, memory.as_ref());
  1399. continue;
  1400. }
  1401. let fresh = made
  1402. .iter()
  1403. .find(|m| m.0 == u.slot && u.root == RootType::Table);
  1404. values[u.index as usize] = match fresh {
  1405. Some(&(_, offset)) => offset,
  1406. None => self.user_value(compute, u.slot, u.root, u.dword),
  1407. };
  1408. }
  1409. #[cfg(feature = "diagnostics")]
  1410. {
  1411. self.user.clear();
  1412. self.user.extend_from_slice(values);
  1413. }
  1414. // SAFETY: an open list; `values` covers the parameter.
  1415. unsafe {
  1416. if compute {
  1417. l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  1418. } else {
  1419. l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  1420. }
  1421. }
  1422. }
  1423. for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
  1424. for &(slot, param) in views {
  1425. if srv && slot == victory_shader::emit::SLOT_MEMORY {
  1426. // Ours: the directory of title memory by address.
  1427. if let Some(m) = &memory {
  1428. // SAFETY: an open list; the directory lives as
  1429. // long as the process and the list holds it.
  1430. unsafe {
  1431. if compute {
  1432. l.SetComputeRootShaderResourceView(param, m.directory);
  1433. } else {
  1434. l.SetGraphicsRootShaderResourceView(param, m.directory);
  1435. }
  1436. }
  1437. }
  1438. continue;
  1439. }
  1440. if srv && slot == victory_shader::emit::SLOT_STRIDES {
  1441. // Ours, not the title's: the shader picks buffers
  1442. // from the view heap by an index it computes.
  1443. match self.heap_buffers(list) {
  1444. // SAFETY: an open list; the table lives as long
  1445. // as the heap the list holds.
  1446. Some(gpu) => unsafe {
  1447. if compute {
  1448. l.SetComputeRootShaderResourceView(param, gpu);
  1449. } else {
  1450. l.SetGraphicsRootShaderResourceView(param, gpu);
  1451. }
  1452. },
  1453. None => once!("a shader picks buffers from a view heap that is not set"),
  1454. }
  1455. continue;
  1456. }
  1457. let tabled = srv && crate::pipeline::host::bounded_root_srvs();
  1458. let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
  1459. else {
  1460. once!(slot, "a shader reads a root view the title did not set");
  1461. // A table left unset is undefined: a null view.
  1462. if tabled && !self.root_srv_table(list, None, param, compute, false) {
  1463. return false;
  1464. }
  1465. continue;
  1466. };
  1467. // The shader adds the bytes a raw view begins early by.
  1468. let biased = srv
  1469. && t.host.user_data.iter().any(|u| {
  1470. u.slot == slot
  1471. && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS)
  1472. });
  1473. if tabled {
  1474. if !self.root_srv_table(list, Some(address), param, compute, biased) {
  1475. return false;
  1476. }
  1477. continue;
  1478. }
  1479. let Some(mut gpu) = root_view(list, address, srv) else {
  1480. continue;
  1481. };
  1482. if biased {
  1483. gpu -= u64::from(self.host_word(
  1484. compute,
  1485. victory_shader::emit::USER_VIEW_BIAS,
  1486. slot,
  1487. 0,
  1488. None,
  1489. ));
  1490. }
  1491. // SAFETY: an open list; the address is in live memory.
  1492. unsafe {
  1493. match (compute, srv) {
  1494. (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
  1495. (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
  1496. (true, false) => l.SetComputeRootConstantBufferView(param, gpu),
  1497. (true, true) => l.SetComputeRootShaderResourceView(param, gpu),
  1498. }
  1499. }
  1500. }
  1501. }
  1502. for &(slot, param) in &stage.root_uavs {
  1503. if slot == victory_shader::emit::SLOT_FAULTS {
  1504. // Ours: where shaders note the pages they found empty.
  1505. if let Some(m) = &memory {
  1506. // SAFETY: an open list; the buffer lives as long as
  1507. // the process and the list holds it.
  1508. unsafe {
  1509. if compute {
  1510. l.SetComputeRootUnorderedAccessView(param, m.faults);
  1511. } else {
  1512. l.SetGraphicsRootUnorderedAccessView(param, m.faults);
  1513. }
  1514. }
  1515. }
  1516. continue;
  1517. }
  1518. let address = match self.roots_ref(compute).get(usize::from(slot)) {
  1519. Some(&Root::View(address)) => Some(address),
  1520. _ => {
  1521. once!(slot, "a shader writes through a root view the title did not set");
  1522. None
  1523. }
  1524. };
  1525. if !self.root_uav(list, address, param, compute, writes) {
  1526. return false;
  1527. }
  1528. }
  1529. }
  1530. // Depth textures it writes through unordered access: their colour
  1531. // twins hold what they lack from here on.
  1532. list.twins_written();
  1533. true
  1534. }
  1535. /// Binds a root UAV: a raw unordered access view of the title buffer's
  1536. /// host copy from `address` on, as a one-view table (a null view
  1537. /// without an address, without a host copy shaders can write, or at an
  1538. /// address not on 16 bytes), or as a root descriptor with
  1539. /// `VICTORY_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there
  1540. /// is nothing to bind). With `writes`, what the shader stored is copied
  1541. /// back into title memory when the list has run. False if the draw
  1542. /// must be dropped.
  1543. /// shortcut: a root view has no size: the view, the refresh and the
  1544. /// copy back cover all that is left of the title's buffer
  1545. /// (`VICTORY_ROOT_UAV_MB` sets a limit for all three).
  1546. fn root_uav(
  1547. &mut self,
  1548. list: &HostList,
  1549. address: Option<u64>,
  1550. param: u32,
  1551. compute: bool,
  1552. writes: bool,
  1553. ) -> bool {
  1554. const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0;
  1555. static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1556. let limit = *LIMIT.get_or_init(|| {
  1557. std::env::var("VICTORY_ROOT_UAV_MB")
  1558. .ok()
  1559. .and_then(|v| v.parse::<u64>().ok())
  1560. .map_or(u64::MAX, |mb| mb << 20)
  1561. });
  1562. let find = |a: u64| {
  1563. let s = crate::shadow::find(a, 1)?;
  1564. // SAFETY: a live buffer.
  1565. let flags = unsafe { s.buffer.GetDesc() }.Flags;
  1566. if flags.0 & UNORDERED == 0 {
  1567. once!("a root UAV of a buffer whose host copy shaders cannot write");
  1568. return None;
  1569. }
  1570. Some(s)
  1571. };
  1572. let ready = |a: u64, s: &std::sync::Arc<crate::shadow::Shadow>| {
  1573. let len = s.left(a).min(limit);
  1574. s.refresh(list, a, len);
  1575. if writes {
  1576. #[cfg(feature = "diagnostics")]
  1577. crate::host::wide_write(a, len, self.pipeline);
  1578. s.gpu_writes(list, a, len);
  1579. }
  1580. };
  1581. if !crate::pipeline::host::bounded_root_srvs() {
  1582. let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else {
  1583. once!("a root UAV with nothing to bind: the draw is dropped");
  1584. return false;
  1585. };
  1586. ready(a, &s);
  1587. // From the 16 bytes below: the shader adds the rest.
  1588. // SAFETY: a live buffer.
  1589. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1590. let gpu = base + ((s.gpu(a) - base) & !15);
  1591. // SAFETY: an open list; the address is in a live buffer.
  1592. unsafe {
  1593. if compute {
  1594. list.list.SetComputeRootUnorderedAccessView(param, gpu);
  1595. } else {
  1596. list.list.SetGraphicsRootUnorderedAccessView(param, gpu);
  1597. }
  1598. }
  1599. return true;
  1600. }
  1601. let heap = match self.heaps[0] {
  1602. 0 => None,
  1603. h => Some(crate::descriptor::heap(h as This)),
  1604. };
  1605. let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
  1606. once!("a root UAV without a bound view heap: the draw is dropped");
  1607. return false;
  1608. };
  1609. let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0));
  1610. let (index, shadow) = match self.root_uav_slots.get(&key) {
  1611. Some((index, shadow)) => (*index, address.zip(shadow.clone())),
  1612. None => {
  1613. let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
  1614. let Some(index) = host.dynamic(1) else {
  1615. return false;
  1616. };
  1617. self.dynamic.push((key.0, index, 1));
  1618. if let Some((a, s)) = &shadow {
  1619. // SAFETY: a live buffer.
  1620. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1621. let offset = s.gpu(*a) - base;
  1622. // Raw views start on 16 bytes: from the 16 bytes
  1623. // below, and the shader adds the rest to its offsets
  1624. // (`victory_shader::emit::USER_VIEW_BIAS`). (An address
  1625. // not on 16 bytes got a null view at first: the
  1626. // builder's counters are at such addresses.)
  1627. let bias = offset & 15;
  1628. host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias);
  1629. }
  1630. if shadow.is_none() {
  1631. host.null_raw_uav_at(index);
  1632. }
  1633. self.root_uav_slots
  1634. .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
  1635. (index, shadow)
  1636. }
  1637. };
  1638. if let Some((a, s)) = &shadow {
  1639. ready(*a, s);
  1640. }
  1641. let handle = host.gpu_handle(index);
  1642. // SAFETY: an open list; the slot is in the bound view heap.
  1643. unsafe {
  1644. if compute {
  1645. list.list.SetComputeRootDescriptorTable(param, handle);
  1646. } else {
  1647. list.list.SetGraphicsRootDescriptorTable(param, handle);
  1648. }
  1649. }
  1650. true
  1651. }
  1652. /// Binds a root SRV as a one-view table
  1653. /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the
  1654. /// title buffer's host copy from `address` to the copy's end, or a null
  1655. /// view (no address, no host copy, or an address not on 16 bytes). One
  1656. /// dynamic slot per address per list, given back with the list's
  1657. /// others. False if no slot could be had or no view heap is bound.
  1658. fn root_srv_table(
  1659. &mut self,
  1660. list: &HostList,
  1661. address: Option<u64>,
  1662. param: u32,
  1663. compute: bool,
  1664. biased: bool,
  1665. ) -> bool {
  1666. let heap = match self.heaps[0] {
  1667. 0 => None,
  1668. h => Some(crate::descriptor::heap(h as This)),
  1669. };
  1670. let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
  1671. once!("a root SRV without a bound view heap: the draw is dropped");
  1672. return false;
  1673. };
  1674. // A view that begins early is another view than one that does not
  1675. // (title addresses stay below bit 63).
  1676. let key = (
  1677. std::ptr::from_ref(heap) as usize,
  1678. address.unwrap_or(0) | u64::from(biased) << 63,
  1679. );
  1680. let (index, shadow) = match self.root_srv_slots.get(&key) {
  1681. Some((index, shadow)) => (*index, address.zip(shadow.clone())),
  1682. None => {
  1683. let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
  1684. let Some(index) = host.dynamic(1) else {
  1685. return false;
  1686. };
  1687. self.dynamic.push((key.0, index, 1));
  1688. self.root_srv_slots
  1689. .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
  1690. match &shadow {
  1691. Some((a, s)) => {
  1692. // SAFETY: a live buffer.
  1693. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1694. let offset = s.gpu(*a) - base;
  1695. if biased {
  1696. // From the 16 bytes below; the shader adds the
  1697. // rest (`victory_shader::emit::USER_VIEW_BIAS`).
  1698. let bias = offset & 15;
  1699. host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias);
  1700. } else if offset.is_multiple_of(16) {
  1701. host.raw_at(index, &s.buffer, offset, s.left(*a));
  1702. } else {
  1703. // Raw views start on 16 bytes; one from the
  1704. // aligned start would shift every read.
  1705. once!(
  1706. address = format_args!("{a:#x}"),
  1707. "a root SRV not on 16 bytes reads zeros"
  1708. );
  1709. host.null_raw_at(index);
  1710. }
  1711. }
  1712. None => host.null_raw_at(index),
  1713. }
  1714. (index, shadow)
  1715. }
  1716. };
  1717. // As for root descriptors (`root_view`): all that is left of the
  1718. // buffer is brought up to date. The first 1 MiB only left what lay
  1719. // past it stale (most mesh vertex streams reach further).
  1720. if let Some((a, s)) = &shadow {
  1721. s.refresh(list, *a, s.left(*a));
  1722. }
  1723. let handle = host.gpu_handle(index);
  1724. // SAFETY: an open list; the slot is in the bound view heap.
  1725. unsafe {
  1726. if compute {
  1727. list.list.SetComputeRootDescriptorTable(param, handle);
  1728. } else {
  1729. list.list.SetGraphicsRootDescriptorTable(param, handle);
  1730. }
  1731. }
  1732. true
  1733. }
  1734. /// For a shader that picks buffers from the view heap by an index it
  1735. /// computes (SM 6.6 dynamic resources): the GPU address of the heap's
  1736. /// table of element strides, with every buffer view of the heap given
  1737. /// its host slot and its memory brought up to date when `list` is
  1738. /// submitted. Tables tell us which views a draw reads; nothing tells
  1739. /// us which of the heap's a computed index names, so all of them are
  1740. /// made ready, once per list.
  1741. /// shortcut: the buffers are read, not written: what such a shader
  1742. /// writes through a picked unordered access view stays in the host
  1743. /// copy. A list refreshes them where it first runs such a shader;
  1744. /// title writes recorded later in the same list are not seen.
  1745. fn heap_buffers(&self, list: &HostList) -> Option<u64> {
  1746. let heap = self
  1747. .heaps
  1748. .iter()
  1749. .filter(|&&h| h != 0)
  1750. .map(|&h| crate::descriptor::heap(h as This))
  1751. .find(|h| !h.samplers())?;
  1752. let host = heap.host()?;
  1753. let gpu = host.strides_gpu()?;
  1754. // One key per list, as textures have: no title resource is there.
  1755. const ONCE: usize = usize::MAX - 0x5e;
  1756. if !list.first_use(ONCE) {
  1757. return Some(gpu);
  1758. }
  1759. // The list may outlive the title's heap object, which owns the table.
  1760. if let Some(buffer) = host.strides_buffer() {
  1761. list.keep(buffer);
  1762. }
  1763. // The pass itself once per frame: per list it ran up to 51 times a
  1764. // frame over 81,000 views and 4,100 host copies, 18 s of every
  1765. // frame (2026-11-24, run 11).
  1766. // shortcut: what the title writes into such buffers between lists
  1767. // of one frame is seen a frame late.
  1768. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1769. let frame = crate::frame::current();
  1770. if FRAME.swap(frame, Ordering::Relaxed) == frame {
  1771. return Some(gpu);
  1772. }
  1773. let started = std::time::Instant::now();
  1774. let mut stage = crate::timeline::span("the heap pass: begun, or done here");
  1775. if crate::host::aside::on() {
  1776. let at = std::ptr::from_ref(heap) as usize;
  1777. list.refreshes_coming(move || {
  1778. crate::descriptor::with_heap(at, |heap| heap.host().map(|host| heap_buffer_pass(heap, host, frame)))
  1779. .flatten()
  1780. .unwrap_or_default()
  1781. });
  1782. } else {
  1783. for (shadow, from, to) in heap_buffer_pass(heap, host, frame) {
  1784. shadow.refresh(list, from, to - from);
  1785. }
  1786. }
  1787. #[cfg(feature = "diagnostics")]
  1788. let refreshed = std::time::Instant::now();
  1789. stage.next("the heap pass: textures");
  1790. self.heap_textures(list, heap, host);
  1791. stage.end();
  1792. #[cfg(feature = "diagnostics")]
  1793. HEAP_SPLIT[2].fetch_add(refreshed.elapsed().as_nanos() as u64, Ordering::Relaxed);
  1794. HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed);
  1795. HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  1796. Some(gpu)
  1797. }
  1798. /// Runs the pass that uploads textures picked by index
  1799. /// ([`State::heap_textures`]) where nothing has asked for it yet
  1800. /// ([`early_budgets`]): once a frame for a few milliseconds, at the
  1801. /// frame's first draw with a view heap set, and with a larger budget
  1802. /// of its own before every draw whose pixel shader is one of the
  1803. /// title's bake programs. The uploads are recorded into `list` ahead
  1804. /// of the draw being bound, as the world's pass records them.
  1805. fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) {
  1806. let (early_ms, bake_ms) = early_budgets();
  1807. if compute || (early_ms == 0 && bake_ms == 0) {
  1808. return;
  1809. }
  1810. let bake = bake_ms > 0
  1811. && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str()));
  1812. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1813. // The milliseconds this frame's bake draws have taken so far: a
  1814. // frame has several, and together they get `bake_ms`.
  1815. static BAKED_MS: AtomicU64 = AtomicU64::new(0);
  1816. let frame = crate::frame::current();
  1817. let first = FRAME.swap(frame, Ordering::Relaxed) != frame;
  1818. if first {
  1819. BAKED_MS.store(0, Ordering::Relaxed);
  1820. }
  1821. let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
  1822. let budget = if bake && left > 0 {
  1823. // What a bake may read must be there now: up to 2 GiB.
  1824. (left, 2 << 30)
  1825. } else if first && early_ms > 0 {
  1826. (early_ms, 64 << 20)
  1827. } else {
  1828. return;
  1829. };
  1830. let Some(heap) = self
  1831. .heaps
  1832. .iter()
  1833. .filter(|&&h| h != 0)
  1834. .map(|&h| crate::descriptor::heap(h as This))
  1835. .find(|h| !h.samplers())
  1836. else {
  1837. return;
  1838. };
  1839. let Some(host) = heap.host() else {
  1840. return;
  1841. };
  1842. let bake = bake && left > 0;
  1843. if bake && !first && bake_exact() {
  1844. let (writes, noted) = host.texture_news();
  1845. if !noted && BAKE_SERVED.load(Ordering::Relaxed) == writes + 1 {
  1846. return;
  1847. }
  1848. }
  1849. let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1;
  1850. if bake && n.is_power_of_two() {
  1851. let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
  1852. tracing::info!(
  1853. frame,
  1854. bakes = n,
  1855. queued_at_the_last_pass = slots,
  1856. due_at_the_last_pass = due,
  1857. uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
  1858. "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)"
  1859. );
  1860. }
  1861. let began = std::time::Instant::now();
  1862. PASS_BUDGET.set(Some(budget));
  1863. crate::texture::BAKING.set(bake && bake_exact());
  1864. self.heap_textures(list, heap, host);
  1865. crate::texture::BAKING.set(false);
  1866. PASS_BUDGET.set(None);
  1867. if bake {
  1868. BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
  1869. }
  1870. }
  1871. /// The queue's side of the card accounting line
  1872. /// (`crate::resource::card_accounting`, which says what the line
  1873. /// holds): the slots that are due, by what their texture has on the
  1874. /// card. Off unless `VICTORY_CARD_ACCOUNTING=1`; then at the first pass
  1875. /// that finds the card without room, and every five seconds after it.
  1876. /// Nothing is made, uploaded or counted as used here. For 18,000 due
  1877. /// slots: 18,000 looks at a title slot and at the texture it views, a
  1878. /// lock each, some milliseconds of the thread that records the frame.
  1879. fn card_accounting(
  1880. heap: &crate::descriptor::Heap,
  1881. host: &crate::descriptor::host::HostHeap,
  1882. frame: u64,
  1883. room: bool,
  1884. ) {
  1885. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1886. if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) {
  1887. return;
  1888. }
  1889. // When the next line is due (0: none yet, the card has had room).
  1890. static NEXT: AtomicU64 = AtomicU64::new(0);
  1891. let now = crate::host::now_ms().max(1);
  1892. let next = NEXT.load(Ordering::Relaxed);
  1893. // (With levels on demand the card may never be without room: the
  1894. // lines then start with the first texture made that way.)
  1895. let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0;
  1896. let due_now = if next == 0 { !room || by_level } else { now >= next };
  1897. if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() {
  1898. return;
  1899. }
  1900. // Due slots; of them uploaded before; of them viewing nothing the
  1901. // title fills; and the textures (each once) whose host copy is
  1902. // alive, with their bytes on the card.
  1903. let mut due = [0u64; 5];
  1904. // Textures (each once) that never had a host copy, and ones whose
  1905. // host copy was let go: where their memory is, and its bytes.
  1906. let (mut never, mut gone) = (Vec::new(), Vec::new());
  1907. let mut seen = std::collections::BTreeSet::new();
  1908. for (index, uploaded) in host.texture_slots_all_due(frame) {
  1909. due[0] += 1;
  1910. due[1] += u64::from(uploaded);
  1911. let state = match heap.handle(index).and_then(crate::descriptor::view) {
  1912. Some(View::Placed(false, resource, desc)) if resource[0] != 1 => {
  1913. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  1914. match crate::resource::placed_known(address, &resource) {
  1915. Some(texture) => crate::resource::copy_state(texture),
  1916. // No title texture was made for it: the pass never
  1917. // got as far as making one.
  1918. None => Some((0, crate::resource::placed_bytes(&resource).unwrap_or(0), address)),
  1919. }
  1920. }
  1921. Some(View::Shader(object, _)) if crate::resource::title_fills(object as This) => {
  1922. crate::resource::copy_state(object as This)
  1923. }
  1924. _ => None,
  1925. };
  1926. let Some((state, bytes, memory)) = state else {
  1927. due[2] += 1;
  1928. continue;
  1929. };
  1930. if !seen.insert(memory) {
  1931. continue;
  1932. }
  1933. match state {
  1934. 2 => {
  1935. due[3] += 1;
  1936. due[4] += bytes;
  1937. }
  1938. 1 => gone.push((memory, bytes)),
  1939. _ => never.push((memory, bytes)),
  1940. }
  1941. }
  1942. crate::resource::card_accounting(room, due, never, gone);
  1943. }
  1944. /// The texture side of [`State::heap_buffers`]: textures the title fills
  1945. /// itself (streamed pages, layout-library copies) whose views sit in the
  1946. /// view heap are created (placed textures have no host texture until
  1947. /// something reads them) and uploaded, as a table read would do, for
  1948. /// shaders that pick them by a computed index. Within a budget of bytes
  1949. /// per frame and in all; the rest waits for later lists and frames.
  1950. /// The most recently written slots first (`TextureQueue::due`); slots
  1951. /// draws read through tables are not in the queue.
  1952. /// shortcut: uploaded once, and again only when the title rewrites the
  1953. /// slot. A placed texture not all mapped yet is uploaded with what is
  1954. /// there and looked at again (1, 2, 4, ... frames later, at most about
  1955. /// a second): uploaded again when more of it is mapped. Pages mapped
  1956. /// in place of others, and contents changed with no descriptor write,
  1957. /// are missed (hook the page-mapping events for those).
  1958. /// `VICTORY_HEAP_TEXTURES=0` turns it off.
  1959. fn heap_textures(
  1960. &self,
  1961. list: &HostList,
  1962. heap: &crate::descriptor::Heap,
  1963. host: &crate::descriptor::host::HostHeap,
  1964. ) {
  1965. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1966. if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
  1967. return;
  1968. }
  1969. let memory = crate::host::host().and_then(|h| h.video_memory());
  1970. // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of
  1971. // textures (a scene's first minutes) then drains in fewer frames.
  1972. static PER_FRAME_MB: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
  1973. let asked = *PER_FRAME_MB.get_or_init(|| {
  1974. std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse::<u64>().ok())
  1975. });
  1976. let per_frame = match asked {
  1977. Some(mb) => mb << 20,
  1978. None => staging_budget_per_frame(memory.map(|[budget, ..]| budget)),
  1979. };
  1980. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1981. static SPENT: AtomicU64 = AtomicU64::new(0);
  1982. let frame = crate::frame::current();
  1983. if FRAME.swap(frame, Ordering::Relaxed) != frame {
  1984. SPENT.store(0, Ordering::Relaxed);
  1985. }
  1986. // No more of them are made while the card has no room
  1987. // (`resource::room`): by what is alive now, not by what was ever
  1988. // staged (4 GB in all, after which later textures stayed empty for
  1989. // the run). The ones nothing names any more are let go, which
  1990. // makes room again: so the slots are still looked at (the pass
  1991. // returned here, and a slot whose texture had been streamed out
  1992. // kept its host copy for as long as the card was full).
  1993. let mut room = crate::resource::room(memory);
  1994. // Bytes uploaded by this pass since the card was last asked
  1995. // whether it has room: asked again every 32 MiB (a pass may upload
  1996. // 192 MB and more, and one asking a pass let the queue run some
  1997. // 400 MB past its line while the world loaded: run 193).
  1998. let mut since_asked = 0u64;
  1999. if !room {
  2000. HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed);
  2001. once!("textures picked by index: the card has no room for more; they wait");
  2002. }
  2003. let mut refused = 0;
  2004. // Room again: the slots held back while the card was full are due
  2005. // now (`full_card_pass`).
  2006. if room {
  2007. host.texture_slots_room(frame);
  2008. }
  2009. // Slots whose texture's memory the runtime mapped, unmapped or
  2010. // wrote since the last pass are due again.
  2011. host.texture_slots_remapped(frame);
  2012. host.texture_slots_short(frame);
  2013. // The slots of textures whose first level with memory (levels on
  2014. // demand), or whose host copy for one with more levels, changed since
  2015. // the last pass are made again from it; those whose new view's upload
  2016. // has run are made from that.
  2017. host.texture_views_remade();
  2018. host.texture_slots_flip();
  2019. // And with room, the textures whose upload left a held level
  2020. // without the card's memory are uploaded again.
  2021. if room {
  2022. host.texture_slots_waiting(frame);
  2023. }
  2024. let baking = crate::texture::BAKING.get();
  2025. let (mut due, census) = host.texture_slots_due(frame, if baking { 1 << 16 } else { 4096 });
  2026. // (Those that are due later after all that are due.)
  2027. let on_time = due.len();
  2028. if baking {
  2029. let known: std::collections::HashSet<u32> = due.iter().map(|&(index, _)| index).collect();
  2030. static AHEAD: AtomicU64 = AtomicU64::new(u64::MAX);
  2031. let again = AHEAD.swap(frame, Ordering::Relaxed) == frame;
  2032. let (ahead, _) = host.texture_slots_due(frame + BAKE_AHEAD[usize::from(again)], 1 << 16);
  2033. due.extend(ahead.into_iter().filter(|(index, _)| !known.contains(index)));
  2034. }
  2035. HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed);
  2036. for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
  2037. count.store(now, Ordering::Relaxed);
  2038. }
  2039. // Where the card's memory is, and what the due slots would need
  2040. // (`VICTORY_CARD_ACCOUNTING=1`; a line when the card first has no
  2041. // room, and every five seconds after it).
  2042. Self::card_accounting(heap, host, frame, room);
  2043. // The frames in about four seconds, between 16 and 256: how long a
  2044. // slot with nothing to upload waits at most for its next look. In
  2045. // frames alone it was 120: four minutes at the opening cutscene's
  2046. // half a frame per second, while the title streams by the clock.
  2047. // (About a second before the runtime told of the memory it maps:
  2048. // the looks are now only for what that does not tell.)
  2049. static PASSED: AtomicU64 = AtomicU64::new(0);
  2050. let now = crate::host::now_ms();
  2051. let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1);
  2052. let most = (4000 / took).clamp(16, 256);
  2053. // What a table entry of a texture a shader samples says.
  2054. let sampled = UsedResource {
  2055. kind: ResourceType::Srv,
  2056. root: RootType::Table,
  2057. table_offset_dwords: 0,
  2058. lower_bound: 0,
  2059. stride: 0,
  2060. dwords: 8,
  2061. user_data: 0,
  2062. slot: 0,
  2063. };
  2064. // Also within a time per pass: the pass runs on a thread that
  2065. // records the frame, and making and staging 192 MB of textures took
  2066. // 1.6-2.2 s of each of the world's first twenty frames (run 20).
  2067. // The rest waits for the next frames, as it does past the bytes.
  2068. static SPAN_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  2069. let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| {
  2070. std::env::var("VICTORY_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250)
  2071. }));
  2072. // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black
  2073. // surfaces at 192 MB a frame) gets three times the bytes and the time until it
  2074. // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget.
  2075. static CATCHUP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2076. let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0"));
  2077. let (per_frame, span) = if catchup && on_time >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) };
  2078. // A run made early (`State::early_textures`) has a budget of its
  2079. // own: its bytes on top of what the frame has spent so far.
  2080. // (Not `most`: that is the longest wait between looks, used below.)
  2081. let (span, bytes_at_most) = match PASS_BUDGET.get() {
  2082. Some((ms, bytes)) => {
  2083. (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes))
  2084. }
  2085. None => (span, per_frame),
  2086. };
  2087. let began = std::time::Instant::now();
  2088. BAKE_SERVED.store(0, Ordering::Relaxed);
  2089. let mut served = true;
  2090. for (index, write) in due {
  2091. if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
  2092. served = false;
  2093. break;
  2094. }
  2095. // A placed texture whose memory is not mapped (not streamed in
  2096. // yet, or streamed out again: the heap keeps tens of thousands
  2097. // of such views) gets no host texture; looked at again soon (a
  2098. // title writes a texture's view before its pages are mapped,
  2099. // and the pass runs early in a frame). One of which some is
  2100. // mapped (a texture streaming in: its smaller mips lie at the
  2101. // start of its memory and arrive first) is uploaded with what
  2102. // is there, and again when more is. (It was uploaded again
  2103. // every 120 frames, changed or not; and asked by its first
  2104. // page alone, one whose first page is the one missing counted
  2105. // as not there.)
  2106. // A slot uploaded whole is looked at again a few times
  2107. // (`RECHECK_FRAMES`): the title writes a texture's view, and
  2108. // may fill the texture's memory itself only afterwards, with
  2109. // no descriptor write and nothing from the runtime to tell of
  2110. // it. The host copy then kept what the memory held at the
  2111. // first look for the rest of the run. The look reads 48 KiB;
  2112. // only a changed texture is uploaded again.
  2113. // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before.
  2114. // One found changed by such a look is looked at in the next frame
  2115. // again: the textures left that change unnoticed are ones the
  2116. // title paints all the time through another view of their pages
  2117. // (all their blocks are shown at other addresses too), and each
  2118. // was shown four frames late, over and over.
  2119. let mut again_in = RECHECK_FRAMES[0];
  2120. if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) {
  2121. if crate::texture::fingerprint(at, len) == print {
  2122. HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed);
  2123. match RECHECK_FRAMES.get(usize::from(looks) + 1) {
  2124. Some(wait) => {
  2125. host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded)
  2126. }
  2127. None => host.texture_slot_done(index, write, None),
  2128. }
  2129. continue;
  2130. }
  2131. if recheck_soon() {
  2132. again_in = 1;
  2133. }
  2134. let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed);
  2135. if n < 200 || n.is_multiple_of(1000) {
  2136. // Whether its pages are the title's at other addresses
  2137. // too: what is written there is told of there alone.
  2138. let elsewhere = crate::inplace::shown_elsewhere(at as usize & !0xffff, (at + len) as usize);
  2139. let first = heap.handle(index).and_then(crate::descriptor::view).map_or(0, |view| match view {
  2140. View::Placed(false, _, desc) => crate::resource::first_mip(&desc),
  2141. _ => 0,
  2142. });
  2143. tracing::warn!(
  2144. first_level = first,
  2145. blocks_shown_elsewhere = elsewhere.len(),
  2146. slot = index,
  2147. address = format_args!("{at:#x}"),
  2148. bytes = len,
  2149. frames_after_upload = frame.saturating_sub(uploaded),
  2150. looks,
  2151. changed = n + 1,
  2152. "a texture picked by index changed after its upload with nothing to tell of it: uploaded again"
  2153. );
  2154. }
  2155. }
  2156. let mut partly = None;
  2157. let mut there = None;
  2158. if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) {
  2159. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2160. let first = crate::resource::first_mip(&desc);
  2161. let len = crate::resource::placed_bytes_from(&resource, first).unwrap_or(1);
  2162. let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize);
  2163. if mapped == 0 {
  2164. HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed);
  2165. // Streamed out: what the slot showed is let go.
  2166. host.texture_slot_gone(index);
  2167. host.texture_slot_later(index, write, frame, most);
  2168. continue;
  2169. }
  2170. host.texture_slot_here(index);
  2171. there = Some(mapped);
  2172. if mapped < len {
  2173. if mapped <= host.texture_slot_mapped(index) {
  2174. HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed);
  2175. host.texture_slot_later(index, write, frame, most);
  2176. continue;
  2177. }
  2178. if !crate::texture::committed(address as *const u8, 1) {
  2179. HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed);
  2180. }
  2181. partly = Some(mapped);
  2182. }
  2183. }
  2184. // A texture object the host renders to or writes holds the
  2185. // host's own contents: nothing to bring up to date, and this
  2186. // pass is no use of it (its host copy is made when something
  2187. // uses it, and its slots then: `descriptor::make_waiting`).
  2188. if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view)
  2189. && crate::resource::buffer_bytes(object as This).is_none()
  2190. && !crate::resource::title_fills(object as This)
  2191. {
  2192. host.texture_slot_done(index, write, None);
  2193. continue;
  2194. }
  2195. // From here on a host texture is made: not without room. The
  2196. // slot stays due.
  2197. // Not so a slot already made from this very view: its host
  2198. // texture exists, and uploading it again takes none of the
  2199. // card's memory. It was refused all the same, so a texture the
  2200. // title filled after its first upload kept its empty host copy
  2201. // from the moment the card reached the line, which is the first
  2202. // world frame in eight launches of nine: the same slots were
  2203. // found changed again at every pass and never uploaded (run
  2204. // 179: 33,000 such findings), and the main character's face
  2205. // had its colour only in the launches that entered the world
  2206. // under the line. `VICTORY_REUPLOAD_WHEN_FULL=0`: refused, as
  2207. // before.
  2208. if !room {
  2209. let has_its_texture = reupload_when_full()
  2210. && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle));
  2211. if !has_its_texture {
  2212. refused += 1;
  2213. if full_card_pass() {
  2214. // Held back for the frames of about four seconds
  2215. // (`most`), or until the card has room; the pass
  2216. // goes on, within a count that bounds one pass.
  2217. host.texture_slot_held(index, write, frame + most);
  2218. if refused > 1024 {
  2219. break;
  2220. }
  2221. } else if refused > 256 {
  2222. break;
  2223. }
  2224. continue;
  2225. }
  2226. let n = HEAP_TEXTURES_REUPLOADED_FULL.fetch_add(1, Ordering::Relaxed) + 1;
  2227. if n == 1 || n.is_multiple_of(500) {
  2228. tracing::info!(
  2229. so_far = n,
  2230. slot = index,
  2231. "a texture already on the card is brought up to date although the card has no room for new ones"
  2232. );
  2233. }
  2234. }
  2235. // A slot that shows the texture by an earlier view of it (one
  2236. // from another level) goes on doing so until the upload of what
  2237. // the new one shows has run.
  2238. let shows_other = !baking
  2239. && crate::resource::held_only()
  2240. && heap.handle(index).is_some_and(|handle| host.texture_slot_shows_other(index, handle));
  2241. let view = heap.handle(index).and_then(|handle| {
  2242. if shows_other { crate::descriptor::view(handle) } else { host.mirror(index, handle, true) }
  2243. });
  2244. let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture);
  2245. let resource = match placed.as_ref().or(view.as_ref()) {
  2246. Some(&View::Shader(resource, _)) => resource as This,
  2247. _ => {
  2248. host.texture_slot_done(index, write, None);
  2249. continue;
  2250. }
  2251. };
  2252. let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written);
  2253. if !title_fills {
  2254. // a render target, a depth or unordered access texture: the host's own
  2255. host.texture_slot_done(index, write, None);
  2256. continue;
  2257. }
  2258. // A texture that has a staging buffer now is one draws read
  2259. // through a table: they upload it, and check it at every
  2260. // submission that samples it.
  2261. let tabled = crate::texture::is_staged(resource);
  2262. // The host copy holds these very bytes: nothing to upload.
  2263. let first = match (&placed, &view) {
  2264. (Some(_), Some(View::Placed(_, _, desc))) => crate::resource::first_mip(desc),
  2265. _ => 0,
  2266. };
  2267. let same = !tabled && crate::texture::unchanged(resource, first);
  2268. if same {
  2269. HEAP_TEXTURES_SAME.fetch_add(1, Ordering::Relaxed);
  2270. if shows_other && let Some(handle) = heap.handle(index) {
  2271. let _ = host.mirror(index, handle, true);
  2272. }
  2273. let again = partly.map(|mapped| (frame + 1, mapped));
  2274. let memory = if again.is_none() && heap_recheck() { crate::texture::title_span(resource, first) } else { None };
  2275. match memory {
  2276. Some((at, len)) => {
  2277. let print = crate::texture::fingerprint(at, len);
  2278. host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame);
  2279. }
  2280. None => host.texture_slot_done(index, write, again),
  2281. }
  2282. continue;
  2283. }
  2284. if let Some(view) = &view {
  2285. // (What was found mapped of it a moment ago is not asked
  2286. // again, unless the host copy may need more.)
  2287. crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)));
  2288. readable(list, sampled.kind, view);
  2289. crate::texture::PICKING.set(None);
  2290. }
  2291. if shows_other && let Some(handle) = heap.handle(index) {
  2292. host.texture_slot_flip(list, index, handle);
  2293. }
  2294. // A texture view the host refuses removes the device: name it.
  2295. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  2296. if !GONE.load(Ordering::Relaxed)
  2297. && let Some(why) = crate::descriptor::host::device_removed()
  2298. {
  2299. GONE.store(true, Ordering::Relaxed);
  2300. let text: String = format!("{view:?}").chars().take(300).collect();
  2301. tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
  2302. crate::host::log_removal_context();
  2303. return;
  2304. }
  2305. let (bytes, whole) = crate::texture::staged(resource, there.is_none()).unwrap_or((0, true));
  2306. // Not all of it there: looked at again next frame, and from
  2307. // then on as a slot with nothing new (a placed texture: until
  2308. // more of it is mapped; a texture object at an address the
  2309. // title mapped: again in 120 frames, as before).
  2310. let again = match partly {
  2311. Some(mapped) => Some((frame + 1, mapped)),
  2312. None => (!whole).then_some((frame + 120, 0)),
  2313. };
  2314. if again.is_some() {
  2315. HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed);
  2316. }
  2317. if tabled {
  2318. // Nothing was staged here, so nothing is counted or spent,
  2319. // and the staging buffer stays: taking it away made the
  2320. // next draw that reads the texture through a table stage,
  2321. // detile and upload all of it once more.
  2322. HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed);
  2323. host.texture_slot_done(index, write, again);
  2324. continue;
  2325. }
  2326. // Uploaded: the list holds the staging buffer until it has run;
  2327. // a table read, or the next look at a texture not all mapped
  2328. // yet, makes it anew. (Kept for those until now: every partly
  2329. // streamed texture of the heap held a staging buffer of its full
  2330. // size for good.)
  2331. let memory = if again.is_none() && heap_recheck() {
  2332. crate::texture::staged_memory(resource)
  2333. } else {
  2334. None
  2335. };
  2336. crate::texture::unstage(resource);
  2337. SPENT.fetch_add(bytes, Ordering::Relaxed);
  2338. since_asked += bytes;
  2339. if room && since_asked >= 32 << 20 {
  2340. since_asked = 0;
  2341. room = crate::resource::room(crate::host::host().and_then(|h| h.video_memory()));
  2342. }
  2343. HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed);
  2344. HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed);
  2345. match memory {
  2346. // Whole and uploaded: looked at again (see above).
  2347. Some((at, len)) => {
  2348. let print = crate::texture::fingerprint(at, len);
  2349. host.texture_slot_recheck(index, write, frame + again_in, (at, len), print, 0, frame);
  2350. }
  2351. None => host.texture_slot_done(index, write, again),
  2352. }
  2353. }
  2354. if baking && served {
  2355. BAKE_SERVED.store(host.texture_news().0 + 1, Ordering::Relaxed);
  2356. }
  2357. }
  2358. /// For the frame listing, after a dropped dispatch's line: its group
  2359. /// counts and the compute root arguments it was recorded with (root
  2360. /// constants as hex dwords, root views with the title buffer they
  2361. /// point into). A program that does not translate has no bindings to
  2362. /// list; these say which memory it would have read and written (the
  2363. /// ray-tracing structure builder passes its buffers this way).
  2364. #[cfg(feature = "diagnostics")]
  2365. fn list_dropped_roots(&self, groups: [u32; 3]) {
  2366. crate::capture::op(0, || {
  2367. use std::fmt::Write;
  2368. let [x, y, z] = groups;
  2369. let mut text = format!(" its roots ({x}x{y}x{z}):");
  2370. for (slot, root) in self.compute.iter().enumerate() {
  2371. match root {
  2372. Root::None => {}
  2373. Root::Table(a) => {
  2374. let _ = write!(text, " {slot}=table {a:#x}");
  2375. }
  2376. Root::Constants(v) => {
  2377. let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]);
  2378. }
  2379. Root::View(a) => {
  2380. let _ = write!(text, " {slot}=view {a:#x}");
  2381. match crate::shadow::extent(*a) {
  2382. Some((start, len)) => {
  2383. let _ = write!(text, " in buffer {start:#x}+{len:#x}");
  2384. }
  2385. None => text.push_str(" in no buffer"),
  2386. }
  2387. }
  2388. }
  2389. }
  2390. text
  2391. });
  2392. }
  2393. /// Runs a dispatch on the host.
  2394. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
  2395. // It may write the arguments a window holds clamped.
  2396. self.window = None;
  2397. #[cfg(feature = "diagnostics")]
  2398. if crate::pipeline::is_skipped(self.pipeline as This) {
  2399. DROPPED.fetch_add(1, Ordering::Relaxed);
  2400. crate::pipeline::note_drop(self.pipeline as This);
  2401. return;
  2402. }
  2403. // The ray-tracing structure builder's stages run all or none.
  2404. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
  2405. DROPPED.fetch_add(1, Ordering::Relaxed);
  2406. #[cfg(feature = "diagnostics")]
  2407. {
  2408. crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned());
  2409. self.list_dropped_roots([x, y, z]);
  2410. }
  2411. return;
  2412. }
  2413. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2414. once!(
  2415. pipeline = format_args!("{:#x}", self.pipeline),
  2416. "a dispatch without a host pipeline dropped"
  2417. );
  2418. DROPPED.fetch_add(1, Ordering::Relaxed);
  2419. #[cfg(feature = "diagnostics")]
  2420. {
  2421. crate::pipeline::note_drop(self.pipeline as This);
  2422. self.list_dropped_roots([x, y, z]);
  2423. }
  2424. return;
  2425. };
  2426. if !p.compute {
  2427. once!("a dispatch with a graphics pipeline");
  2428. return;
  2429. }
  2430. if !self.bind(list, p, true) {
  2431. DROPPED.fetch_add(1, Ordering::Relaxed);
  2432. // A stage of the structure builder that cannot be bound is a
  2433. // dropped stage: the others stop too.
  2434. if crate::pipeline::is_builder(self.pipeline as This) {
  2435. crate::pipeline::builder_rests("one of its dispatches could not be bound");
  2436. }
  2437. return;
  2438. }
  2439. #[cfg(feature = "diagnostics")]
  2440. list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
  2441. #[cfg(feature = "diagnostics")]
  2442. if crate::pipeline::is_builder(self.pipeline as This) {
  2443. crate::capture::op(list as *const _ as usize, || format!("builder {}", p.name));
  2444. self.list_dropped_roots([x, y, z]);
  2445. }
  2446. // SAFETY: an open list with everything set.
  2447. unsafe { list.list.Dispatch(x, y, z) };
  2448. self.buffers_written();
  2449. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  2450. }
  2451. /// What a draw or dispatch runs, for the device-removed report
  2452. /// (diagnostics): the pipeline, then per stage the user data it gets
  2453. /// (with the view at that heap index, if one is), the host addresses
  2454. /// of its root views and the views its tables name.
  2455. #[cfg(feature = "diagnostics")]
  2456. fn op_text(&self, kind: String, compute: bool) -> String {
  2457. use std::fmt::Write;
  2458. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2459. return kind;
  2460. };
  2461. let mut text = format!("{kind} {}", p.name);
  2462. // What it draws into (a dispatch writes through its views below).
  2463. if !compute {
  2464. let described = |t: usize| {
  2465. crate::resource::host_made(t as This).map(|r| {
  2466. // SAFETY: a live resource.
  2467. let d = unsafe { r.GetDesc() };
  2468. format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0)
  2469. })
  2470. };
  2471. let targets: Vec<String> = self.targets.iter().filter_map(|&t| described(t)).collect();
  2472. let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state);
  2473. // The title's scissor and viewport at this draw (the first of
  2474. // each): the title draws what it sees through a
  2475. // portal (a window, from inside a room) under the portal's
  2476. // rectangle, and the listing did not say which draws those are.
  2477. if let Some(r) = self.scissors.first() {
  2478. let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom);
  2479. }
  2480. if let Some(v) = self.viewports.first() {
  2481. let _ = write!(
  2482. text,
  2483. " viewport [{} {} {} {} depth {}..{}]",
  2484. v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth
  2485. );
  2486. }
  2487. }
  2488. let views = (self.heaps[0] != 0)
  2489. .then(|| crate::descriptor::heap(self.heaps[0] as This).host())
  2490. .flatten();
  2491. for stage in &p.stages {
  2492. let t = stage.translated();
  2493. let _ = write!(text, " | {}:", stage.shader.hash);
  2494. for u in &t.host.user_data {
  2495. let v = match u.root {
  2496. RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None),
  2497. _ => self.user_value(compute, u.slot, u.root, u.dword),
  2498. };
  2499. let _ = write!(text, " u{}={v:#x}", u.index);
  2500. let index = if u.root == RootType::Table { v / 32 } else { v };
  2501. if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
  2502. let _ = write!(text, " [heap {index}: {slot}]");
  2503. }
  2504. }
  2505. for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) {
  2506. if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
  2507. let host = crate::shadow::find(*address, 1)
  2508. .map(|s| (s.gpu(*address), s.left(*address)));
  2509. let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
  2510. }
  2511. }
  2512. }
  2513. let _ = write!(text, " tables {:?}", self.reads(compute));
  2514. if !compute && !list_slots().is_empty() {
  2515. text.push_str(&self.slots_text());
  2516. }
  2517. text
  2518. }
  2519. /// For the frame listing, after a draw whose shader `VICTORY_LIST_SLOTS`
  2520. /// names: the heap slots it will pick textures from by index, and what
  2521. /// the title and the host hold there (one `~slot` line each), with the
  2522. /// words they were read from (`~raw` lines, to decode offline what is
  2523. /// not decoded here).
  2524. ///
  2525. /// Where the slots are, for the title's character shaders
  2526. /// (`PS_DeferredPedTexturedNC`, from their native code): in the small
  2527. /// buffers and constants of the draw's own table (every word of those
  2528. /// that names a texture view gets a line); in the material record, at
  2529. /// the byte offset the draw's constants (table 1, dword 56) hold at
  2530. /// 0x1c, of the buffer at table 0, dword 160; and in the record at the
  2531. /// byte offset the second root constant holds of the buffer at table 0,
  2532. /// dword 688. A word that is a small number by chance and names a
  2533. /// texture gets a line too.
  2534. #[cfg(feature = "diagnostics")]
  2535. fn slots_text(&self) -> String {
  2536. use std::fmt::Write;
  2537. const MATERIALS: u32 = 160;
  2538. const GLOBAL: u32 = 688;
  2539. const DRAW_CONSTANTS: u32 = 56;
  2540. let wanted = list_slots();
  2541. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2542. return String::new();
  2543. };
  2544. let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str())))
  2545. else {
  2546. return String::new();
  2547. };
  2548. let Some(heap) = self
  2549. .heaps
  2550. .iter()
  2551. .filter(|&&h| h != 0)
  2552. .map(|&h| crate::descriptor::heap(h as This))
  2553. .find(|h| !h.samplers())
  2554. else {
  2555. return String::new();
  2556. };
  2557. let t = stage.translated();
  2558. let mut text = String::new();
  2559. let entry = |slot: u8, dwords: u32| -> Option<View> {
  2560. let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(slot)) else {
  2561. return None;
  2562. };
  2563. crate::descriptor::view(table + u64::from(dwords) * 4)
  2564. };
  2565. let mut material = None;
  2566. for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) {
  2567. let label = format!("s{}+{}", u.slot, u.table_offset_dwords);
  2568. let Some(view) = entry(u.slot, u.table_offset_dwords) else {
  2569. let _ = write!(text, "\n ~table {label} no view");
  2570. continue;
  2571. };
  2572. let range = match &view {
  2573. View::Constant(address, size) => Some((*address, u64::from(*size))),
  2574. other => crate::descriptor::host::buffer_range(other),
  2575. };
  2576. match range {
  2577. // A small buffer or constants: its words.
  2578. Some((address, len)) if len <= 2048 => {
  2579. Self::slot_words(&mut text, heap, &label, address, len as usize);
  2580. if u.slot == 1 && u.table_offset_dwords == DRAW_CONSTANTS && len >= 0x20 {
  2581. let mut word = [0u8; 4];
  2582. if crate::host::read_into((address + 0x1c) as *const u8, &mut word) {
  2583. material = Some(u32::from_le_bytes(word));
  2584. }
  2585. }
  2586. }
  2587. Some(_) => {}
  2588. // A texture read through the table: the title slot it sits in.
  2589. None => {
  2590. let Some(Root::Table(table)) = self.roots_ref(false).get(usize::from(u.slot)) else {
  2591. continue;
  2592. };
  2593. match heap.index(table + u64::from(u.table_offset_dwords) * 4) {
  2594. Some(index) => text.push_str(&Self::slot_line(heap, &format!("table:{label}"), 0, index)),
  2595. None => {
  2596. let _ = write!(text, "\n ~table {label} title=[{}]", view_state(Some(&view)));
  2597. }
  2598. }
  2599. }
  2600. }
  2601. }
  2602. let uses = |slot: u8, dwords: u32| {
  2603. t.used.iter().any(|u| u.root == RootType::Table && u.slot == slot && u.table_offset_dwords == dwords)
  2604. };
  2605. if let Some(at) = material
  2606. && uses(0, MATERIALS)
  2607. && let Some((base, len)) = entry(0, MATERIALS).as_ref().and_then(crate::descriptor::host::buffer_range)
  2608. {
  2609. let at = u64::from(at);
  2610. let _ = write!(text, "\n ~material record at {at:#x} of the buffer at {base:#x} bytes {len}");
  2611. if at + 64 <= len {
  2612. Self::slot_words(&mut text, heap, "M", base + at, 64);
  2613. }
  2614. if at + 1936 + 512 <= len {
  2615. Self::slot_words(&mut text, heap, "M+1936", base + at + 1936, 512);
  2616. }
  2617. }
  2618. if uses(0, GLOBAL)
  2619. && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot)
  2620. && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot))
  2621. && let Some(&at) = words.get(1)
  2622. && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range)
  2623. {
  2624. let at = u64::from(at);
  2625. let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}");
  2626. if at + 64 <= len {
  2627. Self::slot_words(&mut text, heap, "G", base + at, 64);
  2628. }
  2629. }
  2630. text
  2631. }
  2632. /// Up to 512 bytes of title memory at `address` as hex words (a `~raw`
  2633. /// line), and a `~slot` line for every word of them that names a
  2634. /// texture view in `heap`.
  2635. #[cfg(feature = "diagnostics")]
  2636. fn slot_words(text: &mut String, heap: &crate::descriptor::Heap, label: &str, address: u64, len: usize) {
  2637. use std::fmt::Write;
  2638. let mut bytes = vec![0u8; len.min(512) & !3];
  2639. if bytes.is_empty() || !crate::host::read_into(address as *const u8, &mut bytes) {
  2640. let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}: unreadable");
  2641. return;
  2642. }
  2643. let words: Vec<u32> =
  2644. bytes.chunks_exact(4).map(|w| u32::from_le_bytes([w[0], w[1], w[2], w[3]])).collect();
  2645. let _ = write!(text, "\n ~raw {label} at {address:#x} bytes {len}:");
  2646. for w in &words {
  2647. let _ = write!(text, " {w:08x}");
  2648. }
  2649. for (i, &index) in words.iter().enumerate() {
  2650. let names = index != 0
  2651. && heap
  2652. .handle(index)
  2653. .and_then(crate::descriptor::view)
  2654. .as_ref()
  2655. .is_some_and(crate::descriptor::host::is_texture_view);
  2656. if names {
  2657. text.push_str(&Self::slot_line(heap, label, i * 4, index));
  2658. }
  2659. }
  2660. }
  2661. /// One `~slot` line: where the slot number was read (`from`, byte
  2662. /// `at`), what the title's heap holds in slot `index` with the state
  2663. /// of that texture ([`view_state`]), what the host slot was made from,
  2664. /// and what the queue of textures picked by index knows of it.
  2665. #[cfg(feature = "diagnostics")]
  2666. fn slot_line(heap: &crate::descriptor::Heap, from: &str, at: usize, index: u32) -> String {
  2667. let title = heap.handle(index).and_then(crate::descriptor::view);
  2668. let host: String = heap
  2669. .host()
  2670. .and_then(|h| h.describe_slot(index))
  2671. .unwrap_or_else(|| "none".into())
  2672. .chars()
  2673. .take(90)
  2674. .collect();
  2675. let queue = match heap.host() {
  2676. Some(h) => h.texture_slot_state(index, crate::frame::current()),
  2677. None => "no host heap".into(),
  2678. };
  2679. format!(
  2680. "\n ~slot from={from}+{at:#x} slot={index} title=[{}] host=[{host}] queue=[{queue}]",
  2681. view_state(title.as_ref())
  2682. )
  2683. }
  2684. /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel:
  2685. /// the scissors before it (`on`), the title's after it.
  2686. fn mesh_scissor(&self, list: &HostList, on: bool) {
  2687. if mesh_test() != 2 {
  2688. return;
  2689. }
  2690. if on {
  2691. let one = RECT { left: 0, top: 0, right: 1, bottom: 1 };
  2692. crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]);
  2693. } else if !self.scissors.is_empty() {
  2694. crate::draw::scissors(list, &self.scissors);
  2695. }
  2696. }
  2697. /// Runs a mesh dispatch of `x` groups on the host (the title's mesh
  2698. /// programs are one-dimensional).
  2699. pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
  2700. self.window = None;
  2701. #[cfg(feature = "diagnostics")]
  2702. self.trace("mesh", x, 0);
  2703. let ran = mesh_test() != 1
  2704. && mesh_kept(self.pipeline)
  2705. && self.prepare_for(list, false, true)
  2706. && match list.list.cast::<ID3D12GraphicsCommandList6>() {
  2707. Ok(l6) => {
  2708. #[cfg(feature = "diagnostics")]
  2709. list.note_op(|| self.op_text(format!("mesh {x}"), false));
  2710. self.mesh_scissor(list, true);
  2711. #[cfg(feature = "diagnostics")]
  2712. if let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) {
  2713. list.ran_indirect(p.pso.as_raw() as usize, &p.name, crate::host::indirects::DIRECT, x, &self.user);
  2714. }
  2715. // (The host takes 65,535 groups in a dimension: more is
  2716. // undefined there.)
  2717. if x > 65_535 {
  2718. once!(x, "a mesh dispatch of more groups than the host takes: cut");
  2719. }
  2720. // SAFETY: an open list with everything set.
  2721. unsafe { l6.DispatchMesh(x.min(65_535), 1, 1) };
  2722. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  2723. self.mesh_scissor(list, false);
  2724. DRAWN.fetch_add(1, Ordering::Relaxed);
  2725. true
  2726. }
  2727. Err(_) => false,
  2728. };
  2729. if !ran {
  2730. DROPPED.fetch_add(1, Ordering::Relaxed);
  2731. #[cfg(feature = "diagnostics")]
  2732. dropped(self.pipeline);
  2733. }
  2734. }
  2735. /// The walls trace (`crate::host::walls_trace`): one log line per
  2736. /// frame with the draws of its main pass (four or more colour targets)
  2737. /// by scissor rectangle, and how often each of the title's culling
  2738. /// programs was dispatched. The title clips what it draws
  2739. /// through a window or door to that opening's rectangle while it holds
  2740. /// the camera to be in a room (run 182, frame 1529: 1,386 draws under
  2741. /// `531 0 1789 1337`); in a launch without the room's walls the same
  2742. /// shot has no such rectangle (run 187, frame 1414). The line shows
  2743. /// the frame in which that changes.
  2744. fn walls_census(&self, p: &HostPipeline, compute: bool) {
  2745. const CULL: [(&str, &str); 9] = [
  2746. ("55679a0547649d0b", "tree"),
  2747. ("89d08e561897d4e5", "tree_imposter"),
  2748. ("9209777e8face9dd", "grass"),
  2749. ("17af15c4015cb4b6", "prop"),
  2750. ("fdd56d97a806bcca", "prop_nocull"),
  2751. ("42f717f1b4d18e94", "simple"),
  2752. ("1c4b3c0547e3e6fa", "slod"),
  2753. ("9146291b38ea9ce1", "meshlet_args"),
  2754. ("42683eebec081520", "depth_pyramid_cpu_occlusion"),
  2755. ];
  2756. type Census = (u64, std::collections::BTreeMap<[i32; 4], u32>, [u32; 9]);
  2757. static CENSUS: std::sync::Mutex<Census> =
  2758. std::sync::Mutex::new((u64::MAX, std::collections::BTreeMap::new(), [0; 9]));
  2759. let frame = crate::frame::current();
  2760. let mut census = CENSUS.lock().unwrap_or_else(|e| e.into_inner());
  2761. if census.0 != frame {
  2762. let draws: u32 = census.1.values().sum();
  2763. if draws > 0 {
  2764. let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect();
  2765. rects.sort_unstable_by(|a, b| b.1.cmp(&a.1));
  2766. let scissors: Vec<String> = rects
  2767. .iter()
  2768. .take(5)
  2769. .map(|(r, n)| format!("{} {} {} {} x{n}", r[0], r[1], r[2], r[3]))
  2770. .collect();
  2771. let counts = census.2;
  2772. let culling: Vec<String> = CULL
  2773. .iter()
  2774. .zip(counts)
  2775. .filter(|(_, n)| *n > 0)
  2776. .map(|(c, n)| format!("{}={n}", c.1))
  2777. .collect();
  2778. tracing::info!(
  2779. frame = census.0,
  2780. main_pass_draws = draws,
  2781. rectangles = rects.len(),
  2782. scissors = ?scissors,
  2783. culling = ?culling,
  2784. "walls trace: the frame's main pass by scissor rectangle, and its culling dispatches"
  2785. );
  2786. }
  2787. census.0 = frame;
  2788. census.1.clear();
  2789. census.2 = [0; 9];
  2790. }
  2791. if compute {
  2792. for (i, c) in CULL.iter().enumerate() {
  2793. if p.stages.iter().any(|s| s.shader.hash.as_str() == c.0) {
  2794. census.2[i] += 1;
  2795. }
  2796. }
  2797. } else if self.targets.iter().filter(|&&t| t != 0).count() >= 4 {
  2798. let r = self.scissors.first().map_or([0; 4], |r| [r.left, r.top, r.right, r.bottom]);
  2799. *census.1.entry(r).or_insert(0) += 1;
  2800. }
  2801. }
  2802. fn roots_ref(&self, compute: bool) -> &Vec<Root> {
  2803. if compute {
  2804. &self.compute
  2805. } else {
  2806. &self.graphics
  2807. }
  2808. }
  2809. fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
  2810. let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  2811. return;
  2812. };
  2813. let handle = table + u64::from(u.table_offset_dwords) * 4;
  2814. let Some(heap) = self.heap_of(handle) else {
  2815. return;
  2816. };
  2817. let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
  2818. return;
  2819. };
  2820. if let Some(view) = host.mirror(index, handle, true) {
  2821. readable(list, u.kind, &view);
  2822. // Up to date by this draw: not the texture pass's to make.
  2823. if crate::descriptor::host::is_texture_view(&view) {
  2824. host.texture_slot_tabled(index, true);
  2825. } else {
  2826. host.slot_tabled(index);
  2827. }
  2828. }
  2829. }
  2830. /// The descriptors a shader reads through tables. Tables holding a
  2831. /// constant buffer are made afresh for the draw in dynamic slots, with
  2832. /// the constant data copied to upload memory when the list is
  2833. /// submitted: the host wants constant buffers 256-byte aligned, the
  2834. /// console only 16. Returns those tables' new byte offsets by root
  2835. /// parameter; the other tables' slots are made from the title's.
  2836. ///
  2837. /// Within a list, the same table holding the same descriptors is made
  2838. /// once: its constant data is copied at submission either way, and the
  2839. /// big tables the world binds would otherwise take hundreds of slots per
  2840. /// draw, wrapping the dynamic slots onto lists not yet submitted.
  2841. pub(crate) fn tables(
  2842. &mut self,
  2843. list: &HostList,
  2844. used: &[UsedResource],
  2845. indexed: &[RootIndexedView],
  2846. compute: bool,
  2847. ) -> Few<(u8, u32), 16> {
  2848. let tables = |u: &&UsedResource| u.root == RootType::Table;
  2849. let mut fresh: Few<u8, 16> = Few::default();
  2850. for u in used.iter().filter(tables).filter(|u| u.kind == ResourceType::Cbv) {
  2851. if !fresh.contains(&u.slot) {
  2852. fresh.push(u.slot);
  2853. }
  2854. }
  2855. // Tables reaching past a host heap smaller than the title's (the
  2856. // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the
  2857. // title's slots there have no host slot of their own.
  2858. for u in used.iter().filter(tables) {
  2859. if fresh.contains(&u.slot) {
  2860. continue;
  2861. }
  2862. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  2863. continue;
  2864. };
  2865. let end = table + u64::from(u.table_offset_dwords) * 4;
  2866. let Some(heap) = self.heap_of(table) else {
  2867. continue;
  2868. };
  2869. let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else {
  2870. continue;
  2871. };
  2872. if index >= host.count() {
  2873. fresh.push(u.slot);
  2874. }
  2875. }
  2876. fresh.sort_unstable();
  2877. for u in used.iter().filter(tables) {
  2878. if !fresh.contains(&u.slot) {
  2879. self.table_entry(list, u, compute);
  2880. }
  2881. }
  2882. let mut made = Few::default();
  2883. for &slot in fresh.iter() {
  2884. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
  2885. continue;
  2886. };
  2887. // (Their places among `used`.)
  2888. let mut places: Few<u16, 32> = Few::default();
  2889. for (i, _) in used.iter().enumerate().filter(|(_, u)| tables(u) && u.slot == slot) {
  2890. places.push(i as u16);
  2891. }
  2892. let entries = || places.iter().map(|&i| &used[usize::from(i)]);
  2893. let Some(heap) = self.heap_of(table) else {
  2894. continue;
  2895. };
  2896. if heap.samplers() || (table - heap.start) % 32 != 0 {
  2897. continue;
  2898. }
  2899. let Some(host) = heap.host() else {
  2900. continue;
  2901. };
  2902. let mut selected: Vec<u32> = indexed
  2903. .iter()
  2904. .filter(|index| index.table_slot == slot)
  2905. .map(|index| {
  2906. let constant = self.user_value(
  2907. compute,
  2908. index.constant_slot,
  2909. RootType::Constants,
  2910. index.constant_dword,
  2911. );
  2912. // The shader adds i32 byte offsets and shifts by 5.
  2913. index.byte_offset.wrapping_add(constant << index.shift) / 32
  2914. })
  2915. .collect();
  2916. selected.sort_unstable();
  2917. selected.dedup();
  2918. let n = entries()
  2919. .map(|u| u.table_offset_dwords / 8)
  2920. .chain(selected.last().copied())
  2921. .max()
  2922. .unwrap_or(0)
  2923. + 1;
  2924. let last = table.checked_add(u64::from(n - 1) * 32);
  2925. if n > crate::descriptor::host::DYNAMIC
  2926. || last.and_then(|handle| heap.index(handle)).is_none()
  2927. {
  2928. once!(slot, n, "fresh descriptor table exceeds the available span");
  2929. continue;
  2930. }
  2931. // The table and what its entries hold (record words).
  2932. let key = {
  2933. let mut h = RecordHash::default();
  2934. for k in 0..n {
  2935. let at = table + u64::from(k) * 32;
  2936. // SAFETY: a descriptor slot in title memory.
  2937. h.add(unsafe { (at as *const [u32; 3]).read_unaligned() });
  2938. }
  2939. (table, n, h.0)
  2940. };
  2941. // Who reads of it, and as what, as far as [`readable`] goes by it.
  2942. let reader = (used.as_ptr() as usize, used.len(), STORES.get(), TESTED_DEPTH.get().0);
  2943. if let Some(known) = self.fresh_tables.get_mut(&key) {
  2944. let first = known.first;
  2945. // This reader had it brought up to date, and nothing in the
  2946. // list changed since: nothing to do again.
  2947. let once = ready_once() && selected.is_empty() && entries().all(|u| u.kind != ResourceType::Uav);
  2948. if once
  2949. && known.epoch == list.epoch()
  2950. && let Some((_, depth)) = known.ready.iter().find(|(r, _)| *r == reader)
  2951. {
  2952. if *depth {
  2953. TESTED_DEPTH.set((reader.3, true));
  2954. }
  2955. made.push((slot, first * 32));
  2956. continue;
  2957. }
  2958. let depth_before = TESTED_DEPTH.get();
  2959. TESTED_DEPTH.set((depth_before.0, false));
  2960. for u in entries().filter(|u| u.kind != ResourceType::Cbv) {
  2961. let handle = table + u64::from(u.table_offset_dwords) * 4;
  2962. if let Some(view) = crate::descriptor::view(handle) {
  2963. readable(list, u.kind, &view);
  2964. }
  2965. }
  2966. for k in selected {
  2967. if entries().any(|u| u.table_offset_dwords / 8 == k) {
  2968. continue;
  2969. }
  2970. let handle = table + u64::from(k) * 32;
  2971. if let Some(view) = crate::descriptor::view(handle)
  2972. && let Some(kind) = view_kind(&view)
  2973. {
  2974. readable(list, kind, &view);
  2975. }
  2976. }
  2977. let depth = TESTED_DEPTH.get().1;
  2978. TESTED_DEPTH.set((depth_before.0, depth_before.1 || depth));
  2979. if once && let Some(known) = self.fresh_tables.get_mut(&key) {
  2980. // (The epoch as it is now: what this changed itself it
  2981. // need not do again.)
  2982. let epoch = list.epoch();
  2983. if known.epoch != epoch {
  2984. known.epoch = epoch;
  2985. known.ready.clear();
  2986. }
  2987. if known.ready.len() < 16 {
  2988. known.ready.push((reader, depth));
  2989. }
  2990. }
  2991. made.push((slot, first * 32));
  2992. continue;
  2993. }
  2994. let Some(first) = host.dynamic(n) else {
  2995. // No room: the draw must not run with the title's own
  2996. // offsets (slots never made for it); `bind` drops it.
  2997. made.push((slot, u32::MAX));
  2998. continue;
  2999. };
  3000. self.fresh_tables.insert(key, FreshTable { first, epoch: 0, ready: Vec::new() });
  3001. self.dynamic
  3002. .push((std::ptr::from_ref(heap) as usize, first, n));
  3003. // The title's own slots of this table: what the draw reads of
  3004. // them it brings up to date here, in the dynamic slots.
  3005. let title_first = heap.index(table).filter(|first| first + n <= host.count());
  3006. // They are such a table's, whatever they hold. (Of a big one,
  3007. // which may lie over slots shaders pick by index, only the ones
  3008. // the shader names.)
  3009. if let Some(title) = title_first {
  3010. for k in (0..n).filter(|&k| n <= 64 || entries().any(|u| u.table_offset_dwords / 8 == k)) {
  3011. host.slot_tabled(title + k);
  3012. }
  3013. }
  3014. let list_views = crate::descriptor::host::list_views();
  3015. if self.recording == 0 {
  3016. static NEXT: AtomicU64 = AtomicU64::new(1);
  3017. self.recording = NEXT.fetch_add(1, Ordering::Relaxed);
  3018. }
  3019. let recording = self.recording;
  3020. // The whole range: a shader may index past the entries its
  3021. // used-resource list names (descriptor arrays).
  3022. for k in 0..n {
  3023. let index = first + k;
  3024. // A view this list has made before: its descriptor copied,
  3025. // and nothing more if nothing changed in the list since.
  3026. if list_views
  3027. && let Some(words) = crate::descriptor::record_at(table + u64::from(k) * 32)
  3028. && let Some(mut listed) = host.make_listed(recording, words, index)
  3029. {
  3030. let kind = entries()
  3031. .find(|u| u.table_offset_dwords / 8 == k)
  3032. .map(|u| u.kind)
  3033. .or_else(|| selected.binary_search(&k).ok().and(listed.kind));
  3034. let was = (listed.ready, listed.tabled);
  3035. if let Some(kind) = kind {
  3036. let tested = TESTED_DEPTH.get();
  3037. if kind == ResourceType::Srv && listed.ready.0 == list.epoch() && listed.ready.1 == tested.0 {
  3038. if listed.ready.2 {
  3039. TESTED_DEPTH.set((tested.0, true));
  3040. }
  3041. } else if let Some(view) = crate::descriptor::host::listed_view(recording, words) {
  3042. TESTED_DEPTH.set((tested.0, false));
  3043. readable(list, kind, &view);
  3044. let depth = TESTED_DEPTH.get().1;
  3045. TESTED_DEPTH.set((tested.0, tested.1 || depth));
  3046. if kind == ResourceType::Srv {
  3047. listed.ready = (list.epoch(), tested.0, depth);
  3048. }
  3049. }
  3050. }
  3051. if let Some(title) = title_first
  3052. && listed.texture
  3053. && listed.tabled != Some((title + k, kind.is_some()))
  3054. {
  3055. listed.tabled = Some((title + k, kind.is_some()));
  3056. host.texture_slot_tabled(title + k, kind.is_some());
  3057. if kind.is_some() {
  3058. host.mirror(title + k, table + u64::from(k) * 32, true);
  3059. }
  3060. }
  3061. if was != (listed.ready, listed.tabled) {
  3062. crate::descriptor::host::note_listed(recording, words, listed);
  3063. }
  3064. continue;
  3065. }
  3066. let used = entries().find(|u| u.table_offset_dwords / 8 == k);
  3067. match crate::descriptor::view(table + u64::from(k) * 32) {
  3068. Some(View::Constant(address, size)) => {
  3069. let Some((buffer, gpu, to)) = list.scratch_held(u64::from(size)) else {
  3070. host.make_null(index);
  3071. continue;
  3072. };
  3073. let slot = (std::ptr::from_ref(heap) as usize, index);
  3074. list.defer_constants(to, address as *const u8, size as usize, slot);
  3075. host.constant_at(index, &buffer, gpu, size);
  3076. }
  3077. Some(view) => {
  3078. host.make_at(index, &view);
  3079. let kind = used.map(|u| u.kind).or_else(|| {
  3080. selected.binary_search(&k).ok().and_then(|_| view_kind(&view))
  3081. });
  3082. if let Some(kind) = kind {
  3083. readable(list, kind, &view);
  3084. }
  3085. // The title's slot is a table's: out of the queue
  3086. // of textures picked by index if the draw read it
  3087. // (its texture is up to date now), and made in
  3088. // place as the texture pass would have made it,
  3089. // for a shader that picks it by index all the same.
  3090. if let Some(title) = title_first
  3091. && crate::descriptor::host::is_texture_view(&view)
  3092. {
  3093. host.texture_slot_tabled(title + k, kind.is_some());
  3094. if kind.is_some() {
  3095. host.mirror(title + k, table + u64::from(k) * 32, true);
  3096. }
  3097. }
  3098. }
  3099. None => {
  3100. host.make_null(index);
  3101. if used.is_some() {
  3102. once!(slot, "a table entry without a view");
  3103. }
  3104. }
  3105. }
  3106. }
  3107. made.push((slot, first * 32));
  3108. }
  3109. made
  3110. }
  3111. /// The first draws, at debug level: what they bind and read
  3112. /// (diagnostics builds).
  3113. #[cfg(feature = "diagnostics")]
  3114. fn trace(&self, kind: &str, count: u32, first: u32) {
  3115. static TRACED: AtomicU64 = AtomicU64::new(0);
  3116. if !tracing::enabled!(tracing::Level::DEBUG) {
  3117. return;
  3118. }
  3119. let listed = crate::capture::listed(crate::queue::presented() + 1);
  3120. let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
  3121. let targets: Vec<String> = self
  3122. .targets
  3123. .iter()
  3124. .filter_map(|&t| crate::resource::host_made(t as This))
  3125. .map(|t| {
  3126. // SAFETY: a live resource.
  3127. let d = unsafe { t.GetDesc() };
  3128. format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
  3129. })
  3130. .collect();
  3131. let v = self.vertex[0];
  3132. let line = format!(
  3133. "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
  3134. self.topology,
  3135. self.pipeline,
  3136. v.address,
  3137. v.size,
  3138. v.stride,
  3139. self.reads(false)
  3140. );
  3141. if logged {
  3142. tracing::debug!("draw {line}");
  3143. }
  3144. let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
  3145. if frame.len() < 256 {
  3146. frame.push(line);
  3147. }
  3148. }
  3149. /// What a draw's shaders read, one line per used resource (diagnostics
  3150. /// builds).
  3151. #[cfg(feature = "diagnostics")]
  3152. fn reads(&self, compute: bool) -> Vec<String> {
  3153. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  3154. return vec!["no host pipeline".into()];
  3155. };
  3156. let mut out = Vec::new();
  3157. for stage in &p.stages {
  3158. let t = stage.translated();
  3159. for u in &t.used {
  3160. let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
  3161. (RootType::Table, Some(Root::Table(table))) => {
  3162. let handle = table + u64::from(u.table_offset_dwords) * 4;
  3163. describe(crate::descriptor::view(handle).as_ref())
  3164. }
  3165. (root, _) => format!("{root:?}"),
  3166. };
  3167. out.push(format!(
  3168. "{} {:?} s{}+{}: {what}",
  3169. stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
  3170. ));
  3171. }
  3172. }
  3173. out
  3174. }
  3175. pub(crate) fn draw(
  3176. &mut self,
  3177. list: &HostList,
  3178. vertices: u32,
  3179. instances: u32,
  3180. first: u32,
  3181. first_instance: u32,
  3182. ) {
  3183. self.window = None;
  3184. #[cfg(feature = "diagnostics")]
  3185. self.trace("draw", vertices, first);
  3186. let ready = self.prepare(list, false);
  3187. // A pipeline with the rectangle geometry stage draws the title's
  3188. // vertices as they are; any other gets its rectangles expanded.
  3189. let rects = self.topology == RECTANGLES && !self.completes_rects();
  3190. let ran = ready && (!rects || self.rectangles(list, vertices, first));
  3191. if ran {
  3192. // Rectangles were expanded into their own vertex buffers.
  3193. let (count, from) = if rects {
  3194. (vertices / 3 * 6, 0)
  3195. } else {
  3196. (vertices, first)
  3197. };
  3198. #[cfg(feature = "diagnostics")]
  3199. list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
  3200. // SAFETY: an open list with everything set.
  3201. unsafe {
  3202. list.list
  3203. .DrawInstanced(count, instances, from, first_instance)
  3204. };
  3205. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  3206. DRAWN.fetch_add(1, Ordering::Relaxed);
  3207. }
  3208. if !ran {
  3209. DROPPED.fetch_add(1, Ordering::Relaxed);
  3210. #[cfg(feature = "diagnostics")]
  3211. dropped(self.pipeline);
  3212. }
  3213. }
  3214. /// Whether the bound pipeline completes rectangles itself, in the
  3215. /// geometry stage rectangle pipelines get (`HostPipeline::rects`).
  3216. fn completes_rects(&self) -> bool {
  3217. crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects)
  3218. }
  3219. /// Binds vertex buffers holding the rectangles of vertices `first..first
  3220. /// + count` as triangles, made when the list is submitted.
  3221. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
  3222. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  3223. return false;
  3224. };
  3225. let rects = u64::from(count / 3);
  3226. for slot in 0..32 {
  3227. let elements: Vec<(u32, u32)> = p
  3228. .inputs
  3229. .iter()
  3230. .filter(|e| e.slot == slot && !e.per_instance)
  3231. .map(|e| (e.offset, e.format))
  3232. .collect();
  3233. if elements.is_empty() {
  3234. continue;
  3235. }
  3236. let v = self.vertex[slot as usize];
  3237. let stride = u64::from(v.stride);
  3238. let from = v.address + u64::from(first) * stride;
  3239. if v.address == 0
  3240. || stride == 0
  3241. || u64::from(first + count) * stride > u64::from(v.size)
  3242. || crate::shadow::find(from, rects * 3 * stride).is_none()
  3243. {
  3244. once!(slot, "rectangle vertices outside their buffer");
  3245. return false;
  3246. }
  3247. let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
  3248. return false;
  3249. };
  3250. let (from, to, stride) = (from as usize, to as usize, stride as usize);
  3251. let n = rects as usize;
  3252. list.defer_host_read(from, n * 3 * stride, move || {
  3253. // The vertices are read through the kernel, at submission; in
  3254. // place only if that fails, with no change of mapping under
  3255. // the read (see `crate::watch::title_memory_reading`): while
  3256. // the world streams a change is under way most of the time,
  3257. // and this is the thread that submits.
  3258. let mut read = vec![0u8; n * 3 * stride];
  3259. let held = (!crate::host::read_into(from as *const u8, &mut read)).then(crate::watch::title_memory_reading);
  3260. // SAFETY: the vertices lie in a title buffer (checked when
  3261. // recorded) and the scratch memory is the list's.
  3262. let (src, dst) = unsafe {
  3263. (
  3264. if held.is_some() { std::slice::from_raw_parts(from as *const u8, n * 3 * stride) } else { &read[..] },
  3265. std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
  3266. )
  3267. };
  3268. crate::primitive::expand_rects(src, dst, stride, &elements);
  3269. });
  3270. let view = D3D12_VERTEX_BUFFER_VIEW {
  3271. BufferLocation: gpu,
  3272. SizeInBytes: (rects * 6 * stride as u64) as u32,
  3273. StrideInBytes: v.stride,
  3274. };
  3275. // SAFETY: an open list; the view names live scratch memory.
  3276. unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
  3277. }
  3278. true
  3279. }
  3280. pub(crate) fn draw_indexed(
  3281. &mut self,
  3282. list: &HostList,
  3283. indices: u32,
  3284. instances: u32,
  3285. first: u32,
  3286. base: i32,
  3287. first_instance: u32,
  3288. ) {
  3289. self.window = None;
  3290. #[cfg(feature = "diagnostics")]
  3291. self.trace("indexed", indices, first);
  3292. // Indexed rectangles are drawn by the rectangle geometry stage
  3293. // alone (nothing expands them on the CPU).
  3294. let lost = self.topology == RECTANGLES && !self.completes_rects();
  3295. if lost {
  3296. once!("indexed rectangles not drawn");
  3297. }
  3298. let ran = !lost && self.prepare(list, true);
  3299. if ran {
  3300. #[cfg(feature = "diagnostics")]
  3301. list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
  3302. // SAFETY: an open list with everything set.
  3303. unsafe {
  3304. list.list
  3305. .DrawIndexedInstanced(indices, instances, first, base, first_instance)
  3306. };
  3307. self.drew(crate::pipeline::host_pipeline(self.pipeline as This));
  3308. DRAWN.fetch_add(1, Ordering::Relaxed);
  3309. }
  3310. if !ran {
  3311. DROPPED.fetch_add(1, Ordering::Relaxed);
  3312. #[cfg(feature = "diagnostics")]
  3313. dropped(self.pipeline);
  3314. }
  3315. }
  3316. }
  3317. impl State {
  3318. /// Shaders that can write buffers were recorded: arguments may be others
  3319. /// from here on.
  3320. fn buffers_written(&mut self) {
  3321. match &mut self.batch {
  3322. Some(batch) if batches() == 2 => batch.wrote = true,
  3323. batch => *batch = None,
  3324. }
  3325. }
  3326. /// A draw with the pipeline `p` was recorded (as [`State::buffers_written`]
  3327. /// if its shaders can store to buffers).
  3328. fn drew(&mut self, p: Option<&HostPipeline>) {
  3329. if p.is_none_or(|p| p.stages.iter().any(|stage| stage.translated().stores)) {
  3330. self.batch = None;
  3331. }
  3332. }
  3333. /// A buffer was copied to: what was clamped of it ahead is clamped anew.
  3334. pub(crate) fn copied(&mut self) {
  3335. self.window = None;
  3336. self.batch = None;
  3337. }
  3338. /// The title waits for earlier work (a barrier or a pipeline sync).
  3339. pub(crate) fn synced(&mut self) {
  3340. if self.batch.as_ref().is_some_and(|b| b.wrote) {
  3341. self.batch = None;
  3342. }
  3343. }
  3344. /// Where the clamped record of `kind` at `arguments` of the copy `args`
  3345. /// is, from the open batch or a new one ([`batches`]). `None` if it
  3346. /// cannot be clamped in one.
  3347. fn batched(
  3348. &mut self,
  3349. list: &HostList,
  3350. args: &std::sync::Arc<crate::shadow::Shadow>,
  3351. arguments: u64,
  3352. kind: u32,
  3353. ) -> Option<(ID3D12Resource, u64)> {
  3354. const BATCH_USE: usize = usize::MAX - 0x78;
  3355. const DISPATCH: u32 = 2;
  3356. // Another host list, or this one after its reset ([`windows`]).
  3357. if list.first_use(BATCH_USE) {
  3358. self.batch = None;
  3359. }
  3360. // A draw after dispatches waits for them.
  3361. if kind != DISPATCH {
  3362. self.synced();
  3363. }
  3364. let (id, offset) = (args.id(), args.offset(arguments));
  3365. if let Some(b) = &mut self.batch
  3366. && let Some(at) = b.table.place(id, offset, kind)
  3367. {
  3368. return Some((b.scratch.clone(), at));
  3369. }
  3370. self.batch = None;
  3371. let (mut table, scratch) = crate::indirect::open_batch(list, (id, &args.buffer), &argument_copies(args))?;
  3372. self.host_pipeline = 0;
  3373. self.host_roots[1] = 0;
  3374. let at = table.place(id, offset, kind)?;
  3375. self.batch = Some(Batch { table, scratch: scratch.clone(), wrote: false });
  3376. Some((scratch, at))
  3377. }
  3378. /// Indirect execution of a one-argument signature of `kind` (PC
  3379. /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
  3380. /// records `stride` bytes apart at title address `arguments`, and the
  3381. /// record count at `count` if the title gives one: the GPU reads them
  3382. /// from the buffer's host copy, where earlier dispatches may have
  3383. /// written them. False if it cannot run on the host.
  3384. pub(crate) fn execute_indirect(
  3385. &mut self,
  3386. list: &HostList,
  3387. (kind, stride, max): (u32, u32, u32),
  3388. arguments: u64,
  3389. count: Option<u64>,
  3390. ) -> bool {
  3391. // Skip before the argument clamp can mutate the indirect buffer.
  3392. #[cfg(feature = "diagnostics")]
  3393. if crate::pipeline::is_skipped(self.pipeline as This) {
  3394. crate::pipeline::note_drop(self.pipeline as This);
  3395. return false;
  3396. }
  3397. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
  3398. return false;
  3399. }
  3400. const DRAW: u32 = 0;
  3401. const INDEXED: u32 = 1;
  3402. const DISPATCH: u32 = 2;
  3403. const MESH: u32 = 10;
  3404. #[cfg(feature = "diagnostics")]
  3405. let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}"));
  3406. #[cfg(not(feature = "diagnostics"))]
  3407. let why = |_: &str| {};
  3408. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  3409. #[cfg(feature = "diagnostics")]
  3410. crate::pipeline::note_drop(self.pipeline as This);
  3411. return false;
  3412. };
  3413. // Indirect rectangles (the title's tiled lighting, 256
  3414. // indirect draws a frame, makes their corners from the vertex
  3415. // number) are completed by the pipeline's geometry stage: the
  3416. // arguments stay the title's, three vertices a rectangle. They
  3417. // cannot be expanded on the CPU, which does not know their count.
  3418. // shortcut: in a pipeline without that stage, a rectangle with no
  3419. // per-vertex inputs is drawn as its first triangle (three vertices,
  3420. // half of it), and one with vertex buffers is not drawn.
  3421. let made_rects = !p.rects
  3422. && kind == DRAW
  3423. && self.topology == RECTANGLES
  3424. && !p.inputs.iter().any(|e| !e.per_instance);
  3425. if made_rects {
  3426. once!("indirect rectangles without vertex inputs drawn as their first triangle");
  3427. }
  3428. let matches_kind = match kind {
  3429. DRAW | INDEXED => {
  3430. (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh
  3431. }
  3432. MESH => !p.compute && p.mesh,
  3433. DISPATCH => p.compute,
  3434. _ => false,
  3435. };
  3436. if !matches_kind {
  3437. why(&format!(
  3438. "pipeline mismatch (compute {}, mesh {}, topology {})",
  3439. p.compute, p.mesh, self.topology
  3440. ));
  3441. return false;
  3442. }
  3443. let len = u64::from(stride) * u64::from(max.max(1));
  3444. let Some(args) = crate::shadow::find_any(arguments, len) else {
  3445. why("arguments outside title buffers");
  3446. return false;
  3447. };
  3448. let counter = match count {
  3449. Some(at) => match crate::shadow::find_any(at, 4) {
  3450. Some(s) => Some((s, at)),
  3451. None => {
  3452. why("count outside title buffers");
  3453. return false;
  3454. }
  3455. },
  3456. None => None,
  3457. };
  3458. let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH)
  3459. .then(|| host_signature(kind, stride))
  3460. .flatten()
  3461. else {
  3462. why("no host signature");
  3463. return false;
  3464. };
  3465. if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) {
  3466. why("mesh draws are switched off (VICTORY_MESH_TEST=skip)");
  3467. return false;
  3468. }
  3469. // One record without a count: clamped in a batch (`batches`).
  3470. let batch = if batches() > 0 && max == 1 && count.is_none() {
  3471. args.refresh(list, arguments, len);
  3472. self.batched(list, &args, arguments, kind)
  3473. } else {
  3474. None
  3475. };
  3476. if batch.is_some() {
  3477. self.window = None;
  3478. }
  3479. // A window of records clamped in one pass (`windows`): for single
  3480. // records without a count buffer, drawn by shaders that store to no
  3481. // buffer. Anything else ends the window: it uses the scratch buffer
  3482. // or may write the arguments.
  3483. const WINDOW_USE: usize = usize::MAX - 0x77;
  3484. let offset = args.offset(arguments);
  3485. let windowed = windows()
  3486. && kind != DISPATCH
  3487. && max == 1
  3488. && count.is_none()
  3489. && !p.stages.iter().any(|stage| stage.translated().stores);
  3490. // Another host list (a new one after a cut, or this one after its
  3491. // reset) has another scratch buffer, or this one's with old bytes.
  3492. if !windowed || list.first_use(WINDOW_USE) {
  3493. self.window = None;
  3494. }
  3495. let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride;
  3496. let hit = self
  3497. .window
  3498. .as_ref()
  3499. .filter(|w| same(w) && offset >= w.base)
  3500. .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records))
  3501. .map(|w| (w.scratch.clone(), offset - w.base));
  3502. let (bounded, at) = match batch.or(hit) {
  3503. Some(hit) => hit,
  3504. None => {
  3505. // A record a short step after the last window's last one
  3506. // (the same step as that window's, if it had one): the
  3507. // title walks the buffer, so the ones that step apart
  3508. // after it are clamped with it.
  3509. let (step, records) = match &self.window {
  3510. Some(w) if windowed && same(w) => {
  3511. let last = w.base + u64::from(w.records - 1) * u64::from(w.step);
  3512. let step = offset.saturating_sub(last);
  3513. let walks = step >= u64::from(stride)
  3514. && step <= 256
  3515. && step % 4 == 0
  3516. && (w.records == 1 || step == u64::from(w.step));
  3517. if walks {
  3518. let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32;
  3519. (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1))
  3520. } else {
  3521. (stride, max)
  3522. }
  3523. }
  3524. _ => (stride, max),
  3525. };
  3526. args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records)));
  3527. if let Some((s, at)) = &counter {
  3528. s.refresh(list, *at, 4);
  3529. }
  3530. // Bounded first: the clamp binds a compute pipeline of its
  3531. // own and copies clamped active records into a scratch
  3532. // buffer at offset 0.
  3533. let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at)));
  3534. // More than the record asked for: a window clamped ahead,
  3535. // whose unfilled slots must not spend the list's budget.
  3536. let bounded = if windowed && records > 1 {
  3537. crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records))
  3538. } else {
  3539. crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records))
  3540. };
  3541. let Some(bounded) = bounded else {
  3542. self.window = None;
  3543. why("not bounded (no clamp, or arguments not 4-byte aligned)");
  3544. return false;
  3545. };
  3546. self.host_pipeline = 0;
  3547. self.host_roots[1] = 0;
  3548. self.window = windowed.then(|| Window {
  3549. copy: args.id(),
  3550. kind,
  3551. stride,
  3552. step,
  3553. base: offset,
  3554. records,
  3555. scratch: bounded.clone(),
  3556. });
  3557. (bounded, 0)
  3558. }
  3559. };
  3560. let ran = match kind {
  3561. DRAW | INDEXED => self.prepare(list, kind == INDEXED),
  3562. MESH => self.prepare_for(list, false, true),
  3563. DISPATCH => self.bind(list, p, true),
  3564. _ => false,
  3565. };
  3566. if !ran {
  3567. why("prepare failed");
  3568. return false;
  3569. }
  3570. #[cfg(feature = "diagnostics")]
  3571. list.note_op(|| {
  3572. self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
  3573. });
  3574. #[cfg(feature = "diagnostics")]
  3575. list.ran_indirect(p.pso.as_raw() as usize, &p.name, kind, max, &self.user);
  3576. if kind == MESH {
  3577. self.mesh_scissor(list, true);
  3578. }
  3579. // SAFETY: an open list with everything set; the scratch buffer and
  3580. // host copies are kept alive by the list, and the signature is cached.
  3581. unsafe {
  3582. list.list.ExecuteIndirect(
  3583. &signature,
  3584. max,
  3585. &bounded,
  3586. at,
  3587. counter.as_ref().map(|(s, _)| &s.buffer),
  3588. counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
  3589. )
  3590. };
  3591. if kind == MESH {
  3592. self.mesh_scissor(list, false);
  3593. }
  3594. if kind == DISPATCH {
  3595. self.buffers_written();
  3596. } else {
  3597. self.drew(Some(p));
  3598. }
  3599. // The scratch buffer stays readable as arguments: the next draw of
  3600. // the window reads it with no barrier, and the next clamp moves it
  3601. // back (`crate::indirect`).
  3602. if kind == DISPATCH {
  3603. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  3604. } else {
  3605. DRAWN.fetch_add(1, Ordering::Relaxed);
  3606. }
  3607. true
  3608. }
  3609. }
  3610. /// The host command signature for one argument of `kind` with records
  3611. /// `stride` bytes apart (no root arguments, so no root signature), made
  3612. /// once.
  3613. fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> {
  3614. static MADE: std::sync::Mutex<Vec<((u32, u32), ID3D12CommandSignature)>> =
  3615. std::sync::Mutex::new(Vec::new());
  3616. let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
  3617. if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) {
  3618. return Some(s.clone());
  3619. }
  3620. let argument = D3D12_INDIRECT_ARGUMENT_DESC {
  3621. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  3622. ..Default::default()
  3623. };
  3624. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  3625. ByteStride: stride,
  3626. NumArgumentDescs: 1,
  3627. pArgumentDescs: &argument,
  3628. NodeMask: 0,
  3629. };
  3630. let mut signature: Option<ID3D12CommandSignature> = None;
  3631. // SAFETY: a description of one argument; no root arguments.
  3632. let result = unsafe {
  3633. crate::host::host()?.device.CreateCommandSignature(
  3634. &desc,
  3635. None::<&ID3D12RootSignature>,
  3636. &mut signature,
  3637. )
  3638. };
  3639. if let Err(e) = result {
  3640. once!(error = %e, kind, stride, "host command signature refused");
  3641. return None;
  3642. }
  3643. let signature = signature?;
  3644. made.push(((kind, stride), signature.clone()));
  3645. Some(signature)
  3646. }
  3647. /// Gets what a shader reads or writes through a view ready: buffer data
  3648. /// copied, textures moved to the state they need.
  3649. pub(crate) fn view_kind(view: &View) -> Option<ResourceType> {
  3650. match view {
  3651. View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv),
  3652. View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav),
  3653. _ => None,
  3654. }
  3655. }
  3656. /// The host state a depth view needs of its texture: the read state if the
  3657. /// view writes no plane the format has (the title's read-only flags), else
  3658. /// the write state.
  3659. /// shortcut: whole textures have one state, so a view that writes one of
  3660. /// two planes counts as writing.
  3661. fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 {
  3662. // D16_UNORM and D32_FLOAT: depth formats without a stencil plane.
  3663. const ONE_PLANE: [i32; 2] = [55, 40];
  3664. let Some(desc) = desc else {
  3665. return DEPTH_WRITE;
  3666. };
  3667. let format = if desc.Format.0 == 0 {
  3668. // SAFETY: a live texture; a view without a format has its own.
  3669. unsafe { texture.GetDesc() }.Format.0
  3670. } else {
  3671. desc.Format.0
  3672. };
  3673. let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0;
  3674. if !ONE_PLANE.contains(&format) {
  3675. needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0;
  3676. }
  3677. if desc.Flags.0 & needed == needed {
  3678. DEPTH_READ
  3679. } else {
  3680. DEPTH_WRITE
  3681. }
  3682. }
  3683. /// A few things, up to `N` of them without memory of the heap: what a draw's
  3684. /// tables are gone through with, some six lists a stage.
  3685. struct Few<T, const N: usize> {
  3686. few: [T; N],
  3687. len: usize,
  3688. /// All of them, if they are more.
  3689. many: Vec<T>,
  3690. }
  3691. impl<T: Copy + Default, const N: usize> Default for Few<T, N> {
  3692. fn default() -> Self {
  3693. Few { few: [T::default(); N], len: 0, many: Vec::new() }
  3694. }
  3695. }
  3696. impl<T: Copy, const N: usize> Few<T, N> {
  3697. fn push(&mut self, what: T) {
  3698. if self.many.is_empty() && self.len < N {
  3699. self.few[self.len] = what;
  3700. self.len += 1;
  3701. } else {
  3702. if self.many.is_empty() {
  3703. self.many.extend_from_slice(&self.few);
  3704. }
  3705. self.many.push(what);
  3706. }
  3707. }
  3708. }
  3709. impl<T, const N: usize> std::ops::Deref for Few<T, N> {
  3710. type Target = [T];
  3711. fn deref(&self) -> &[T] {
  3712. if self.many.is_empty() { &self.few[..self.len] } else { &self.many }
  3713. }
  3714. }
  3715. impl<T, const N: usize> std::ops::DerefMut for Few<T, N> {
  3716. fn deref_mut(&mut self) -> &mut [T] {
  3717. if self.many.is_empty() { &mut self.few[..self.len] } else { &mut self.many }
  3718. }
  3719. }
  3720. /// A table made afresh in dynamic slots, in a list ([`State::tables`]).
  3721. struct FreshTable {
  3722. first: u32,
  3723. /// The list's epoch ([`HostList::epoch`]) at which all its entries that
  3724. /// these readers (a stage's list of what it reads, whether it stores, the
  3725. /// tested depth target) read were brought up to date, and whether that read the
  3726. /// tested depth target.
  3727. epoch: u64,
  3728. ready: Vec<((usize, usize, bool, usize), bool)>,
  3729. }
  3730. /// Whether a table a list reads again, with nothing changed in the list
  3731. /// since, is left as it is (`VICTORY_READY_ONCE=0`: every entry is gone
  3732. /// through again at every draw).
  3733. fn ready_once() -> bool {
  3734. crate::toggled!("VICTORY_READY_ONCE")
  3735. }
  3736. /// A hash of records' words: 64 bits, two multiplications a record. (The
  3737. /// standard library's took 3 % of the recording threads' time.)
  3738. #[derive(Default)]
  3739. struct RecordHash(u64);
  3740. impl RecordHash {
  3741. fn add(&mut self, [a, b, c]: [u32; 3]) {
  3742. let fold = |x: u64, y: u64| {
  3743. let p = u128::from(x) * u128::from(y);
  3744. p as u64 ^ (p >> 64) as u64
  3745. };
  3746. let words = u64::from(a) << 32 | u64::from(b);
  3747. let first = fold(self.0 ^ words ^ 0x2d35_8dcc_aa6c_78a5, 0x8bb8_4b93_962e_acc9 ^ u64::from(c));
  3748. self.0 = fold(first ^ 0x4b33_a62e_d433_d4a3, 0x4d5a_2da5_1de1_aa47 ^ self.0.rotate_left(23)) ^ first;
  3749. }
  3750. }
  3751. fn readable(list: &HostList, kind: ResourceType, view: &View) {
  3752. const UNORDERED_ACCESS: u32 = 0x8;
  3753. let placed = crate::descriptor::host::placed_texture(view);
  3754. let view = placed.as_ref().unwrap_or(view);
  3755. // Buffer views read title memory: their range is copied at submission;
  3756. // what shaders write through unordered access goes back to it after.
  3757. if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) {
  3758. shadow.refresh(list, address, len);
  3759. if kind == ResourceType::Uav {
  3760. // A shader that cannot store to buffers leaves the range as
  3761. // the title has it: nothing to find afterwards.
  3762. if STORES.get() || !write_skip() {
  3763. #[cfg(feature = "diagnostics")]
  3764. crate::host::wide_write(address, len, 0);
  3765. shadow.gpu_writes(list, address, len);
  3766. } else {
  3767. #[cfg(feature = "diagnostics")]
  3768. {
  3769. crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1);
  3770. crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len);
  3771. }
  3772. }
  3773. }
  3774. }
  3775. match (view, kind) {
  3776. (View::Shader(resource, _), ResourceType::Srv) => {
  3777. // A view the title placed, in another format, in the memory of
  3778. // a texture the host writes: that texture's texels, copied on
  3779. // the host (title memory does not have them).
  3780. let aliased = crate::resource::alias_of(*resource as This)
  3781. .is_some_and(|source| crate::texture::alias(list, *resource as This, source));
  3782. if !aliased
  3783. && let Some(t) = crate::resource::host_copy(*resource as This)
  3784. && t.flags() & 0x7 == 0
  3785. {
  3786. // (A texture the title writes: no target, depth or unordered
  3787. // access, `crate::texture::title_written`.)
  3788. // Of a texture the title placed, the levels the view shows.
  3789. let first = match (&placed, view) {
  3790. (Some(_), View::Shader(_, Some(desc))) => crate::resource::first_mip(desc),
  3791. _ => 0,
  3792. };
  3793. crate::texture::upload_from(list, *resource as This, first);
  3794. }
  3795. // A depth texture shaders also write: what they wrote, first.
  3796. list.twin_use(*resource as This, false, false);
  3797. // The depth target the draw only tests is read in both ways at
  3798. // once: both read states, which its preparation asks for too.
  3799. let (tested, _) = TESTED_DEPTH.get();
  3800. let state = if tested != 0 && tested == *resource {
  3801. TESTED_DEPTH.set((tested, true));
  3802. DEPTH_READ | SHADER_RESOURCE
  3803. } else {
  3804. SHADER_RESOURCE
  3805. };
  3806. crate::list::ensure_state(list, *resource as This, state);
  3807. #[cfg(feature = "diagnostics")]
  3808. if tracing::enabled!(tracing::Level::DEBUG)
  3809. && let Some(t) = crate::resource::host_resource(*resource as This)
  3810. {
  3811. // SAFETY: a live resource.
  3812. let d = unsafe { t.GetDesc() };
  3813. if d.Flags.0 & 7 == 0 {
  3814. tracing::debug!(
  3815. resource = format_args!("{resource:#x}"),
  3816. ?d,
  3817. "a shader reads a texture the title fills"
  3818. );
  3819. }
  3820. }
  3821. }
  3822. (View::Unordered(resource, _, _), ResourceType::Uav) => {
  3823. #[cfg(feature = "diagnostics")]
  3824. crate::capture::note_target(*resource as This);
  3825. // Unordered access to a depth texture is its colour twin's.
  3826. if !list.twin_use(*resource as This, true, true) {
  3827. crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
  3828. }
  3829. }
  3830. _ => {}
  3831. }
  3832. }
  3833. /// The pixel shaders whose draws get their slots listed
  3834. /// ([`State::slots_text`]): `VICTORY_LIST_SLOTS`, hash prefixes separated
  3835. /// by commas. None by default.
  3836. #[cfg(feature = "diagnostics")]
  3837. fn list_slots() -> &'static [String] {
  3838. static LIST: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
  3839. LIST.get_or_init(|| {
  3840. std::env::var("VICTORY_LIST_SLOTS")
  3841. .unwrap_or_default()
  3842. .split(',')
  3843. .map(|s| s.trim().to_ascii_lowercase())
  3844. .filter(|s| !s.is_empty())
  3845. .collect()
  3846. })
  3847. }
  3848. /// A fingerprint of the 4 KiB of title memory at `at` (FNV-1a, 64 bits; of
  3849. /// 4 KiB of zeros it is always the same value, which `slots.py` knows), or
  3850. /// "unreadable".
  3851. #[cfg(feature = "diagnostics")]
  3852. fn print_4k(at: u64) -> String {
  3853. let mut bytes = [0u8; 4096];
  3854. if at == 0 || !crate::host::read_into(at as *const u8, &mut bytes) {
  3855. return "unreadable".into();
  3856. }
  3857. let mut hash = 0xcbf2_9ce4_8422_2325_u64;
  3858. for b in bytes {
  3859. hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
  3860. }
  3861. format!("{hash:016x}")
  3862. }
  3863. /// The `bytes` of title memory at `at`: how many are mapped, and the
  3864. /// fingerprints of the first and the last 4 KiB (a texture's smallest
  3865. /// levels lie first, its largest last).
  3866. #[cfg(feature = "diagnostics")]
  3867. fn memory_state(at: u64, bytes: u64) -> String {
  3868. let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize);
  3869. let last = at + bytes.saturating_sub(4096);
  3870. format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last))
  3871. }
  3872. /// Title texture `this` for the frame listing: its size, whether it has a
  3873. /// host copy (not made here), its staging buffer's state, whether the host
  3874. /// copied into it, and its memory ([`memory_state`]).
  3875. #[cfg(feature = "diagnostics")]
  3876. fn texture_state(this: This) -> String {
  3877. let Some((at, desc)) = crate::resource::texture_memory(this) else {
  3878. return "not a texture".into();
  3879. };
  3880. // SAFETY: 56 bytes in the description's layout.
  3881. let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() };
  3882. let bytes = crate::resource::placed_bytes(&words).unwrap_or(0);
  3883. let staged = match crate::texture::staged_state(this) {
  3884. Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"),
  3885. None => "staged=no".into(),
  3886. };
  3887. format!(
  3888. "{}x{} f{} levels={} host_copy={} {staged} host_written={} title_fills={} {}",
  3889. u64::from(words[4]) | u64::from(words[5]) << 32,
  3890. words[6],
  3891. words[8],
  3892. words[7] >> 16,
  3893. crate::resource::host_made(this).is_some(),
  3894. crate::texture::host_wrote(this as usize),
  3895. crate::resource::title_fills(this),
  3896. memory_state(at as u64, bytes)
  3897. )
  3898. }
  3899. /// A view of the title's heap for the frame listing: a texture with its
  3900. /// state ([`texture_state`]; a placed one that has no resource yet with
  3901. /// its memory alone), anything else in a few words.
  3902. #[cfg(feature = "diagnostics")]
  3903. fn view_state(view: Option<&View>) -> String {
  3904. match view {
  3905. None => "no view".into(),
  3906. Some(View::Placed(false, r, d)) if r[0] != 1 => {
  3907. let address = u64::from(d[10]) | u64::from(d[11]) << 32;
  3908. let state = match crate::resource::texture_at_made(address, r) {
  3909. Some(this) => texture_state(this),
  3910. None => format!(
  3911. "{}x{} f{} levels={} resource=none {}",
  3912. u64::from(r[4]) | u64::from(r[5]) << 32,
  3913. r[6],
  3914. r[8],
  3915. r[7] >> 16,
  3916. memory_state(address, crate::resource::placed_bytes(r).unwrap_or(0))
  3917. ),
  3918. };
  3919. // (Last, so that readers of the older lines still find
  3920. // theirs: the level the view starts at, and how many it shows.)
  3921. format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32)
  3922. }
  3923. Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => {
  3924. format!(
  3925. "texture object {r:#x} view_format={} {} view_levels={}",
  3926. d.as_ref().map_or(0, |d| d[0]),
  3927. texture_state(*r as This),
  3928. d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32))
  3929. )
  3930. }
  3931. Some(v) => format!("{v:?}").chars().take(80).collect(),
  3932. }
  3933. }
  3934. /// A view in a few words (diagnostics builds).
  3935. #[cfg(feature = "diagnostics")]
  3936. fn describe(view: Option<&View>) -> String {
  3937. let texture = |r: This| {
  3938. crate::resource::host_made(r).map(|t| {
  3939. // SAFETY: a live resource.
  3940. let d = unsafe { t.GetDesc() };
  3941. format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0)
  3942. })
  3943. };
  3944. match view {
  3945. None => "no view".into(),
  3946. Some(v @ View::Shader(r, _)) => texture(*r as This)
  3947. .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
  3948. Some(v @ View::Unordered(r, ..)) => match texture(*r as This) {
  3949. Some(t) => format!("uav texture {t}"),
  3950. None => format!(
  3951. "uav resource {r:#x} buffer {:?}",
  3952. crate::descriptor::host::buffer_range(v)
  3953. ),
  3954. },
  3955. Some(View::Placed(u, r, d)) => format!(
  3956. "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
  3957. r[0],
  3958. u64::from(r[4]) | u64::from(r[5]) << 32,
  3959. r[6],
  3960. r[8],
  3961. r[11],
  3962. u64::from(d[10]) | u64::from(d[11]) << 32
  3963. ),
  3964. // The first four values, as a colour rectangle's constants are.
  3965. Some(View::Constant(address, size))
  3966. if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
  3967. {
  3968. // SAFETY: 16 committed bytes of title memory.
  3969. let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
  3970. format!("Constant({address:#x}, {size}) {v:?}")
  3971. }
  3972. Some(v) => format!("{v:?}").chars().take(60).collect(),
  3973. }
  3974. }
  3975. /// The console's own primitive topologies.
  3976. const TRIANGLE_FAN: u32 = 6;
  3977. const RECTANGLES: u32 = 17;
  3978. const LINE_LOOP: u32 = 18;
  3979. const QUADS: u32 = 19;
  3980. const QUAD_STRIP: u32 = 20;
  3981. /// Fixed-function state, straight onto the host list.
  3982. pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  3983. // SAFETY: an open list.
  3984. unsafe { list.list.RSSetViewports(viewports) };
  3985. }
  3986. pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
  3987. // SAFETY: an open list.
  3988. unsafe { list.list.RSSetScissorRects(rects) };
  3989. }
  3990. pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
  3991. // SAFETY: an open list.
  3992. unsafe { list.list.OMSetBlendFactor(factor) };
  3993. }
  3994. pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
  3995. #[cfg(feature = "diagnostics")]
  3996. crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}"));
  3997. // SAFETY: an open list.
  3998. unsafe { list.list.OMSetStencilRef(reference) };
  3999. }
  4000. pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) {
  4001. #[cfg(feature = "diagnostics")]
  4002. crate::capture::op(std::ptr::from_ref(list) as usize, || {
  4003. format!("DEPTH BOUNDS {min}..{max}")
  4004. });
  4005. if crate::host::host().is_some_and(|h| h.depth_bounds())
  4006. && let Ok(l1) = list.list.cast::<ID3D12GraphicsCommandList1>()
  4007. {
  4008. // SAFETY: an open list on a device that supports depth bounds.
  4009. unsafe { l1.OMSetDepthBounds(min, max) };
  4010. }
  4011. }
  4012. /// Per-frame texture staging byte budget scaled from the adapter's local VRAM
  4013. /// budget (`None` keeps the 192 MiB 12 GiB baseline).
  4014. fn staging_budget_per_frame(vram_budget: Option<u64>) -> u64 {
  4015. const GIB: u64 = 1 << 30;
  4016. const MIB: u64 = 1 << 20;
  4017. match vram_budget {
  4018. Some(budget) if budget <= 6 * GIB => 96 * MIB,
  4019. Some(budget) if budget >= 20 * GIB => 384 * MIB,
  4020. Some(budget) if budget > 12 * GIB => 256 * MIB,
  4021. _ => 192 * MIB,
  4022. }
  4023. }
  4024. #[cfg(test)]
  4025. mod tests {
  4026. use super::staging_budget_per_frame;
  4027. #[test]
  4028. fn staging_budget_scales_with_vram_budget() {
  4029. const GIB: u64 = 1 << 30;
  4030. const MIB: u64 = 1 << 20;
  4031. assert_eq!(staging_budget_per_frame(None), 192 * MIB);
  4032. assert_eq!(staging_budget_per_frame(Some(4 * GIB)), 96 * MIB);
  4033. assert_eq!(staging_budget_per_frame(Some(6 * GIB)), 96 * MIB);
  4034. assert_eq!(staging_budget_per_frame(Some(8 * GIB)), 192 * MIB);
  4035. assert_eq!(staging_budget_per_frame(Some(12 * GIB)), 192 * MIB);
  4036. assert_eq!(staging_budget_per_frame(Some(13 * GIB)), 256 * MIB);
  4037. assert_eq!(staging_budget_per_frame(Some(14 * GIB)), 256 * MIB);
  4038. assert_eq!(staging_budget_per_frame(Some(16 * GIB)), 256 * MIB);
  4039. assert_eq!(staging_budget_per_frame(Some(20 * GIB)), 384 * MIB);
  4040. assert_eq!(staging_budget_per_frame(Some(24 * GIB)), 384 * MIB);
  4041. assert_eq!(staging_budget_per_frame(Some(32 * GIB)), 384 * MIB);
  4042. }
  4043. }
  4044. #[cfg(test)]
  4045. mod record_hash_tests {
  4046. use super::{Few, RecordHash};
  4047. #[test]
  4048. fn a_few_things_are_kept_in_order_however_many() {
  4049. for n in 0..10u32 {
  4050. let mut few: Few<u32, 4> = Few::default();
  4051. (0..n).for_each(|i| few.push(n - i));
  4052. assert_eq!(few.to_vec(), (0..n).map(|i| n - i).collect::<Vec<_>>());
  4053. few.sort_unstable();
  4054. assert_eq!(few.to_vec(), (1..=n).collect::<Vec<_>>());
  4055. }
  4056. }
  4057. #[test]
  4058. fn records_that_differ_hash_apart() {
  4059. let of = |records: &[[u32; 3]]| {
  4060. let mut h = RecordHash::default();
  4061. records.iter().for_each(|r| h.add(*r));
  4062. h.0
  4063. };
  4064. let mut seen = std::collections::HashSet::new();
  4065. // One record, one word or two of it different; runs of zeros; order.
  4066. for a in 0..64u32 {
  4067. for b in 0..64u32 {
  4068. for c in [0, 1, 0x8000_0000, u32::MAX] {
  4069. assert!(seen.insert(of(&[[a, b, c]])));
  4070. assert!(seen.insert(of(&[[1, 2, 3], [a, b, c]])));
  4071. assert!(seen.insert(of(&[[a, b, c], [1, 2, 3], [0, 0, 0]])));
  4072. }
  4073. }
  4074. }
  4075. assert!(seen.insert(of(&[])));
  4076. // (One record of zeros is among the above.)
  4077. let zeros: Vec<u64> = (2..100).map(|n| of(&vec![[0; 3]; n])).collect();
  4078. assert!(zeros.iter().all(|h| seen.insert(*h)));
  4079. }
  4080. }