draw.rs 166 KB

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