draw.rs 197 KB

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