draw.rs 176 KB

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