draw.rs 129 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949
  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. /// What one title list has set, and what its host list was last given.
  173. #[derive(Default)]
  174. pub(crate) struct State {
  175. pipeline: usize,
  176. /// View heap, sampler heap.
  177. heaps: [usize; 2],
  178. graphics: Vec<Root>,
  179. compute: Vec<Root>,
  180. vertex: [VertexView; 32],
  181. index: IndexView,
  182. /// Bound render target and depth resources, for their host states.
  183. targets: Vec<usize>,
  184. depth: usize,
  185. /// The host state the bound depth view needs ([`depth_state`]).
  186. depth_state: u32,
  187. /// The title's primitive topology (the host's may differ).
  188. topology: u32,
  189. /// What the title set that goes straight onto the host list, kept for
  190. /// the host list that continues this one after a cut ([`State::replay`]):
  191. /// whether a topology was set, the render target and depth handles, the
  192. /// viewports, the scissors, the blend factor and the stencil reference.
  193. topology_set: bool,
  194. target_handles: Vec<u64>,
  195. depth_handle: u64,
  196. targets_set: bool,
  197. viewports: Vec<D3D12_VIEWPORT>,
  198. scissors: Vec<RECT>,
  199. blend: Option<[f32; 4]>,
  200. stencil: Option<u32>,
  201. depth_bounds: Option<[f32; 2]>,
  202. /// The indirect records clamped last, if later draws may still read
  203. /// them ([`windows`]).
  204. window: Option<Window>,
  205. /// What the host list has: pipeline, root signature, heaps.
  206. host_pipeline: usize,
  207. /// Graphics, compute.
  208. host_roots: [usize; 2],
  209. host_heaps: [usize; 2],
  210. /// Tables made afresh in this list: (table, slot count, contents) → first
  211. /// dynamic slot.
  212. fresh_tables: std::collections::HashMap<(u64, u32, u64), u32>,
  213. /// The dynamic slots the list holds: title heap, first, count; given
  214. /// back when the list has run, is reset or released.
  215. dynamic: Vec<(usize, u32, u32)>,
  216. /// Root SRVs bound as one-view tables in this list: (title heap, title
  217. /// address; 0 for none) → dynamic slot, and the host copy the slot
  218. /// shows: later draws of the list bring that one up to date, whatever
  219. /// copy the address would find by then (`shadow.rs` `tails`).
  220. root_srv_slots: std::collections::HashMap<(usize, u64), RootSlot>,
  221. /// Root UAVs bound as one-view tables in this list, likewise.
  222. root_uav_slots: std::collections::HashMap<(usize, u64), RootSlot>,
  223. /// The list ran and its dynamic slots were given back.
  224. tables_gone: bool,
  225. }
  226. impl Drop for State {
  227. fn drop(&mut self) {
  228. for &(heap, first, n) in &self.dynamic {
  229. crate::descriptor::release_dynamic(heap, first, n);
  230. }
  231. }
  232. }
  233. impl State {
  234. /// The list's submission has run (submissions are waited for): the
  235. /// dynamic slots its tables were made in are given back, not kept
  236. /// until the title resets the list. A frame of the opening cutscene
  237. /// asks for 12,500 tables; held until the resets they ran the 131,072
  238. /// slots out, and up to 4,900 draws a frame went without their tables.
  239. /// shortcut: a list the title runs a second time without a reset then
  240. /// reads slots others may have taken (logged once).
  241. pub(crate) fn tables_done(&mut self) {
  242. if self.tables_gone && self.dynamic.is_empty() {
  243. return;
  244. }
  245. if self.tables_gone {
  246. static ONCE: std::sync::Once = std::sync::Once::new();
  247. ONCE.call_once(|| tracing::warn!("a list ran again after its descriptor tables were given back"));
  248. }
  249. for (heap, first, n) in self.dynamic.drain(..) {
  250. crate::descriptor::release_dynamic(heap, first, n);
  251. }
  252. self.fresh_tables.clear();
  253. self.root_srv_slots.clear();
  254. self.root_uav_slots.clear();
  255. self.tables_gone = true;
  256. }
  257. }
  258. /// An experiment on the title's scissor rectangles (`VICTORY_SCISSOR_TEST=full`):
  259. /// they are all widened to the whole target. The title's room at
  260. /// the start of the prologue lost its walls in five runs of seven, and in
  261. /// those runs the player's body and the world outside were cut by one
  262. /// rectangle around the window (run 85, frame 2046): one run with this on
  263. /// says whether the walls are drawn and cut away by such a rectangle, or
  264. /// not drawn at all. Off by default: a rectangle the title sets is part of
  265. /// its picture.
  266. fn scissor_test() -> bool {
  267. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  268. *ON.get_or_init(|| std::env::var("VICTORY_SCISSOR_TEST").as_deref() == Ok("full"))
  269. }
  270. /// An experiment on mesh draws (`VICTORY_MESH_TEST`): 1 for `skip` (none
  271. /// is issued), 2 for `scissor` (each runs its shaders but rasterises one
  272. /// pixel), 0 otherwise. It tells a card hung by a mesh shader from one hung
  273. /// by what the shader's triangles cover.
  274. fn mesh_test() -> u8 {
  275. static ON: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
  276. *ON.get_or_init(|| match std::env::var("VICTORY_MESH_TEST").as_deref() {
  277. Ok("skip") => 1,
  278. Ok("scissor") => 2,
  279. _ => 0,
  280. })
  281. }
  282. /// `VICTORY_MESH_TEST=keep:<hex digits>[:<hex digits>]`: only the mesh
  283. /// draws whose mesh shader's hash ends in one of the first digits (and
  284. /// whose digit before it is one of the second, if given) are issued: a
  285. /// search for the shaders that stop the card.
  286. fn mesh_kept(pipeline: usize) -> bool {
  287. static KEEP: std::sync::OnceLock<Option<(String, String)>> = std::sync::OnceLock::new();
  288. let Some((last, before)) = KEEP.get_or_init(|| {
  289. let value = std::env::var("VICTORY_MESH_TEST").ok()?;
  290. let mut parts = value.strip_prefix("keep:")?.split(':');
  291. Some((parts.next()?.to_owned(), parts.next().unwrap_or("").to_owned()))
  292. }) else {
  293. return true;
  294. };
  295. let Some(p) = crate::pipeline::host_pipeline(pipeline as This) else {
  296. return true;
  297. };
  298. let Some(at) = p.name.find("mesh ") else {
  299. return true;
  300. };
  301. let hash = p.name[at + 5..].as_bytes();
  302. if hash.len() < 16 {
  303. return true;
  304. }
  305. last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14]))
  306. }
  307. /// Draws recorded on the host GPU since the last frame line.
  308. static DRAWN: AtomicU64 = AtomicU64::new(0);
  309. /// Draws run on the host so far.
  310. pub(crate) fn drawn() -> u64 {
  311. DRAWN.load(Ordering::Relaxed)
  312. }
  313. /// The draws traced since the last present (diagnostics builds, with
  314. /// debug logging for this module): logged when the frame comes out black.
  315. #[cfg(feature = "diagnostics")]
  316. static FRAME: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
  317. /// The draws traced since the last call.
  318. #[cfg(feature = "diagnostics")]
  319. pub(crate) fn take_frame() -> Vec<String> {
  320. std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
  321. }
  322. /// Draws, mesh dispatches and dispatches recorded but not run on the host
  323. /// (no host pipeline) since the last call.
  324. pub(crate) fn take_dropped() -> u64 {
  325. DROPPED.swap(0, Ordering::Relaxed)
  326. }
  327. /// A root SRV's dynamic slot in a list, and the host copy it shows.
  328. type RootSlot = (u32, Option<std::sync::Arc<crate::shadow::Shadow>>);
  329. /// Buffer views of the heap whose slot showed another host buffer than
  330. /// the copy the pass brought up to date for them, since the start
  331. /// (diagnostics; for the memory line). It stays 0 while the pass and the
  332. /// slots agree; with `VICTORY_VIEW_EXTENT=0` it counts the views that were
  333. /// read stale.
  334. #[cfg(feature = "diagnostics")]
  335. pub(crate) static HEAP_VIEWS_ELSEWHERE: AtomicU64 = AtomicU64::new(0);
  336. /// Passes over the view heap's buffer views for shaders that pick them by
  337. /// index ([`State::heap_buffers`]), and the microseconds they took.
  338. pub(crate) static HEAP_BUFFER_PASSES: AtomicU64 = AtomicU64::new(0);
  339. pub(crate) static HEAP_BUFFER_MICROS: AtomicU64 = AtomicU64::new(0);
  340. /// Textures brought up to date for shaders that pick them by index
  341. /// ([`State::heap_textures`]), the bytes of their memory, and the slots
  342. /// still waiting.
  343. pub(crate) static HEAP_TEXTURES: AtomicU64 = AtomicU64::new(0);
  344. pub(crate) static HEAP_TEXTURE_BYTES: AtomicU64 = AtomicU64::new(0);
  345. pub(crate) static HEAP_TEXTURES_WAITING: AtomicU64 = AtomicU64::new(0);
  346. /// Passes that made no texture because the card had no room
  347. /// (`crate::resource::room`), for the memory line.
  348. pub(crate) static HEAP_TEXTURES_FULL: AtomicU64 = AtomicU64::new(0);
  349. /// Frames after a whole upload of a texture picked by index at which its
  350. /// memory is looked at again, each counted from the look before.
  351. const RECHECK_FRAMES: [u64; 5] = [4, 12, 40, 120, 400];
  352. /// Looks at uploaded textures picked by index that found the memory as it
  353. /// was, and that found it changed (uploaded again), since the start.
  354. pub(crate) static HEAP_TEXTURES_RECHECKED: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
  355. /// Whether textures picked by index are looked at again after their upload
  356. /// (`VICTORY_HEAP_RECHECK=0`: no).
  357. fn heap_recheck() -> bool {
  358. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  359. *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_RECHECK").is_none_or(|v| v != "0"))
  360. }
  361. /// Times a placed texture's slot was passed over because its memory is not
  362. /// mapped.
  363. pub(crate) static HEAP_TEXTURES_AWAY: AtomicU64 = AtomicU64::new(0);
  364. /// Slots the pass found up to date already: their texture is uploaded by
  365. /// the draws that read it through a table (it has a staging buffer).
  366. pub(crate) static HEAP_TEXTURES_TABLED: AtomicU64 = AtomicU64::new(0);
  367. /// The queue of textures picked by index at the last pass
  368. /// (`TextureQueue::census`): slots in it, due, waiting for their memory,
  369. /// uploaded in part, and the frames the oldest due one has waited.
  370. pub(crate) static HEAP_TEXTURES_QUEUE: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
  371. /// Since the start: looks at a slot uploaded in part that found no more of
  372. /// its memory mapped; uploads of textures not all mapped; and of those,
  373. /// the ones whose first page was not there (asked by the first page alone,
  374. /// as before, they counted as not there at all).
  375. pub(crate) static HEAP_TEXTURES_PARTLY: [AtomicU64; 3] = [const { AtomicU64::new(0) }; 3];
  376. static DROPPED: AtomicU64 = AtomicU64::new(0);
  377. /// Marks the last traced draw as not run on the host.
  378. #[cfg(feature = "diagnostics")]
  379. fn dropped(pipeline: usize) {
  380. crate::pipeline::note_drop(pipeline as This);
  381. if let Some(last) = FRAME.lock().unwrap_or_else(|e| e.into_inner()).last_mut() {
  382. last.push_str(" DROPPED");
  383. }
  384. }
  385. /// Dispatches run on the host so far.
  386. static DISPATCHED: AtomicU64 = AtomicU64::new(0);
  387. pub(crate) fn dispatched() -> u64 {
  388. DISPATCHED.load(Ordering::Relaxed)
  389. }
  390. /// The host address of a root view: its buffer's host copy, or for a
  391. /// constant buffer not 256-byte aligned there (the console needs 16) a
  392. /// copy in upload memory.
  393. /// shortcut: a root view has no size; constant buffers are taken as 64 KiB
  394. /// (cut at their buffer's end), other views as all that is left of their
  395. /// buffer. (They were taken as 1 MiB: 1,452 of the 2,021 mesh vertex
  396. /// streams of a cutscene frame reach further, and what lay past the first
  397. /// megabyte was never brought up to date - meshes without bodies, exploded
  398. /// triangles. `VICTORY_ROOT_VIEW_MB` sets a limit again.)
  399. fn root_view(list: &HostList, address: u64, srv: bool) -> Option<u64> {
  400. static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  401. let limit = *LIMIT.get_or_init(|| {
  402. std::env::var("VICTORY_ROOT_VIEW_MB")
  403. .ok()
  404. .and_then(|v| v.parse::<u64>().ok())
  405. .map_or(u64::MAX, |mb| mb << 20)
  406. });
  407. let shadow = crate::shadow::find(address, 1)?;
  408. let len = shadow
  409. .left(address)
  410. .min(if srv { limit } else { 1 << 16 });
  411. let gpu = shadow.gpu(address);
  412. if srv || gpu % 256 == 0 {
  413. shadow.refresh(list, address, len);
  414. return Some(gpu);
  415. }
  416. let (gpu, to) = list.scratch(len)?;
  417. list.defer_fill(to, address as *const u8, len as usize);
  418. Some(gpu)
  419. }
  420. macro_rules! once {
  421. ($($arg:tt)*) => {{
  422. static ONCE: std::sync::Once = std::sync::Once::new();
  423. ONCE.call_once(|| tracing::warn!($($arg)*));
  424. }};
  425. }
  426. fn set(roots: &mut Vec<Root>, slot: u32, root: Root) {
  427. let slot = slot as usize;
  428. if roots.len() <= slot {
  429. roots.resize(slot + 1, Root::None);
  430. }
  431. roots[slot] = root;
  432. }
  433. impl State {
  434. pub(crate) fn reset(&mut self, pipeline: This) {
  435. *self = State::default();
  436. self.pipeline = pipeline as usize;
  437. }
  438. /// The title's topology; console-only ones become host lists (see
  439. /// [`crate::primitive`]).
  440. pub(crate) fn set_topology(&mut self, list: &HostList, topology: u32) {
  441. self.topology = topology;
  442. self.topology_set = true;
  443. let host = match topology {
  444. RECTANGLES => 4,
  445. TRIANGLE_FAN | LINE_LOOP | QUADS | QUAD_STRIP => {
  446. once!(topology, "console topology drawn as a triangle list");
  447. 4
  448. }
  449. t => t,
  450. };
  451. // SAFETY: an open list.
  452. unsafe {
  453. list.list
  454. .IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(host as i32))
  455. };
  456. }
  457. pub(crate) fn set_pipeline(&mut self, pipeline: This) {
  458. self.pipeline = pipeline as usize;
  459. }
  460. pub(crate) fn set_heaps(&mut self, heaps: &[This]) {
  461. self.heaps = [0; 2];
  462. for &h in heaps {
  463. if !h.is_null() {
  464. let samplers = crate::descriptor::heap(h).samplers();
  465. self.heaps[usize::from(samplers)] = h as usize;
  466. }
  467. }
  468. }
  469. fn roots(&mut self, compute: bool) -> &mut Vec<Root> {
  470. if compute {
  471. &mut self.compute
  472. } else {
  473. &mut self.graphics
  474. }
  475. }
  476. pub(crate) fn set_table(&mut self, compute: bool, slot: u32, handle: u64) {
  477. set(self.roots(compute), slot, Root::Table(handle));
  478. }
  479. pub(crate) fn set_view(&mut self, compute: bool, slot: u32, address: u64) {
  480. set(self.roots(compute), slot, Root::View(address));
  481. }
  482. pub(crate) fn set_constants(&mut self, compute: bool, slot: u32, values: &[u32], offset: u32) {
  483. let roots = self.roots(compute);
  484. let s = slot as usize;
  485. if !matches!(roots.get(s), Some(Root::Constants(_))) {
  486. set(roots, slot, Root::Constants(Vec::new()));
  487. }
  488. if let Root::Constants(c) = &mut roots[s] {
  489. let end = offset as usize + values.len();
  490. if c.len() < end {
  491. c.resize(end, 0);
  492. }
  493. c[offset as usize..end].copy_from_slice(values);
  494. }
  495. }
  496. pub(crate) fn set_vertex_buffers(&mut self, start: u32, views: &[VertexView]) {
  497. for (i, v) in views.iter().enumerate() {
  498. if let Some(slot) = self.vertex.get_mut(start as usize + i) {
  499. *slot = *v;
  500. }
  501. }
  502. }
  503. pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) {
  504. for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) {
  505. *slot = VertexView::default();
  506. }
  507. }
  508. pub(crate) fn set_index_buffer(&mut self, view: Option<&IndexView>) {
  509. self.index = view.copied().unwrap_or_default();
  510. }
  511. /// Render targets and depth, set on the host list at once.
  512. pub(crate) fn set_targets(&mut self, list: &HostList, handles: &[u64], depth: u64) {
  513. let Some(host) = crate::host::host() else {
  514. return;
  515. };
  516. self.target_handles.clear();
  517. self.target_handles.extend_from_slice(handles);
  518. self.depth_handle = depth;
  519. self.targets_set = true;
  520. self.targets.clear();
  521. let mut rtvs = Vec::new();
  522. for &h in handles {
  523. let Some(record) = crate::descriptor::rtv_record(h) else {
  524. once!(
  525. handle = format_args!("{h:#x}"),
  526. "render target without a recorded view"
  527. );
  528. continue;
  529. };
  530. let Some(texture) = crate::resource::host_resource(record.resource) else {
  531. // A typed null view (or a target without a host copy) still
  532. // takes its slot: left out, the next live target would move
  533. // into it and the pixel shader's outputs reach the wrong
  534. // targets.
  535. // shortcut: a view without a description or a format has no
  536. // null view to stand for it and is left out, as before.
  537. let null = record
  538. .desc()
  539. .filter(|d| d.Format.0 != 0 && d.ViewDimension.0 != 0);
  540. if let Some(desc) = null {
  541. rtvs.push(host.rtv(None, Some(&desc)));
  542. }
  543. continue;
  544. };
  545. self.targets.push(record.resource as usize);
  546. #[cfg(feature = "diagnostics")]
  547. crate::capture::note_target(record.resource);
  548. rtvs.push(host.rtv(Some(texture), record.desc().as_ref()));
  549. }
  550. self.depth = 0;
  551. self.depth_state = DEPTH_WRITE;
  552. let dsv = crate::descriptor::dsv_record(depth).and_then(|record| {
  553. let texture = crate::resource::host_resource(record.resource)?;
  554. self.depth = record.resource as usize;
  555. self.depth_state = depth_state(texture, record.depth_desc().as_ref());
  556. if crate::resource::depth_and_unordered(record.resource) {
  557. crate::resource::DEPTH_UNORDERED[1].fetch_add(1, Ordering::Relaxed);
  558. }
  559. #[cfg(feature = "diagnostics")]
  560. crate::capture::note_target(record.resource);
  561. Some(host.dsv(texture, record.depth_desc().as_ref()))
  562. });
  563. // SAFETY: an open list; the views were just made.
  564. unsafe {
  565. list.list.OMSetRenderTargets(
  566. rtvs.len() as u32,
  567. (!rtvs.is_empty()).then_some(rtvs.as_ptr()),
  568. false,
  569. dsv.as_ref().map(std::ptr::from_ref),
  570. )
  571. };
  572. }
  573. /// Viewports, scissors, the blend factor and the stencil reference: set
  574. /// on the host list at once, and kept for [`State::replay`].
  575. pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  576. self.viewports.clear();
  577. self.viewports.extend_from_slice(viewports);
  578. crate::draw::viewports(list, viewports);
  579. }
  580. pub(crate) fn set_scissors(&mut self, list: &HostList, rects: &[RECT]) {
  581. self.scissors.clear();
  582. self.scissors.extend_from_slice(rects);
  583. if scissor_test() {
  584. // The experiment: every rectangle the title sets is widened to
  585. // the largest target there is, so nothing is cut by one. What
  586. // the listing shows (`op_text`) stays the title's own.
  587. let full = RECT {
  588. left: 0,
  589. top: 0,
  590. right: 16384,
  591. bottom: 16384,
  592. };
  593. crate::draw::scissors(list, &vec![full; rects.len()]);
  594. return;
  595. }
  596. crate::draw::scissors(list, rects);
  597. }
  598. pub(crate) fn set_blend_factor(&mut self, list: &HostList, factor: Option<&[f32; 4]>) {
  599. self.blend = factor.copied();
  600. crate::draw::blend_factor(list, factor);
  601. }
  602. pub(crate) fn set_stencil_ref(&mut self, list: &HostList, reference: u32) {
  603. self.stencil = Some(reference);
  604. crate::draw::stencil_ref(list, reference);
  605. }
  606. pub(crate) fn set_depth_bounds(&mut self, list: &HostList, min: f32, max: f32) {
  607. self.depth_bounds = Some([min, max]);
  608. crate::draw::depth_bounds(list, min, max);
  609. }
  610. /// `list` is a new host list that continues the title's list (it was
  611. /// cut at a wait for a memory value, `crate::list::cut`): a new host
  612. /// list has nothing set, so what the title set so far is set again.
  613. /// The pipeline, the root signatures and the heaps are set by the next
  614. /// draw or dispatch (`bind`, which is told here that the host list has
  615. /// none); root arguments, vertex and index buffers are set by every
  616. /// draw anyway. The dynamic descriptor slots and the tables made in
  617. /// them stay: the parts before the cut have not run yet, and they are
  618. /// given back when the title's list is reset.
  619. /// shortcut: the render target views are made again from the handles'
  620. /// descriptors as they are now, not as they were when the title set
  621. /// the targets (a descriptor rewritten in between names another view).
  622. pub(crate) fn replay(&mut self, list: &HostList) {
  623. self.host_pipeline = 0;
  624. self.host_roots = [0; 2];
  625. self.host_heaps = [0; 2];
  626. if self.topology_set {
  627. self.set_topology(list, self.topology);
  628. }
  629. if self.targets_set {
  630. let handles = std::mem::take(&mut self.target_handles);
  631. self.set_targets(list, &handles, self.depth_handle);
  632. }
  633. if !self.viewports.is_empty() {
  634. crate::draw::viewports(list, &self.viewports);
  635. }
  636. if !self.scissors.is_empty() {
  637. let rects = std::mem::take(&mut self.scissors);
  638. self.set_scissors(list, &rects);
  639. }
  640. if let Some(factor) = self.blend {
  641. crate::draw::blend_factor(list, Some(&factor));
  642. }
  643. if let Some(reference) = self.stencil {
  644. crate::draw::stencil_ref(list, reference);
  645. }
  646. if let Some([min, max]) = self.depth_bounds {
  647. crate::draw::depth_bounds(list, min, max);
  648. }
  649. }
  650. /// The user-data value of a root argument, as translated shaders read
  651. /// it: a table's byte offset in its heap, a constant's value.
  652. fn user_value(&self, compute: bool, slot: u8, root: RootType, dword: u32) -> u32 {
  653. match (self.roots_ref(compute).get(usize::from(slot)), root) {
  654. (Some(Root::Table(handle)), RootType::Table) => match self.heap_of(*handle) {
  655. Some(heap) => (handle - heap.start) as u32,
  656. None => {
  657. once!(
  658. handle = format_args!("{handle:#x}"),
  659. "descriptor table outside the bound heaps"
  660. );
  661. 0
  662. }
  663. },
  664. (Some(Root::Constants(c)), RootType::Constants) => {
  665. c.get(dword as usize).copied().unwrap_or(0)
  666. }
  667. // The host's own ([`Self::host_word`]): no root argument.
  668. (_, RootType::Other(_)) => 0,
  669. _ => {
  670. once!(
  671. slot,
  672. ?root,
  673. "a shader reads a root argument the title did not set"
  674. );
  675. 0
  676. }
  677. }
  678. }
  679. /// A user-data dword the host computes for a translated shader
  680. /// (`victory_shader::emit::USER_MEMORY_BASE`, `USER_VIEW_ADDRESS`).
  681. fn host_word(
  682. &self,
  683. compute: bool,
  684. kind: u32,
  685. slot: u8,
  686. dword: u32,
  687. memory: Option<&crate::memory::Ready>,
  688. ) -> u32 {
  689. use victory_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS};
  690. if kind == USER_MEMORY_BASE {
  691. return memory.map_or(0, |m| m.base);
  692. }
  693. if kind == USER_VIEW_BIAS {
  694. // The view begins on 16 bytes of the copy the address finds
  695. // (`root_uav`, `root_srv_table`).
  696. // shortcut: found again here, not taken from the list's slot.
  697. return match self.roots_ref(compute).get(usize::from(slot)) {
  698. Some(&Root::View(address)) => crate::shadow::find(address, 1).map_or(0, |s| {
  699. // SAFETY: a live buffer.
  700. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  701. ((s.gpu(address) - base) & 15) as u32
  702. }),
  703. _ => 0,
  704. };
  705. }
  706. if kind != USER_VIEW_ADDRESS && kind != USER_VIEW_ADDRESS + 1 {
  707. once!(kind, "a shader reads a host value this build does not know");
  708. return 0;
  709. }
  710. // The title address of the buffer view at that dword of the table.
  711. let address = match self.roots_ref(compute).get(usize::from(slot)) {
  712. Some(&Root::Table(table)) => crate::descriptor::view(table + u64::from(dword) * 4)
  713. .and_then(|view| crate::descriptor::host::buffer_range(&view))
  714. .map_or(0, |range| range.0),
  715. _ => 0,
  716. };
  717. if address == 0 {
  718. once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0");
  719. }
  720. if kind == USER_VIEW_ADDRESS {
  721. address as u32
  722. } else {
  723. (address >> 32) as u32
  724. }
  725. }
  726. /// For a shader that reads title memory by address
  727. /// ([`crate::memory`]): its directory, fault notes and view slots,
  728. /// with the pages of the root views the list has set made ready.
  729. fn memory_ready(&self, list: &HostList, compute: bool, writes: bool) -> Option<crate::memory::Ready> {
  730. let heap = match self.heaps[0] {
  731. 0 => None,
  732. h => crate::descriptor::heap(h as This).host(),
  733. }?;
  734. let (mut addresses, mut constants) = (Vec::new(), Vec::new());
  735. for root in self.roots_ref(compute) {
  736. match root {
  737. Root::View(address) => addresses.push(*address),
  738. Root::Constants(values) => constants.extend_from_slice(values),
  739. _ => {}
  740. }
  741. }
  742. crate::memory::ready(list, heap, &addresses, &constants, writes)
  743. }
  744. /// The bound heap holding `handle`.
  745. fn heap_of(&self, handle: u64) -> Option<&'static crate::descriptor::Heap> {
  746. self.heaps
  747. .iter()
  748. .filter(|&&h| h != 0)
  749. .map(|&h| crate::descriptor::heap(h as This))
  750. .find(|h| h.index(handle).is_some())
  751. }
  752. /// Brings the host list up to date for a draw; false if the draw cannot
  753. /// run on the host.
  754. fn prepare(&mut self, list: &HostList, indexed: bool) -> bool {
  755. self.prepare_for(list, indexed, false)
  756. }
  757. /// As [`State::prepare`], for draws (`mesh` false) or mesh dispatches.
  758. fn prepare_for(&mut self, list: &HostList, indexed: bool, mesh: bool) -> bool {
  759. #[cfg(feature = "diagnostics")]
  760. if crate::pipeline::is_skipped(self.pipeline as This) {
  761. return false;
  762. }
  763. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  764. return false;
  765. };
  766. if p.compute || p.mesh != mesh {
  767. once!(mesh, "a draw or mesh dispatch with another kind of pipeline");
  768. return false;
  769. }
  770. if p.rects && self.topology != RECTANGLES {
  771. // Its geometry stage would turn each triangle into a rectangle.
  772. once!("a rectangle pipeline drawn with another topology");
  773. }
  774. if !self.bind(list, p, false) {
  775. return false;
  776. }
  777. let l = &list.list;
  778. // Vertex buffers the input layout reads.
  779. let mut views = [D3D12_VERTEX_BUFFER_VIEW::default(); 32];
  780. let mut count = 0;
  781. for (slot, (view, &v)) in views.iter_mut().zip(&self.vertex).enumerate() {
  782. if p.slots & 1 << slot == 0 {
  783. continue;
  784. }
  785. count = slot + 1;
  786. if v.address == 0 || v.size == 0 {
  787. continue;
  788. }
  789. let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
  790. continue;
  791. };
  792. shadow.refresh(list, v.address, u64::from(v.size));
  793. *view = D3D12_VERTEX_BUFFER_VIEW {
  794. BufferLocation: shadow.gpu(v.address),
  795. SizeInBytes: v.size,
  796. StrideInBytes: v.stride,
  797. };
  798. }
  799. // SAFETY: an open list; the views name live host buffers.
  800. unsafe {
  801. if count > 0 {
  802. l.IASetVertexBuffers(0, Some(&views[..count]));
  803. }
  804. }
  805. if indexed {
  806. let v = self.index;
  807. let Some(shadow) = crate::shadow::find_any(v.address, u64::from(v.size)) else {
  808. return false;
  809. };
  810. shadow.refresh(list, v.address, u64::from(v.size));
  811. let view = D3D12_INDEX_BUFFER_VIEW {
  812. BufferLocation: shadow.gpu(v.address),
  813. SizeInBytes: v.size,
  814. Format: DXGI_FORMAT(v.format as i32),
  815. };
  816. // SAFETY: an open list; the view names a live host buffer.
  817. unsafe { l.IASetIndexBuffer(Some(&view)) };
  818. }
  819. const RENDER_TARGET: u32 = 0x4;
  820. for &t in &self.targets {
  821. crate::list::ensure_state(list, t as This, RENDER_TARGET);
  822. }
  823. if self.depth != 0 {
  824. // A depth texture shaders also write: what they wrote, first.
  825. list.twin_use(self.depth as This, false, true);
  826. // A view that writes neither plane keeps the texture readable:
  827. // the depth read state, together with the shader read states
  828. // if this draw's shaders read the same texture (the write state
  829. // put it out of the state those views need, and a move to it
  830. // and back for every such draw).
  831. let state = if self.depth_state == DEPTH_READ {
  832. let (tested, read) = TESTED_DEPTH.get();
  833. if read && tested == self.depth {
  834. DEPTH_READ | SHADER_RESOURCE
  835. } else {
  836. DEPTH_READ
  837. }
  838. } else {
  839. DEPTH_WRITE
  840. };
  841. crate::list::ensure_state(list, self.depth as This, state);
  842. }
  843. true
  844. }
  845. /// A descriptor a shader reads through a table: its host slot made if
  846. /// it changed, constant data copied, textures made readable.
  847. /// What draws and dispatches share: heaps, our root signature, the
  848. /// pipeline, and per stage the user data, root views and the
  849. /// descriptors its tables hold.
  850. /// False if the draw or dispatch must not run: a root SRV it reads
  851. /// could not be given a view.
  852. pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool {
  853. let l = &list.list;
  854. // Textures picked by index, before anything asks for them.
  855. self.early_textures(list, p, compute);
  856. // Heaps first: a root signature with directly indexed heaps must be
  857. // set after them.
  858. if self.host_heaps != self.heaps {
  859. let heaps: Vec<Option<ID3D12DescriptorHeap>> = self
  860. .heaps
  861. .iter()
  862. .filter(|&&h| h != 0)
  863. .filter_map(|&h| crate::descriptor::heap(h as This).host())
  864. .map(|h| Some(h.heap.clone()))
  865. .collect();
  866. heaps.iter().flatten().for_each(|h| list.keep(h));
  867. // SAFETY: an open list and shader-visible heaps.
  868. unsafe { l.SetDescriptorHeaps(&heaps) };
  869. self.host_heaps = self.heaps;
  870. self.host_roots = [0; 2];
  871. }
  872. // The depth target a draw only tests, for the views of it that the
  873. // draw's shaders read (`readable`).
  874. let tested = if !compute && self.depth_state == DEPTH_READ {
  875. self.depth
  876. } else {
  877. 0
  878. };
  879. TESTED_DEPTH.set((tested, false));
  880. let root = p.root.as_raw() as usize;
  881. if self.host_roots[usize::from(compute)] != root {
  882. // SAFETY: an open list and a live root signature.
  883. unsafe {
  884. if compute {
  885. l.SetComputeRootSignature(&p.root);
  886. } else {
  887. l.SetGraphicsRootSignature(&p.root);
  888. }
  889. }
  890. self.host_roots[usize::from(compute)] = root;
  891. }
  892. // By host object: a title pipeline released and another made at its
  893. // address is another host pipeline (the list keeps the old one).
  894. if self.host_pipeline != p.pso.as_raw() as usize {
  895. // SAFETY: an open list and a live pipeline.
  896. unsafe { l.SetPipelineState(&p.pso) };
  897. self.host_pipeline = p.pso.as_raw() as usize;
  898. list.used_pipeline(&p.name);
  899. // The title may release the pipeline before it submits the list.
  900. list.keep(&p.pso);
  901. list.keep(&p.root);
  902. }
  903. for stage in &p.stages {
  904. let t = stage.translated();
  905. STORES.set(t.stores);
  906. let made = self.tables(list, &t.used, &t.host.root_indexed_views, compute);
  907. STORES.set(true);
  908. if made.iter().any(|m| m.1 == u32::MAX) {
  909. once!("a draw whose descriptor table found no free slots is dropped");
  910. return false;
  911. }
  912. // What the shader stores through root views and raw addresses is
  913. // copied back into title memory afterwards.
  914. let writes = (t.stores || !write_skip())
  915. && !crate::pipeline::builder_quarantined(self.pipeline as This);
  916. // Title memory by address: what the shader finds it by.
  917. let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) {
  918. let Some(ready) = self.memory_ready(list, compute, writes) else {
  919. once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped");
  920. return false;
  921. };
  922. Some(ready)
  923. } else {
  924. None
  925. };
  926. if let Some((param, dwords)) = stage.user_data {
  927. let mut values = vec![0u32; dwords as usize];
  928. for u in &t.host.user_data {
  929. if let RootType::Other(kind) = u.root {
  930. values[u.index as usize] =
  931. self.host_word(compute, kind, u.slot, u.dword, memory.as_ref());
  932. continue;
  933. }
  934. let fresh = made
  935. .iter()
  936. .find(|m| m.0 == u.slot && u.root == RootType::Table);
  937. values[u.index as usize] = match fresh {
  938. Some(&(_, offset)) => offset,
  939. None => self.user_value(compute, u.slot, u.root, u.dword),
  940. };
  941. }
  942. // SAFETY: an open list; `values` covers the parameter.
  943. unsafe {
  944. if compute {
  945. l.SetComputeRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  946. } else {
  947. l.SetGraphicsRoot32BitConstants(param, dwords, values.as_ptr().cast(), 0);
  948. }
  949. }
  950. }
  951. for (views, srv) in [(&stage.root_cbvs, false), (&stage.root_srvs, true)] {
  952. for &(slot, param) in views {
  953. if srv && slot == victory_shader::emit::SLOT_MEMORY {
  954. // Ours: the directory of title memory by address.
  955. if let Some(m) = &memory {
  956. // SAFETY: an open list; the directory lives as
  957. // long as the process and the list holds it.
  958. unsafe {
  959. if compute {
  960. l.SetComputeRootShaderResourceView(param, m.directory);
  961. } else {
  962. l.SetGraphicsRootShaderResourceView(param, m.directory);
  963. }
  964. }
  965. }
  966. continue;
  967. }
  968. if srv && slot == victory_shader::emit::SLOT_STRIDES {
  969. // Ours, not the title's: the shader picks buffers
  970. // from the view heap by an index it computes.
  971. match self.heap_buffers(list) {
  972. // SAFETY: an open list; the table lives as long
  973. // as the heap the list holds.
  974. Some(gpu) => unsafe {
  975. if compute {
  976. l.SetComputeRootShaderResourceView(param, gpu);
  977. } else {
  978. l.SetGraphicsRootShaderResourceView(param, gpu);
  979. }
  980. },
  981. None => once!("a shader picks buffers from a view heap that is not set"),
  982. }
  983. continue;
  984. }
  985. let tabled = srv && crate::pipeline::host::bounded_root_srvs();
  986. let Some(&Root::View(address)) = self.roots_ref(compute).get(usize::from(slot))
  987. else {
  988. once!(slot, "a shader reads a root view the title did not set");
  989. // A table left unset is undefined: a null view.
  990. if tabled && !self.root_srv_table(list, None, param, compute, false) {
  991. return false;
  992. }
  993. continue;
  994. };
  995. // The shader adds the bytes a raw view begins early by.
  996. let biased = srv
  997. && t.host.user_data.iter().any(|u| {
  998. u.slot == slot
  999. && u.root == RootType::Other(victory_shader::emit::USER_VIEW_BIAS)
  1000. });
  1001. if tabled {
  1002. if !self.root_srv_table(list, Some(address), param, compute, biased) {
  1003. return false;
  1004. }
  1005. continue;
  1006. }
  1007. let Some(mut gpu) = root_view(list, address, srv) else {
  1008. continue;
  1009. };
  1010. if biased {
  1011. gpu -= u64::from(self.host_word(
  1012. compute,
  1013. victory_shader::emit::USER_VIEW_BIAS,
  1014. slot,
  1015. 0,
  1016. None,
  1017. ));
  1018. }
  1019. // SAFETY: an open list; the address is in live memory.
  1020. unsafe {
  1021. match (compute, srv) {
  1022. (false, false) => l.SetGraphicsRootConstantBufferView(param, gpu),
  1023. (false, true) => l.SetGraphicsRootShaderResourceView(param, gpu),
  1024. (true, false) => l.SetComputeRootConstantBufferView(param, gpu),
  1025. (true, true) => l.SetComputeRootShaderResourceView(param, gpu),
  1026. }
  1027. }
  1028. }
  1029. }
  1030. for &(slot, param) in &stage.root_uavs {
  1031. if slot == victory_shader::emit::SLOT_FAULTS {
  1032. // Ours: where shaders note the pages they found empty.
  1033. if let Some(m) = &memory {
  1034. // SAFETY: an open list; the buffer lives as long as
  1035. // the process and the list holds it.
  1036. unsafe {
  1037. if compute {
  1038. l.SetComputeRootUnorderedAccessView(param, m.faults);
  1039. } else {
  1040. l.SetGraphicsRootUnorderedAccessView(param, m.faults);
  1041. }
  1042. }
  1043. }
  1044. continue;
  1045. }
  1046. let address = match self.roots_ref(compute).get(usize::from(slot)) {
  1047. Some(&Root::View(address)) => Some(address),
  1048. _ => {
  1049. once!(slot, "a shader writes through a root view the title did not set");
  1050. None
  1051. }
  1052. };
  1053. if !self.root_uav(list, address, param, compute, writes) {
  1054. return false;
  1055. }
  1056. }
  1057. }
  1058. // Depth textures it writes through unordered access: their colour
  1059. // twins hold what they lack from here on.
  1060. list.twins_written();
  1061. true
  1062. }
  1063. /// Binds a root UAV: a raw unordered access view of the title buffer's
  1064. /// host copy from `address` on, as a one-view table (a null view
  1065. /// without an address, without a host copy shaders can write, or at an
  1066. /// address not on 16 bytes), or as a root descriptor with
  1067. /// `VICTORY_ROOT_SRV_DIRECT=1` (the dispatch is dropped then if there
  1068. /// is nothing to bind). With `writes`, what the shader stored is copied
  1069. /// back into title memory when the list has run. False if the draw
  1070. /// must be dropped.
  1071. /// shortcut: a root view has no size: the view, the refresh and the
  1072. /// copy back cover all that is left of the title's buffer
  1073. /// (`VICTORY_ROOT_UAV_MB` sets a limit for all three).
  1074. fn root_uav(
  1075. &mut self,
  1076. list: &HostList,
  1077. address: Option<u64>,
  1078. param: u32,
  1079. compute: bool,
  1080. writes: bool,
  1081. ) -> bool {
  1082. const UNORDERED: i32 = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0;
  1083. static LIMIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1084. let limit = *LIMIT.get_or_init(|| {
  1085. std::env::var("VICTORY_ROOT_UAV_MB")
  1086. .ok()
  1087. .and_then(|v| v.parse::<u64>().ok())
  1088. .map_or(u64::MAX, |mb| mb << 20)
  1089. });
  1090. let find = |a: u64| {
  1091. let s = crate::shadow::find(a, 1)?;
  1092. // SAFETY: a live buffer.
  1093. let flags = unsafe { s.buffer.GetDesc() }.Flags;
  1094. if flags.0 & UNORDERED == 0 {
  1095. once!("a root UAV of a buffer whose host copy shaders cannot write");
  1096. return None;
  1097. }
  1098. Some(s)
  1099. };
  1100. let ready = |a: u64, s: &std::sync::Arc<crate::shadow::Shadow>| {
  1101. let len = s.left(a).min(limit);
  1102. s.refresh(list, a, len);
  1103. if writes {
  1104. #[cfg(feature = "diagnostics")]
  1105. crate::host::wide_write(a, len, self.pipeline);
  1106. s.gpu_writes(list, a, len);
  1107. }
  1108. };
  1109. if !crate::pipeline::host::bounded_root_srvs() {
  1110. let Some((a, s)) = address.and_then(|a| Some((a, find(a)?))) else {
  1111. once!("a root UAV with nothing to bind: the draw is dropped");
  1112. return false;
  1113. };
  1114. ready(a, &s);
  1115. // From the 16 bytes below: the shader adds the rest.
  1116. // SAFETY: a live buffer.
  1117. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1118. let gpu = base + ((s.gpu(a) - base) & !15);
  1119. // SAFETY: an open list; the address is in a live buffer.
  1120. unsafe {
  1121. if compute {
  1122. list.list.SetComputeRootUnorderedAccessView(param, gpu);
  1123. } else {
  1124. list.list.SetGraphicsRootUnorderedAccessView(param, gpu);
  1125. }
  1126. }
  1127. return true;
  1128. }
  1129. let heap = match self.heaps[0] {
  1130. 0 => None,
  1131. h => Some(crate::descriptor::heap(h as This)),
  1132. };
  1133. let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
  1134. once!("a root UAV without a bound view heap: the draw is dropped");
  1135. return false;
  1136. };
  1137. let key = (std::ptr::from_ref(heap) as usize, address.unwrap_or(0));
  1138. let (index, shadow) = match self.root_uav_slots.get(&key) {
  1139. Some((index, shadow)) => (*index, address.zip(shadow.clone())),
  1140. None => {
  1141. let shadow = address.and_then(|a| find(a).map(|s| (a, s)));
  1142. let Some(index) = host.dynamic(1) else {
  1143. return false;
  1144. };
  1145. self.dynamic.push((key.0, index, 1));
  1146. if let Some((a, s)) = &shadow {
  1147. // SAFETY: a live buffer.
  1148. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1149. let offset = s.gpu(*a) - base;
  1150. // Raw views start on 16 bytes: from the 16 bytes
  1151. // below, and the shader adds the rest to its offsets
  1152. // (`victory_shader::emit::USER_VIEW_BIAS`). (An address
  1153. // not on 16 bytes got a null view at first: the
  1154. // builder's counters are at such addresses.)
  1155. let bias = offset & 15;
  1156. host.raw_uav_at(index, &s.buffer, offset - bias, s.left(*a).min(limit) + bias);
  1157. }
  1158. if shadow.is_none() {
  1159. host.null_raw_uav_at(index);
  1160. }
  1161. self.root_uav_slots
  1162. .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
  1163. (index, shadow)
  1164. }
  1165. };
  1166. if let Some((a, s)) = &shadow {
  1167. ready(*a, s);
  1168. }
  1169. let handle = host.gpu_handle(index);
  1170. // SAFETY: an open list; the slot is in the bound view heap.
  1171. unsafe {
  1172. if compute {
  1173. list.list.SetComputeRootDescriptorTable(param, handle);
  1174. } else {
  1175. list.list.SetGraphicsRootDescriptorTable(param, handle);
  1176. }
  1177. }
  1178. true
  1179. }
  1180. /// Binds a root SRV as a one-view table
  1181. /// ([`crate::pipeline::host::bounded_root_srvs`]): a raw view of the
  1182. /// title buffer's host copy from `address` to the copy's end, or a null
  1183. /// view (no address, no host copy, or an address not on 16 bytes). One
  1184. /// dynamic slot per address per list, given back with the list's
  1185. /// others. False if no slot could be had or no view heap is bound.
  1186. fn root_srv_table(
  1187. &mut self,
  1188. list: &HostList,
  1189. address: Option<u64>,
  1190. param: u32,
  1191. compute: bool,
  1192. biased: bool,
  1193. ) -> bool {
  1194. let heap = match self.heaps[0] {
  1195. 0 => None,
  1196. h => Some(crate::descriptor::heap(h as This)),
  1197. };
  1198. let Some((heap, host)) = heap.and_then(|h| Some((h, h.host()?))) else {
  1199. once!("a root SRV without a bound view heap: the draw is dropped");
  1200. return false;
  1201. };
  1202. // A view that begins early is another view than one that does not
  1203. // (title addresses stay below bit 63).
  1204. let key = (
  1205. std::ptr::from_ref(heap) as usize,
  1206. address.unwrap_or(0) | u64::from(biased) << 63,
  1207. );
  1208. let (index, shadow) = match self.root_srv_slots.get(&key) {
  1209. Some((index, shadow)) => (*index, address.zip(shadow.clone())),
  1210. None => {
  1211. let shadow = address.and_then(|a| crate::shadow::find(a, 1).map(|s| (a, s)));
  1212. let Some(index) = host.dynamic(1) else {
  1213. return false;
  1214. };
  1215. self.dynamic.push((key.0, index, 1));
  1216. self.root_srv_slots
  1217. .insert(key, (index, shadow.as_ref().map(|(_, s)| s.clone())));
  1218. match &shadow {
  1219. Some((a, s)) => {
  1220. // SAFETY: a live buffer.
  1221. let base = unsafe { s.buffer.GetGPUVirtualAddress() };
  1222. let offset = s.gpu(*a) - base;
  1223. if biased {
  1224. // From the 16 bytes below; the shader adds the
  1225. // rest (`victory_shader::emit::USER_VIEW_BIAS`).
  1226. let bias = offset & 15;
  1227. host.raw_at(index, &s.buffer, offset - bias, s.left(*a) + bias);
  1228. } else if offset.is_multiple_of(16) {
  1229. host.raw_at(index, &s.buffer, offset, s.left(*a));
  1230. } else {
  1231. // Raw views start on 16 bytes; one from the
  1232. // aligned start would shift every read.
  1233. once!(
  1234. address = format_args!("{a:#x}"),
  1235. "a root SRV not on 16 bytes reads zeros"
  1236. );
  1237. host.null_raw_at(index);
  1238. }
  1239. }
  1240. None => host.null_raw_at(index),
  1241. }
  1242. (index, shadow)
  1243. }
  1244. };
  1245. // As for root descriptors (`root_view`): all that is left of the
  1246. // buffer is brought up to date. The first 1 MiB only left what lay
  1247. // past it stale (most mesh vertex streams reach further).
  1248. if let Some((a, s)) = &shadow {
  1249. s.refresh(list, *a, s.left(*a));
  1250. }
  1251. let handle = host.gpu_handle(index);
  1252. // SAFETY: an open list; the slot is in the bound view heap.
  1253. unsafe {
  1254. if compute {
  1255. list.list.SetComputeRootDescriptorTable(param, handle);
  1256. } else {
  1257. list.list.SetGraphicsRootDescriptorTable(param, handle);
  1258. }
  1259. }
  1260. true
  1261. }
  1262. /// For a shader that picks buffers from the view heap by an index it
  1263. /// computes (SM 6.6 dynamic resources): the GPU address of the heap's
  1264. /// table of element strides, with every buffer view of the heap given
  1265. /// its host slot and its memory brought up to date when `list` is
  1266. /// submitted. Tables tell us which views a draw reads; nothing tells
  1267. /// us which of the heap's a computed index names, so all of them are
  1268. /// made ready, once per list.
  1269. /// shortcut: the buffers are read, not written: what such a shader
  1270. /// writes through a picked unordered access view stays in the host
  1271. /// copy. A list refreshes them where it first runs such a shader;
  1272. /// title writes recorded later in the same list are not seen.
  1273. fn heap_buffers(&self, list: &HostList) -> Option<u64> {
  1274. let heap = self
  1275. .heaps
  1276. .iter()
  1277. .filter(|&&h| h != 0)
  1278. .map(|&h| crate::descriptor::heap(h as This))
  1279. .find(|h| !h.samplers())?;
  1280. let host = heap.host()?;
  1281. let gpu = host.strides_gpu()?;
  1282. // One key per list, as textures have: no title resource is there.
  1283. const ONCE: usize = usize::MAX - 0x5e;
  1284. if !list.first_use(ONCE) {
  1285. return Some(gpu);
  1286. }
  1287. // The list may outlive the title's heap object, which owns the table.
  1288. if let Some(buffer) = host.strides_buffer() {
  1289. list.keep(buffer);
  1290. }
  1291. // The pass itself once per frame: per list it ran up to 51 times a
  1292. // frame over 81,000 views and 4,100 host copies, 18 s of every
  1293. // frame (2026-11-24, run 11).
  1294. // shortcut: what the title writes into such buffers between lists
  1295. // of one frame is seen a frame late.
  1296. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1297. let frame = crate::frame::current();
  1298. if FRAME.swap(frame, Ordering::Relaxed) == frame {
  1299. return Some(gpu);
  1300. }
  1301. let started = std::time::Instant::now();
  1302. // Per host heap: the host copy and range each slot's buffer view
  1303. // reads, kept from pass to pass. Only the slots written since the
  1304. // last pass are looked at again (83,000 slots a pass otherwise, 0.1 s
  1305. // at best); all of them every 16 passes, because a view of a
  1306. // released resource goes stale without a write, and a slot written
  1307. // before its memory had a host copy is only made then.
  1308. type Ranges = std::collections::HashMap<u32, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)>;
  1309. static RANGES: std::sync::Mutex<Option<std::collections::HashMap<usize, (u64, Ranges)>>> =
  1310. std::sync::Mutex::new(None);
  1311. let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner());
  1312. let (passes, ranges) = kept
  1313. .get_or_insert_with(Default::default)
  1314. .entry(std::ptr::from_ref(host) as usize)
  1315. .or_insert_with(|| (0, Ranges::new()));
  1316. let changed = host.buffer_changes();
  1317. let slots = if *passes % 16 == 0 {
  1318. ranges.clear();
  1319. host.buffer_slots()
  1320. } else {
  1321. changed
  1322. };
  1323. *passes += 1;
  1324. // Whether the device was there before the pass: a view that removes
  1325. // it is named below.
  1326. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  1327. let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
  1328. for (n, &index) in slots.iter().enumerate() {
  1329. ranges.remove(&index);
  1330. let Some(handle) = heap.handle(index) else {
  1331. continue;
  1332. };
  1333. let Some(view) = host.mirror(index, handle, true) else {
  1334. continue;
  1335. };
  1336. // Every 64 views while the device lives (a cheap query).
  1337. if alive
  1338. && n % 64 == 63
  1339. && let Some(why) = crate::descriptor::host::device_removed()
  1340. {
  1341. alive = false;
  1342. GONE.store(true, Ordering::Relaxed);
  1343. let last: Vec<String> = slots[n - 63..=n]
  1344. .iter()
  1345. .filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}")))
  1346. .map(|s| s.chars().take(200).collect())
  1347. .collect();
  1348. tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}");
  1349. crate::host::log_removal_context();
  1350. }
  1351. // The copy the slot shows (`buffer_copy`), not the one the
  1352. // view's range alone would find.
  1353. let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else {
  1354. continue;
  1355. };
  1356. #[cfg(feature = "diagnostics")]
  1357. if host.shows(index, &shadow.buffer) == Some(false) {
  1358. HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
  1359. }
  1360. ranges.insert(index, (shadow, address, address + len));
  1361. }
  1362. let views = ranges.len() as u32;
  1363. // Per host copy, the span its picked views cover.
  1364. let mut spans: std::collections::HashMap<usize, (std::sync::Arc<crate::shadow::Shadow>, u64, u64)> =
  1365. std::collections::HashMap::new();
  1366. for (shadow, from, to) in ranges.values() {
  1367. let key = std::sync::Arc::as_ptr(shadow) as usize;
  1368. let span = spans.entry(key).or_insert_with(|| (shadow.clone(), *from, *to));
  1369. span.1 = span.1.min(*from);
  1370. span.2 = span.2.max(*to);
  1371. }
  1372. drop(kept);
  1373. let bytes: u64 = spans.values().map(|s| s.2 - s.1).sum();
  1374. // Memory that is not write-watched is copied whole by every refresh.
  1375. // It was once refreshed only every 120 frames (unmapped pages read
  1376. // one by one cost 14 GB a frame in run 11, before they were
  1377. // remembered): streamed geometry then drew from stale buffers, and
  1378. // the garbage ended runs (the card stopped answering 14-90 frames
  1379. // into the opening cutscene; with every frame it ran on). The pass
  1380. // costs some 30 ms a frame this way.
  1381. static WHOLE: std::sync::Mutex<Option<std::collections::HashMap<usize, u64>>> = std::sync::Mutex::new(None);
  1382. let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner());
  1383. let whole = whole.get_or_insert_with(Default::default);
  1384. for (shadow, from, to) in spans.values() {
  1385. if shadow.unwatched() {
  1386. // By the copy's number: a copy made where one let go was
  1387. // (`shadow::let_go_idle`) has never been refreshed.
  1388. let key = shadow.id() as usize;
  1389. // `VICTORY_UNWATCHED_FRAMES` sets the interval (1: every frame).
  1390. static EVERY: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1391. let every = *EVERY.get_or_init(|| {
  1392. std::env::var("VICTORY_UNWATCHED_FRAMES")
  1393. .ok()
  1394. .and_then(|v| v.parse().ok())
  1395. .unwrap_or(1)
  1396. });
  1397. match whole.get(&key) {
  1398. Some(&last) if frame < last + every => continue,
  1399. _ => {
  1400. whole.insert(key, frame);
  1401. }
  1402. }
  1403. }
  1404. shadow.refresh(list, *from, to - from);
  1405. }
  1406. self.heap_textures(list, heap, host);
  1407. HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed);
  1408. HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  1409. static LOGGED: AtomicU64 = AtomicU64::new(0);
  1410. // The first pass and every growth of the set by half.
  1411. let seen = LOGGED.load(Ordering::Relaxed);
  1412. if u64::from(views) > seen + seen / 2 {
  1413. LOGGED.store(u64::from(views), Ordering::Relaxed);
  1414. tracing::info!(
  1415. slots = slots.len(),
  1416. views,
  1417. copies = spans.len(),
  1418. mb = bytes >> 20,
  1419. ms = started.elapsed().as_millis(),
  1420. "buffer views of the heap made ready for shaders that pick them by index"
  1421. );
  1422. }
  1423. Some(gpu)
  1424. }
  1425. /// Runs the pass that uploads textures picked by index
  1426. /// ([`State::heap_textures`]) where nothing has asked for it yet
  1427. /// ([`early_budgets`]): once a frame for a few milliseconds, at the
  1428. /// frame's first draw with a view heap set, and with a larger budget
  1429. /// of its own before every draw whose pixel shader is one of the
  1430. /// title's bake programs. The uploads are recorded into `list` ahead
  1431. /// of the draw being bound, as the world's pass records them.
  1432. fn early_textures(&self, list: &HostList, p: &HostPipeline, compute: bool) {
  1433. let (early_ms, bake_ms) = early_budgets();
  1434. if compute || (early_ms == 0 && bake_ms == 0) {
  1435. return;
  1436. }
  1437. let bake = bake_ms > 0
  1438. && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str()));
  1439. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1440. // The milliseconds this frame's bake draws have taken so far: a
  1441. // frame has several, and together they get `bake_ms`.
  1442. static BAKED_MS: AtomicU64 = AtomicU64::new(0);
  1443. let frame = crate::frame::current();
  1444. let first = FRAME.swap(frame, Ordering::Relaxed) != frame;
  1445. if first {
  1446. BAKED_MS.store(0, Ordering::Relaxed);
  1447. }
  1448. let left = bake_ms.saturating_sub(BAKED_MS.load(Ordering::Relaxed));
  1449. let budget = if bake && left > 0 {
  1450. // What a bake may read must be there now: up to 2 GiB.
  1451. (left, 2 << 30)
  1452. } else if first && early_ms > 0 {
  1453. (early_ms, 64 << 20)
  1454. } else {
  1455. return;
  1456. };
  1457. let Some(heap) = self
  1458. .heaps
  1459. .iter()
  1460. .filter(|&&h| h != 0)
  1461. .map(|&h| crate::descriptor::heap(h as This))
  1462. .find(|h| !h.samplers())
  1463. else {
  1464. return;
  1465. };
  1466. let Some(host) = heap.host() else {
  1467. return;
  1468. };
  1469. let bake = bake && left > 0;
  1470. let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1;
  1471. if bake && n.is_power_of_two() {
  1472. let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed));
  1473. tracing::info!(
  1474. frame,
  1475. bakes = n,
  1476. queued_at_the_last_pass = slots,
  1477. due_at_the_last_pass = due,
  1478. uploaded_so_far = HEAP_TEXTURES.load(Ordering::Relaxed),
  1479. "a draw of the title's decoration bake: textures picked by index are uploaded first (VICTORY_BAKE_TEXTURES_MS=0: not)"
  1480. );
  1481. }
  1482. let began = std::time::Instant::now();
  1483. PASS_BUDGET.set(Some(budget));
  1484. self.heap_textures(list, heap, host);
  1485. PASS_BUDGET.set(None);
  1486. if bake {
  1487. BAKED_MS.fetch_add(began.elapsed().as_millis() as u64, Ordering::Relaxed);
  1488. }
  1489. }
  1490. /// The texture side of [`State::heap_buffers`]: textures the title fills
  1491. /// itself (streamed pages, layout-library copies) whose views sit in the
  1492. /// view heap are created (placed textures have no host texture until
  1493. /// something reads them) and uploaded, as a table read would do, for
  1494. /// shaders that pick them by a computed index. Within a budget of bytes
  1495. /// per frame and in all; the rest waits for later lists and frames.
  1496. /// The most recently written slots first (`TextureQueue::due`); slots
  1497. /// draws read through tables are not in the queue.
  1498. /// shortcut: uploaded once, and again only when the title rewrites the
  1499. /// slot. A placed texture not all mapped yet is uploaded with what is
  1500. /// there and looked at again (1, 2, 4, ... frames later, at most about
  1501. /// a second): uploaded again when more of it is mapped. Pages mapped
  1502. /// in place of others, and contents changed with no descriptor write,
  1503. /// are missed (hook the page-mapping events for those).
  1504. /// `VICTORY_HEAP_TEXTURES=0` turns it off.
  1505. fn heap_textures(
  1506. &self,
  1507. list: &HostList,
  1508. heap: &crate::descriptor::Heap,
  1509. host: &crate::descriptor::host::HostHeap,
  1510. ) {
  1511. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1512. if !*ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_TEXTURES").is_none_or(|v| v != "0")) {
  1513. return;
  1514. }
  1515. let memory = crate::host::host().and_then(|h| h.video_memory());
  1516. // `VICTORY_TEXTURE_STAGE_MB` sets it: a backlog of tens of thousands of
  1517. // textures (a scene's first minutes) then drains in fewer frames.
  1518. static PER_FRAME_MB: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
  1519. let asked = *PER_FRAME_MB.get_or_init(|| {
  1520. std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse::<u64>().ok())
  1521. });
  1522. let per_frame = match asked {
  1523. Some(mb) => mb << 20,
  1524. None => staging_budget_per_frame(memory.map(|[budget, ..]| budget)),
  1525. };
  1526. static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
  1527. static SPENT: AtomicU64 = AtomicU64::new(0);
  1528. let frame = crate::frame::current();
  1529. if FRAME.swap(frame, Ordering::Relaxed) != frame {
  1530. SPENT.store(0, Ordering::Relaxed);
  1531. }
  1532. // No more of them are made while the card has no room
  1533. // (`resource::room`): by what is alive now, not by what was ever
  1534. // staged (4 GB in all, after which later textures stayed empty for
  1535. // the run). The ones nothing names any more are let go, which
  1536. // makes room again: so the slots are still looked at (the pass
  1537. // returned here, and a slot whose texture had been streamed out
  1538. // kept its host copy for as long as the card was full).
  1539. let room = crate::resource::room(memory);
  1540. if !room {
  1541. HEAP_TEXTURES_FULL.fetch_add(1, Ordering::Relaxed);
  1542. once!("textures picked by index: the card has no room for more; they wait");
  1543. }
  1544. let mut refused = 0;
  1545. // Slots whose texture's memory the runtime mapped, unmapped or
  1546. // wrote since the last pass are due again.
  1547. host.texture_slots_remapped(frame);
  1548. let (due, census) = host.texture_slots_due(frame, 4096);
  1549. HEAP_TEXTURES_WAITING.store(census[0], Ordering::Relaxed);
  1550. for (count, now) in HEAP_TEXTURES_QUEUE.iter().zip(census) {
  1551. count.store(now, Ordering::Relaxed);
  1552. }
  1553. // The frames in about four seconds, between 16 and 256: how long a
  1554. // slot with nothing to upload waits at most for its next look. In
  1555. // frames alone it was 120: four minutes at the opening cutscene's
  1556. // half a frame per second, while the title streams by the clock.
  1557. // (About a second before the runtime told of the memory it maps:
  1558. // the looks are now only for what that does not tell.)
  1559. static PASSED: AtomicU64 = AtomicU64::new(0);
  1560. let now = crate::host::now_ms();
  1561. let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1);
  1562. let most = (4000 / took).clamp(16, 256);
  1563. // What a table entry of a texture a shader samples says.
  1564. let sampled = UsedResource {
  1565. kind: ResourceType::Srv,
  1566. root: RootType::Table,
  1567. table_offset_dwords: 0,
  1568. lower_bound: 0,
  1569. stride: 0,
  1570. dwords: 8,
  1571. user_data: 0,
  1572. slot: 0,
  1573. };
  1574. // Also within a time per pass: the pass runs on a thread that
  1575. // records the frame, and making and staging 192 MB of textures took
  1576. // 1.6-2.2 s of each of the world's first twenty frames (run 20).
  1577. // The rest waits for the next frames, as it does past the bytes.
  1578. static SPAN_MS: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1579. let span = std::time::Duration::from_millis(*SPAN_MS.get_or_init(|| {
  1580. std::env::var("VICTORY_TEXTURE_STAGE_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(250)
  1581. }));
  1582. // A backlog (a scene's first minutes: 22,000 slots due, 2-3 minutes of black
  1583. // surfaces at 192 MB a frame) gets three times the bytes and the time until it
  1584. // drains; `VICTORY_TEXTURE_CATCHUP=0` keeps the plain budget.
  1585. static CATCHUP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1586. let catchup = *CATCHUP.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_CATCHUP").is_none_or(|v| v != "0"));
  1587. let (per_frame, span) = if catchup && due.len() >= 1024 { (per_frame * 3, span * 3) } else { (per_frame, span) };
  1588. // A run made early (`State::early_textures`) has a budget of its
  1589. // own: its bytes on top of what the frame has spent so far.
  1590. // (Not `most`: that is the longest wait between looks, used below.)
  1591. let (span, bytes_at_most) = match PASS_BUDGET.get() {
  1592. Some((ms, bytes)) => {
  1593. (std::time::Duration::from_millis(ms), SPENT.load(Ordering::Relaxed).saturating_add(bytes))
  1594. }
  1595. None => (span, per_frame),
  1596. };
  1597. let began = std::time::Instant::now();
  1598. for (index, write) in due {
  1599. if SPENT.load(Ordering::Relaxed) >= bytes_at_most || began.elapsed() > span {
  1600. break;
  1601. }
  1602. // A placed texture whose memory is not mapped (not streamed in
  1603. // yet, or streamed out again: the heap keeps tens of thousands
  1604. // of such views) gets no host texture; looked at again soon (a
  1605. // title writes a texture's view before its pages are mapped,
  1606. // and the pass runs early in a frame). One of which some is
  1607. // mapped (a texture streaming in: its smaller mips lie at the
  1608. // start of its memory and arrive first) is uploaded with what
  1609. // is there, and again when more is. (It was uploaded again
  1610. // every 120 frames, changed or not; and asked by its first
  1611. // page alone, one whose first page is the one missing counted
  1612. // as not there.)
  1613. // A slot uploaded whole is looked at again a few times
  1614. // (`RECHECK_FRAMES`): the title writes a texture's view, and
  1615. // may fill the texture's memory itself only afterwards, with
  1616. // no descriptor write and nothing from the runtime to tell of
  1617. // it. The host copy then kept what the memory held at the
  1618. // first look for the rest of the run. The look reads 48 KiB;
  1619. // only a changed texture is uploaded again.
  1620. // `VICTORY_HEAP_RECHECK=0`: uploaded once, as before.
  1621. if let Some((at, len, print, looks, uploaded)) = host.texture_slot_checked(index) {
  1622. if crate::texture::fingerprint(at, len) == print {
  1623. HEAP_TEXTURES_RECHECKED[0].fetch_add(1, Ordering::Relaxed);
  1624. match RECHECK_FRAMES.get(usize::from(looks) + 1) {
  1625. Some(wait) => {
  1626. host.texture_slot_recheck(index, write, frame + wait, (at, len), print, looks + 1, uploaded)
  1627. }
  1628. None => host.texture_slot_done(index, write, None),
  1629. }
  1630. continue;
  1631. }
  1632. let n = HEAP_TEXTURES_RECHECKED[1].fetch_add(1, Ordering::Relaxed);
  1633. if n < 200 || n.is_multiple_of(1000) {
  1634. tracing::warn!(
  1635. slot = index,
  1636. address = format_args!("{at:#x}"),
  1637. bytes = len,
  1638. frames_after_upload = frame.saturating_sub(uploaded),
  1639. looks,
  1640. changed = n + 1,
  1641. "a texture picked by index changed after its upload with nothing to tell of it: uploaded again"
  1642. );
  1643. }
  1644. }
  1645. let mut partly = None;
  1646. if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) {
  1647. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  1648. let len = crate::resource::placed_bytes(&resource).unwrap_or(1);
  1649. let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize);
  1650. if mapped == 0 {
  1651. HEAP_TEXTURES_AWAY.fetch_add(1, Ordering::Relaxed);
  1652. // Streamed out: what the slot showed is let go.
  1653. host.texture_slot_gone(index);
  1654. host.texture_slot_later(index, write, frame, most);
  1655. continue;
  1656. }
  1657. if mapped < len {
  1658. if mapped <= host.texture_slot_mapped(index) {
  1659. HEAP_TEXTURES_PARTLY[0].fetch_add(1, Ordering::Relaxed);
  1660. host.texture_slot_later(index, write, frame, most);
  1661. continue;
  1662. }
  1663. if !crate::texture::committed(address as *const u8, 1) {
  1664. HEAP_TEXTURES_PARTLY[2].fetch_add(1, Ordering::Relaxed);
  1665. }
  1666. partly = Some(mapped);
  1667. }
  1668. }
  1669. // A texture object the host renders to or writes holds the
  1670. // host's own contents: nothing to bring up to date, and this
  1671. // pass is no use of it (its host copy is made when something
  1672. // uses it, and its slots then: `descriptor::make_waiting`).
  1673. if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view)
  1674. && crate::resource::buffer_bytes(object as This).is_none()
  1675. && !crate::resource::title_fills(object as This)
  1676. {
  1677. host.texture_slot_done(index, write, None);
  1678. continue;
  1679. }
  1680. // From here on a host texture is made: not without room. The
  1681. // slot stays due.
  1682. if !room {
  1683. refused += 1;
  1684. if refused > 256 {
  1685. break;
  1686. }
  1687. continue;
  1688. }
  1689. let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true));
  1690. let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture);
  1691. let resource = match placed.as_ref().or(view.as_ref()) {
  1692. Some(&View::Shader(resource, _)) => resource as This,
  1693. _ => {
  1694. host.texture_slot_done(index, write, None);
  1695. continue;
  1696. }
  1697. };
  1698. let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written);
  1699. if !title_fills {
  1700. // a render target, a depth or unordered access texture: the host's own
  1701. host.texture_slot_done(index, write, None);
  1702. continue;
  1703. }
  1704. // A texture that has a staging buffer now is one draws read
  1705. // through a table: they upload it, and check it at every
  1706. // submission that samples it.
  1707. let tabled = crate::texture::is_staged(resource);
  1708. if let Some(view) = &view {
  1709. readable(list, sampled.kind, view);
  1710. }
  1711. // A texture view the host refuses removes the device: name it.
  1712. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  1713. if !GONE.load(Ordering::Relaxed)
  1714. && let Some(why) = crate::descriptor::host::device_removed()
  1715. {
  1716. GONE.store(true, Ordering::Relaxed);
  1717. let text: String = format!("{view:?}").chars().take(300).collect();
  1718. tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}");
  1719. crate::host::log_removal_context();
  1720. return;
  1721. }
  1722. let (bytes, whole) = crate::texture::staged(resource).unwrap_or((0, true));
  1723. // Not all of it there: looked at again next frame, and from
  1724. // then on as a slot with nothing new (a placed texture: until
  1725. // more of it is mapped; a texture object at an address the
  1726. // title mapped: again in 120 frames, as before).
  1727. let again = match partly {
  1728. Some(mapped) => Some((frame + 1, mapped)),
  1729. None => (!whole).then_some((frame + 120, 0)),
  1730. };
  1731. if again.is_some() {
  1732. HEAP_TEXTURES_PARTLY[1].fetch_add(1, Ordering::Relaxed);
  1733. }
  1734. if tabled {
  1735. // Nothing was staged here, so nothing is counted or spent,
  1736. // and the staging buffer stays: taking it away made the
  1737. // next draw that reads the texture through a table stage,
  1738. // detile and upload all of it once more.
  1739. HEAP_TEXTURES_TABLED.fetch_add(1, Ordering::Relaxed);
  1740. host.texture_slot_done(index, write, again);
  1741. continue;
  1742. }
  1743. // Uploaded: the list holds the staging buffer until it has run;
  1744. // a table read, or the next look at a texture not all mapped
  1745. // yet, makes it anew. (Kept for those until now: every partly
  1746. // streamed texture of the heap held a staging buffer of its full
  1747. // size for good.)
  1748. let memory = if again.is_none() && heap_recheck() {
  1749. crate::texture::staged_memory(resource)
  1750. } else {
  1751. None
  1752. };
  1753. crate::texture::unstage(resource);
  1754. SPENT.fetch_add(bytes, Ordering::Relaxed);
  1755. HEAP_TEXTURE_BYTES.fetch_add(bytes, Ordering::Relaxed);
  1756. HEAP_TEXTURES.fetch_add(1, Ordering::Relaxed);
  1757. match memory {
  1758. // Whole and uploaded: looked at again (see above).
  1759. Some((at, len)) => {
  1760. let print = crate::texture::fingerprint(at, len);
  1761. host.texture_slot_recheck(index, write, frame + RECHECK_FRAMES[0], (at, len), print, 0, frame);
  1762. }
  1763. None => host.texture_slot_done(index, write, again),
  1764. }
  1765. }
  1766. }
  1767. /// For the frame listing, after a dropped dispatch's line: its group
  1768. /// counts and the compute root arguments it was recorded with (root
  1769. /// constants as hex dwords, root views with the title buffer they
  1770. /// point into). A program that does not translate has no bindings to
  1771. /// list; these say which memory it would have read and written (the
  1772. /// ray-tracing structure builder passes its buffers this way).
  1773. #[cfg(feature = "diagnostics")]
  1774. fn list_dropped_roots(&self, groups: [u32; 3]) {
  1775. crate::capture::op(0, || {
  1776. use std::fmt::Write;
  1777. let [x, y, z] = groups;
  1778. let mut text = format!(" its roots ({x}x{y}x{z}):");
  1779. for (slot, root) in self.compute.iter().enumerate() {
  1780. match root {
  1781. Root::None => {}
  1782. Root::Table(a) => {
  1783. let _ = write!(text, " {slot}=table {a:#x}");
  1784. }
  1785. Root::Constants(v) => {
  1786. let _ = write!(text, " {slot}=constants {:x?}", &v[..v.len().min(48)]);
  1787. }
  1788. Root::View(a) => {
  1789. let _ = write!(text, " {slot}=view {a:#x}");
  1790. match crate::shadow::extent(*a) {
  1791. Some((start, len)) => {
  1792. let _ = write!(text, " in buffer {start:#x}+{len:#x}");
  1793. }
  1794. None => text.push_str(" in no buffer"),
  1795. }
  1796. }
  1797. }
  1798. }
  1799. text
  1800. });
  1801. }
  1802. /// Runs a dispatch on the host.
  1803. pub(crate) fn dispatch(&mut self, list: &HostList, x: u32, y: u32, z: u32) {
  1804. // It may write the arguments a window holds clamped.
  1805. self.window = None;
  1806. #[cfg(feature = "diagnostics")]
  1807. if crate::pipeline::is_skipped(self.pipeline as This) {
  1808. DROPPED.fetch_add(1, Ordering::Relaxed);
  1809. crate::pipeline::note_drop(self.pipeline as This);
  1810. return;
  1811. }
  1812. // The ray-tracing structure builder's stages run all or none.
  1813. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
  1814. DROPPED.fetch_add(1, Ordering::Relaxed);
  1815. #[cfg(feature = "diagnostics")]
  1816. {
  1817. crate::pipeline::note_why("a stage of the ray-tracing structure builder, which is off".to_owned());
  1818. self.list_dropped_roots([x, y, z]);
  1819. }
  1820. return;
  1821. }
  1822. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  1823. once!(
  1824. pipeline = format_args!("{:#x}", self.pipeline),
  1825. "a dispatch without a host pipeline dropped"
  1826. );
  1827. DROPPED.fetch_add(1, Ordering::Relaxed);
  1828. #[cfg(feature = "diagnostics")]
  1829. {
  1830. crate::pipeline::note_drop(self.pipeline as This);
  1831. self.list_dropped_roots([x, y, z]);
  1832. }
  1833. return;
  1834. };
  1835. if !p.compute {
  1836. once!("a dispatch with a graphics pipeline");
  1837. return;
  1838. }
  1839. if !self.bind(list, p, true) {
  1840. DROPPED.fetch_add(1, Ordering::Relaxed);
  1841. // A stage of the structure builder that cannot be bound is a
  1842. // dropped stage: the others stop too.
  1843. if crate::pipeline::is_builder(self.pipeline as This) {
  1844. crate::pipeline::builder_off("one of its dispatches could not be bound");
  1845. }
  1846. return;
  1847. }
  1848. #[cfg(feature = "diagnostics")]
  1849. list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
  1850. // SAFETY: an open list with everything set.
  1851. unsafe { list.list.Dispatch(x, y, z) };
  1852. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  1853. }
  1854. /// What a draw or dispatch runs, for the device-removed report
  1855. /// (diagnostics): the pipeline, then per stage the user data it gets
  1856. /// (with the view at that heap index, if one is), the host addresses
  1857. /// of its root views and the views its tables name.
  1858. #[cfg(feature = "diagnostics")]
  1859. fn op_text(&self, kind: String, compute: bool) -> String {
  1860. use std::fmt::Write;
  1861. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  1862. return kind;
  1863. };
  1864. let mut text = format!("{kind} {}", p.name);
  1865. // What it draws into (a dispatch writes through its views below).
  1866. if !compute {
  1867. let described = |t: usize| {
  1868. crate::resource::host_made(t as This).map(|r| {
  1869. // SAFETY: a live resource.
  1870. let d = unsafe { r.GetDesc() };
  1871. format!("{t:#x} {}x{} f{}", d.Width, d.Height, d.Format.0)
  1872. })
  1873. };
  1874. let targets: Vec<String> = self.targets.iter().filter_map(|&t| described(t)).collect();
  1875. let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state);
  1876. // The title's scissor and viewport at this draw (the first of
  1877. // each): the title draws what it sees through a
  1878. // portal (a window, from inside a room) under the portal's
  1879. // rectangle, and the listing did not say which draws those are.
  1880. if let Some(r) = self.scissors.first() {
  1881. let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom);
  1882. }
  1883. if let Some(v) = self.viewports.first() {
  1884. let _ = write!(
  1885. text,
  1886. " viewport [{} {} {} {} depth {}..{}]",
  1887. v.TopLeftX, v.TopLeftY, v.Width, v.Height, v.MinDepth, v.MaxDepth
  1888. );
  1889. }
  1890. }
  1891. let views = (self.heaps[0] != 0)
  1892. .then(|| crate::descriptor::heap(self.heaps[0] as This).host())
  1893. .flatten();
  1894. for stage in &p.stages {
  1895. let t = stage.translated();
  1896. let _ = write!(text, " | {}:", stage.shader.hash);
  1897. for u in &t.host.user_data {
  1898. let v = match u.root {
  1899. RootType::Other(kind) => self.host_word(compute, kind, u.slot, u.dword, None),
  1900. _ => self.user_value(compute, u.slot, u.root, u.dword),
  1901. };
  1902. let _ = write!(text, " u{}={v:#x}", u.index);
  1903. let index = if u.root == RootType::Table { v / 32 } else { v };
  1904. if let Some(slot) = views.and_then(|h| h.describe_slot(index)) {
  1905. let _ = write!(text, " [heap {index}: {slot}]");
  1906. }
  1907. }
  1908. for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) {
  1909. if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) {
  1910. let host = crate::shadow::find(*address, 1)
  1911. .map(|s| (s.gpu(*address), s.left(*address)));
  1912. let _ = write!(text, " root{slot}={address:#x} host {host:#x?}");
  1913. }
  1914. }
  1915. }
  1916. let _ = write!(text, " tables {:?}", self.reads(compute));
  1917. text
  1918. }
  1919. /// A mesh draw under `VICTORY_MESH_TEST=scissor` rasterises one pixel:
  1920. /// the scissors before it (`on`), the title's after it.
  1921. fn mesh_scissor(&self, list: &HostList, on: bool) {
  1922. if mesh_test() != 2 {
  1923. return;
  1924. }
  1925. if on {
  1926. let one = RECT { left: 0, top: 0, right: 1, bottom: 1 };
  1927. crate::draw::scissors(list, &vec![one; self.scissors.len().max(1)]);
  1928. } else if !self.scissors.is_empty() {
  1929. crate::draw::scissors(list, &self.scissors);
  1930. }
  1931. }
  1932. /// Runs a mesh dispatch of `x` groups on the host (the title's mesh
  1933. /// programs are one-dimensional).
  1934. pub(crate) fn dispatch_mesh(&mut self, list: &HostList, x: u32) {
  1935. self.window = None;
  1936. #[cfg(feature = "diagnostics")]
  1937. self.trace("mesh", x, 0);
  1938. let ran = mesh_test() != 1
  1939. && mesh_kept(self.pipeline)
  1940. && self.prepare_for(list, false, true)
  1941. && match list.list.cast::<ID3D12GraphicsCommandList6>() {
  1942. Ok(l6) => {
  1943. #[cfg(feature = "diagnostics")]
  1944. list.note_op(|| self.op_text(format!("mesh {x}"), false));
  1945. self.mesh_scissor(list, true);
  1946. // SAFETY: an open list with everything set.
  1947. unsafe { l6.DispatchMesh(x, 1, 1) };
  1948. self.mesh_scissor(list, false);
  1949. DRAWN.fetch_add(1, Ordering::Relaxed);
  1950. true
  1951. }
  1952. Err(_) => false,
  1953. };
  1954. if !ran {
  1955. DROPPED.fetch_add(1, Ordering::Relaxed);
  1956. #[cfg(feature = "diagnostics")]
  1957. dropped(self.pipeline);
  1958. }
  1959. }
  1960. fn roots_ref(&self, compute: bool) -> &Vec<Root> {
  1961. if compute {
  1962. &self.compute
  1963. } else {
  1964. &self.graphics
  1965. }
  1966. }
  1967. fn table_entry(&self, list: &HostList, u: &UsedResource, compute: bool) {
  1968. let Some(Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  1969. return;
  1970. };
  1971. let handle = table + u64::from(u.table_offset_dwords) * 4;
  1972. let Some(heap) = self.heap_of(handle) else {
  1973. return;
  1974. };
  1975. let (Some(host), Some(index)) = (heap.host(), heap.index(handle)) else {
  1976. return;
  1977. };
  1978. if let Some(view) = host.mirror(index, handle, true) {
  1979. readable(list, u.kind, &view);
  1980. // Up to date by this draw: not the texture pass's to make.
  1981. if crate::descriptor::host::is_texture_view(&view) {
  1982. host.texture_slot_tabled(index, true);
  1983. }
  1984. }
  1985. }
  1986. /// The descriptors a shader reads through tables. Tables holding a
  1987. /// constant buffer are made afresh for the draw in dynamic slots, with
  1988. /// the constant data copied to upload memory when the list is
  1989. /// submitted: the host wants constant buffers 256-byte aligned, the
  1990. /// console only 16. Returns those tables' new byte offsets by root
  1991. /// parameter; the other tables' slots are made from the title's.
  1992. ///
  1993. /// Within a list, the same table holding the same descriptors is made
  1994. /// once: its constant data is copied at submission either way, and the
  1995. /// big tables the world binds would otherwise take hundreds of slots per
  1996. /// draw, wrapping the dynamic slots onto lists not yet submitted.
  1997. pub(crate) fn tables(
  1998. &mut self,
  1999. list: &HostList,
  2000. used: &[UsedResource],
  2001. indexed: &[RootIndexedView],
  2002. compute: bool,
  2003. ) -> Vec<(u8, u32)> {
  2004. let tables = |u: &&UsedResource| u.root == RootType::Table;
  2005. let mut fresh: Vec<u8> = used
  2006. .iter()
  2007. .filter(tables)
  2008. .filter(|u| u.kind == ResourceType::Cbv)
  2009. .map(|u| u.slot)
  2010. .collect();
  2011. // Tables reaching past a host heap smaller than the title's (the
  2012. // host's limit, 1,000,000 views on NVIDIA) are made afresh too: the
  2013. // title's slots there have no host slot of their own.
  2014. for u in used.iter().filter(tables) {
  2015. if fresh.contains(&u.slot) {
  2016. continue;
  2017. }
  2018. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(u.slot)) else {
  2019. continue;
  2020. };
  2021. let end = table + u64::from(u.table_offset_dwords) * 4;
  2022. let Some(heap) = self.heap_of(table) else {
  2023. continue;
  2024. };
  2025. let (Some(host), Some(index)) = (heap.host(), heap.index(end)) else {
  2026. continue;
  2027. };
  2028. if index >= host.count() {
  2029. fresh.push(u.slot);
  2030. }
  2031. }
  2032. fresh.sort_unstable();
  2033. fresh.dedup();
  2034. for u in used.iter().filter(tables) {
  2035. if !fresh.contains(&u.slot) {
  2036. self.table_entry(list, u, compute);
  2037. }
  2038. }
  2039. let mut made = Vec::new();
  2040. for slot in fresh {
  2041. let Some(&Root::Table(table)) = self.roots_ref(compute).get(usize::from(slot)) else {
  2042. continue;
  2043. };
  2044. let entries: Vec<&UsedResource> = used
  2045. .iter()
  2046. .filter(tables)
  2047. .filter(|u| u.slot == slot)
  2048. .collect();
  2049. let Some(heap) = self.heap_of(table) else {
  2050. continue;
  2051. };
  2052. if heap.samplers() || (table - heap.start) % 32 != 0 {
  2053. continue;
  2054. }
  2055. let Some(host) = heap.host() else {
  2056. continue;
  2057. };
  2058. let mut selected: Vec<u32> = indexed
  2059. .iter()
  2060. .filter(|index| index.table_slot == slot)
  2061. .map(|index| {
  2062. let constant = self.user_value(
  2063. compute,
  2064. index.constant_slot,
  2065. RootType::Constants,
  2066. index.constant_dword,
  2067. );
  2068. // The shader adds i32 byte offsets and shifts by 5.
  2069. index.byte_offset.wrapping_add(constant << index.shift) / 32
  2070. })
  2071. .collect();
  2072. selected.sort_unstable();
  2073. selected.dedup();
  2074. let n = entries
  2075. .iter()
  2076. .map(|u| u.table_offset_dwords / 8)
  2077. .chain(selected.last().copied())
  2078. .max()
  2079. .unwrap_or(0)
  2080. + 1;
  2081. let last = table.checked_add(u64::from(n - 1) * 32);
  2082. if n > crate::descriptor::host::DYNAMIC
  2083. || last.and_then(|handle| heap.index(handle)).is_none()
  2084. {
  2085. once!(slot, n, "fresh descriptor table exceeds the available span");
  2086. continue;
  2087. }
  2088. // The table and what its entries hold (record words).
  2089. let key = {
  2090. use std::hash::{Hash, Hasher};
  2091. let mut h = std::collections::hash_map::DefaultHasher::new();
  2092. for k in 0..n {
  2093. let at = table + u64::from(k) * 32;
  2094. // SAFETY: a descriptor slot in title memory.
  2095. unsafe { (at as *const [u32; 3]).read_unaligned() }.hash(&mut h);
  2096. }
  2097. (table, n, h.finish())
  2098. };
  2099. if let Some(&first) = self.fresh_tables.get(&key) {
  2100. for u in entries.iter().filter(|u| u.kind != ResourceType::Cbv) {
  2101. let handle = table + u64::from(u.table_offset_dwords) * 4;
  2102. if let Some(view) = crate::descriptor::view(handle) {
  2103. readable(list, u.kind, &view);
  2104. }
  2105. }
  2106. for k in selected {
  2107. if entries.iter().any(|u| u.table_offset_dwords / 8 == k) {
  2108. continue;
  2109. }
  2110. let handle = table + u64::from(k) * 32;
  2111. if let Some(view) = crate::descriptor::view(handle)
  2112. && let Some(kind) = view_kind(&view)
  2113. {
  2114. readable(list, kind, &view);
  2115. }
  2116. }
  2117. made.push((slot, first * 32));
  2118. continue;
  2119. }
  2120. let Some(first) = host.dynamic(n) else {
  2121. // No room: the draw must not run with the title's own
  2122. // offsets (slots never made for it); `bind` drops it.
  2123. made.push((slot, u32::MAX));
  2124. continue;
  2125. };
  2126. self.fresh_tables.insert(key, first);
  2127. self.dynamic
  2128. .push((std::ptr::from_ref(heap) as usize, first, n));
  2129. // The title's own slots of this table: what the draw reads of
  2130. // them it brings up to date here, in the dynamic slots.
  2131. let title_first = heap.index(table).filter(|first| first + n <= host.count());
  2132. // The whole range: a shader may index past the entries its
  2133. // used-resource list names (descriptor arrays).
  2134. for k in 0..n {
  2135. let index = first + k;
  2136. let used = entries.iter().find(|u| u.table_offset_dwords / 8 == k);
  2137. match crate::descriptor::view(table + u64::from(k) * 32) {
  2138. Some(View::Constant(address, size)) => {
  2139. let Some((gpu, to)) = list.scratch(u64::from(size)) else {
  2140. host.make_null(index);
  2141. continue;
  2142. };
  2143. let slot = (std::ptr::from_ref(heap) as usize, index);
  2144. list.defer_constants(to, address as *const u8, size as usize, slot);
  2145. host.constant_at(index, gpu, size);
  2146. }
  2147. Some(view) => {
  2148. host.make_at(index, &view);
  2149. let kind = used.map(|u| u.kind).or_else(|| {
  2150. selected.binary_search(&k).ok().and_then(|_| view_kind(&view))
  2151. });
  2152. if let Some(kind) = kind {
  2153. readable(list, kind, &view);
  2154. }
  2155. // The title's slot is a table's: out of the queue
  2156. // of textures picked by index if the draw read it
  2157. // (its texture is up to date now), and made in
  2158. // place as the texture pass would have made it,
  2159. // for a shader that picks it by index all the same.
  2160. if let Some(title) = title_first
  2161. && crate::descriptor::host::is_texture_view(&view)
  2162. {
  2163. host.texture_slot_tabled(title + k, kind.is_some());
  2164. if kind.is_some() {
  2165. host.mirror(title + k, table + u64::from(k) * 32, true);
  2166. }
  2167. }
  2168. }
  2169. None => {
  2170. host.make_null(index);
  2171. if used.is_some() {
  2172. once!(slot, "a table entry without a view");
  2173. }
  2174. }
  2175. }
  2176. }
  2177. made.push((slot, first * 32));
  2178. }
  2179. made
  2180. }
  2181. /// The first draws, at debug level: what they bind and read
  2182. /// (diagnostics builds).
  2183. #[cfg(feature = "diagnostics")]
  2184. fn trace(&self, kind: &str, count: u32, first: u32) {
  2185. static TRACED: AtomicU64 = AtomicU64::new(0);
  2186. if !tracing::enabled!(tracing::Level::DEBUG) {
  2187. return;
  2188. }
  2189. let listed = crate::capture::listed(crate::queue::presented() + 1);
  2190. let logged = listed || TRACED.fetch_add(1, Ordering::Relaxed) < 64;
  2191. let targets: Vec<String> = self
  2192. .targets
  2193. .iter()
  2194. .filter_map(|&t| crate::resource::host_made(t as This))
  2195. .map(|t| {
  2196. // SAFETY: a live resource.
  2197. let d = unsafe { t.GetDesc() };
  2198. format!("{}x{} f{}", d.Width, d.Height, d.Format.0)
  2199. })
  2200. .collect();
  2201. let v = self.vertex[0];
  2202. let line = format!(
  2203. "{kind} {count} from {first} topology {} pipeline {:#x} targets {targets:?} vb {:#x}+{} stride {} reads {:?}",
  2204. self.topology,
  2205. self.pipeline,
  2206. v.address,
  2207. v.size,
  2208. v.stride,
  2209. self.reads(false)
  2210. );
  2211. if logged {
  2212. tracing::debug!("draw {line}");
  2213. }
  2214. let mut frame = FRAME.lock().unwrap_or_else(|e| e.into_inner());
  2215. if frame.len() < 256 {
  2216. frame.push(line);
  2217. }
  2218. }
  2219. /// What a draw's shaders read, one line per used resource (diagnostics
  2220. /// builds).
  2221. #[cfg(feature = "diagnostics")]
  2222. fn reads(&self, compute: bool) -> Vec<String> {
  2223. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2224. return vec!["no host pipeline".into()];
  2225. };
  2226. let mut out = Vec::new();
  2227. for stage in &p.stages {
  2228. let t = stage.translated();
  2229. for u in &t.used {
  2230. let what = match (u.root, self.roots_ref(compute).get(usize::from(u.slot))) {
  2231. (RootType::Table, Some(Root::Table(table))) => {
  2232. let handle = table + u64::from(u.table_offset_dwords) * 4;
  2233. describe(crate::descriptor::view(handle).as_ref())
  2234. }
  2235. (root, _) => format!("{root:?}"),
  2236. };
  2237. out.push(format!(
  2238. "{} {:?} s{}+{}: {what}",
  2239. stage.shader.hash, u.kind, u.slot, u.table_offset_dwords
  2240. ));
  2241. }
  2242. }
  2243. out
  2244. }
  2245. pub(crate) fn draw(
  2246. &mut self,
  2247. list: &HostList,
  2248. vertices: u32,
  2249. instances: u32,
  2250. first: u32,
  2251. first_instance: u32,
  2252. ) {
  2253. self.window = None;
  2254. #[cfg(feature = "diagnostics")]
  2255. self.trace("draw", vertices, first);
  2256. let ready = self.prepare(list, false);
  2257. // A pipeline with the rectangle geometry stage draws the title's
  2258. // vertices as they are; any other gets its rectangles expanded.
  2259. let rects = self.topology == RECTANGLES && !self.completes_rects();
  2260. let ran = ready && (!rects || self.rectangles(list, vertices, first));
  2261. if ran {
  2262. // Rectangles were expanded into their own vertex buffers.
  2263. let (count, from) = if rects {
  2264. (vertices / 3 * 6, 0)
  2265. } else {
  2266. (vertices, first)
  2267. };
  2268. #[cfg(feature = "diagnostics")]
  2269. list.note_op(|| self.op_text(format!("draw {count}x{instances}"), false));
  2270. // SAFETY: an open list with everything set.
  2271. unsafe {
  2272. list.list
  2273. .DrawInstanced(count, instances, from, first_instance)
  2274. };
  2275. DRAWN.fetch_add(1, Ordering::Relaxed);
  2276. }
  2277. if !ran {
  2278. DROPPED.fetch_add(1, Ordering::Relaxed);
  2279. #[cfg(feature = "diagnostics")]
  2280. dropped(self.pipeline);
  2281. }
  2282. }
  2283. /// Whether the bound pipeline completes rectangles itself, in the
  2284. /// geometry stage rectangle pipelines get (`HostPipeline::rects`).
  2285. fn completes_rects(&self) -> bool {
  2286. crate::pipeline::host_pipeline(self.pipeline as This).is_some_and(|p| p.rects)
  2287. }
  2288. /// Binds vertex buffers holding the rectangles of vertices `first..first
  2289. /// + count` as triangles, made when the list is submitted.
  2290. fn rectangles(&self, list: &HostList, count: u32, first: u32) -> bool {
  2291. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2292. return false;
  2293. };
  2294. let rects = u64::from(count / 3);
  2295. for slot in 0..32 {
  2296. let elements: Vec<(u32, u32)> = p
  2297. .inputs
  2298. .iter()
  2299. .filter(|e| e.slot == slot && !e.per_instance)
  2300. .map(|e| (e.offset, e.format))
  2301. .collect();
  2302. if elements.is_empty() {
  2303. continue;
  2304. }
  2305. let v = self.vertex[slot as usize];
  2306. let stride = u64::from(v.stride);
  2307. let from = v.address + u64::from(first) * stride;
  2308. if v.address == 0
  2309. || stride == 0
  2310. || u64::from(first + count) * stride > u64::from(v.size)
  2311. || crate::shadow::find(from, rects * 3 * stride).is_none()
  2312. {
  2313. once!(slot, "rectangle vertices outside their buffer");
  2314. return false;
  2315. }
  2316. let Some((gpu, to)) = list.scratch(rects * 6 * stride) else {
  2317. return false;
  2318. };
  2319. let (from, to, stride) = (from as usize, to as usize, stride as usize);
  2320. let n = rects as usize;
  2321. list.defer_host_read(from, n * 3 * stride, move || {
  2322. // The vertices are read in place, at submission: no change
  2323. // of mapping under the read (see
  2324. // `crate::watch::title_memory_reading`).
  2325. let _mapped = crate::watch::title_memory_reading();
  2326. // SAFETY: the vertices lie in a title buffer (checked when
  2327. // recorded) and the scratch memory is the list's.
  2328. let (src, dst) = unsafe {
  2329. (
  2330. std::slice::from_raw_parts(from as *const u8, n * 3 * stride),
  2331. std::slice::from_raw_parts_mut(to as *mut u8, n * 6 * stride),
  2332. )
  2333. };
  2334. crate::primitive::expand_rects(src, dst, stride, &elements);
  2335. });
  2336. let view = D3D12_VERTEX_BUFFER_VIEW {
  2337. BufferLocation: gpu,
  2338. SizeInBytes: (rects * 6 * stride as u64) as u32,
  2339. StrideInBytes: v.stride,
  2340. };
  2341. // SAFETY: an open list; the view names live scratch memory.
  2342. unsafe { list.list.IASetVertexBuffers(slot, Some(&[view])) };
  2343. }
  2344. true
  2345. }
  2346. pub(crate) fn draw_indexed(
  2347. &mut self,
  2348. list: &HostList,
  2349. indices: u32,
  2350. instances: u32,
  2351. first: u32,
  2352. base: i32,
  2353. first_instance: u32,
  2354. ) {
  2355. self.window = None;
  2356. #[cfg(feature = "diagnostics")]
  2357. self.trace("indexed", indices, first);
  2358. // Indexed rectangles are drawn by the rectangle geometry stage
  2359. // alone (nothing expands them on the CPU).
  2360. let lost = self.topology == RECTANGLES && !self.completes_rects();
  2361. if lost {
  2362. once!("indexed rectangles not drawn");
  2363. }
  2364. let ran = !lost && self.prepare(list, true);
  2365. if ran {
  2366. #[cfg(feature = "diagnostics")]
  2367. list.note_op(|| self.op_text(format!("indexed {indices}x{instances}"), false));
  2368. // SAFETY: an open list with everything set.
  2369. unsafe {
  2370. list.list
  2371. .DrawIndexedInstanced(indices, instances, first, base, first_instance)
  2372. };
  2373. DRAWN.fetch_add(1, Ordering::Relaxed);
  2374. }
  2375. if !ran {
  2376. DROPPED.fetch_add(1, Ordering::Relaxed);
  2377. #[cfg(feature = "diagnostics")]
  2378. dropped(self.pipeline);
  2379. }
  2380. }
  2381. }
  2382. impl State {
  2383. /// Indirect execution of a one-argument signature of `kind` (PC
  2384. /// numbering: 0 draw, 1 indexed draw, 2 dispatch, 10 mesh dispatch) with
  2385. /// records `stride` bytes apart at title address `arguments`, and the
  2386. /// record count at `count` if the title gives one: the GPU reads them
  2387. /// from the buffer's host copy, where earlier dispatches may have
  2388. /// written them. False if it cannot run on the host.
  2389. pub(crate) fn execute_indirect(
  2390. &mut self,
  2391. list: &HostList,
  2392. (kind, stride, max): (u32, u32, u32),
  2393. arguments: u64,
  2394. count: Option<u64>,
  2395. ) -> bool {
  2396. // Skip before the argument clamp can mutate the indirect buffer.
  2397. #[cfg(feature = "diagnostics")]
  2398. if crate::pipeline::is_skipped(self.pipeline as This) {
  2399. crate::pipeline::note_drop(self.pipeline as This);
  2400. return false;
  2401. }
  2402. if crate::pipeline::is_builder(self.pipeline as This) && !crate::pipeline::builder_runs() {
  2403. return false;
  2404. }
  2405. const DRAW: u32 = 0;
  2406. const INDEXED: u32 = 1;
  2407. const DISPATCH: u32 = 2;
  2408. const MESH: u32 = 10;
  2409. #[cfg(feature = "diagnostics")]
  2410. let why = |what: &str| crate::pipeline::note_why(format!("indirect kind {kind}: {what}"));
  2411. #[cfg(not(feature = "diagnostics"))]
  2412. let why = |_: &str| {};
  2413. let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else {
  2414. #[cfg(feature = "diagnostics")]
  2415. crate::pipeline::note_drop(self.pipeline as This);
  2416. return false;
  2417. };
  2418. // Indirect rectangles (the title's tiled lighting, 256
  2419. // indirect draws a frame, makes their corners from the vertex
  2420. // number) are completed by the pipeline's geometry stage: the
  2421. // arguments stay the title's, three vertices a rectangle. They
  2422. // cannot be expanded on the CPU, which does not know their count.
  2423. // shortcut: in a pipeline without that stage, a rectangle with no
  2424. // per-vertex inputs is drawn as its first triangle (three vertices,
  2425. // half of it), and one with vertex buffers is not drawn.
  2426. let made_rects = !p.rects
  2427. && kind == DRAW
  2428. && self.topology == RECTANGLES
  2429. && !p.inputs.iter().any(|e| !e.per_instance);
  2430. if made_rects {
  2431. once!("indirect rectangles without vertex inputs drawn as their first triangle");
  2432. }
  2433. let matches_kind = match kind {
  2434. DRAW | INDEXED => {
  2435. (self.topology != RECTANGLES || made_rects || p.rects) && !p.compute && !p.mesh
  2436. }
  2437. MESH => !p.compute && p.mesh,
  2438. DISPATCH => p.compute,
  2439. _ => false,
  2440. };
  2441. if !matches_kind {
  2442. why(&format!(
  2443. "pipeline mismatch (compute {}, mesh {}, topology {})",
  2444. p.compute, p.mesh, self.topology
  2445. ));
  2446. return false;
  2447. }
  2448. let len = u64::from(stride) * u64::from(max.max(1));
  2449. let Some(args) = crate::shadow::find_any(arguments, len) else {
  2450. why("arguments outside title buffers");
  2451. return false;
  2452. };
  2453. let counter = match count {
  2454. Some(at) => match crate::shadow::find_any(at, 4) {
  2455. Some(s) => Some((s, at)),
  2456. None => {
  2457. why("count outside title buffers");
  2458. return false;
  2459. }
  2460. },
  2461. None => None,
  2462. };
  2463. let Some(signature) = matches!(kind, DRAW | INDEXED | DISPATCH | MESH)
  2464. .then(|| host_signature(kind, stride))
  2465. .flatten()
  2466. else {
  2467. why("no host signature");
  2468. return false;
  2469. };
  2470. if kind == MESH && (mesh_test() == 1 || !mesh_kept(self.pipeline)) {
  2471. why("mesh draws are switched off (VICTORY_MESH_TEST=skip)");
  2472. return false;
  2473. }
  2474. // A window of records clamped in one pass (`windows`): for single
  2475. // records without a count buffer, drawn by shaders that store to no
  2476. // buffer. Anything else ends the window: it uses the scratch buffer
  2477. // or may write the arguments.
  2478. const WINDOW_USE: usize = usize::MAX - 0x77;
  2479. let offset = args.offset(arguments);
  2480. let windowed = windows()
  2481. && kind != DISPATCH
  2482. && max == 1
  2483. && count.is_none()
  2484. && !p.stages.iter().any(|stage| stage.translated().stores);
  2485. // Another host list (a new one after a cut, or this one after its
  2486. // reset) has another scratch buffer, or this one's with old bytes.
  2487. if !windowed || list.first_use(WINDOW_USE) {
  2488. self.window = None;
  2489. }
  2490. let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride;
  2491. let hit = self
  2492. .window
  2493. .as_ref()
  2494. .filter(|w| same(w) && offset >= w.base)
  2495. .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records))
  2496. .map(|w| (w.scratch.clone(), offset - w.base));
  2497. let (bounded, at) = match hit {
  2498. Some(hit) => hit,
  2499. None => {
  2500. // A record a short step after the last window's last one
  2501. // (the same step as that window's, if it had one): the
  2502. // title walks the buffer, so the ones that step apart
  2503. // after it are clamped with it.
  2504. let (step, records) = match &self.window {
  2505. Some(w) if windowed && same(w) => {
  2506. let last = w.base + u64::from(w.records - 1) * u64::from(w.step);
  2507. let step = offset.saturating_sub(last);
  2508. let walks = step >= u64::from(stride)
  2509. && step <= 256
  2510. && step % 4 == 0
  2511. && (w.records == 1 || step == u64::from(w.step));
  2512. if walks {
  2513. let fit = (args.left(arguments) / step).min(WINDOW_MOST) as u32;
  2514. (step as u32, (if w.records == 1 { 16 } else { w.records * 2 }).min(fit).max(1))
  2515. } else {
  2516. (stride, max)
  2517. }
  2518. }
  2519. _ => (stride, max),
  2520. };
  2521. args.refresh(list, arguments, len.max(u64::from(step) * u64::from(records)));
  2522. if let Some((s, at)) = &counter {
  2523. s.refresh(list, *at, 4);
  2524. }
  2525. // Bounded first: the clamp binds a compute pipeline of its
  2526. // own and copies clamped active records into a scratch
  2527. // buffer at offset 0.
  2528. let count_arg = counter.as_ref().map(|(s, at)| (&s.buffer, s.offset(*at)));
  2529. // More than the record asked for: a window clamped ahead,
  2530. // whose unfilled slots must not spend the list's budget.
  2531. let bounded = if windowed && records > 1 {
  2532. crate::indirect::bound_ahead(list, (&args.buffer, offset), (kind, step, records))
  2533. } else {
  2534. crate::indirect::bound(list, (&args.buffer, offset), count_arg, (kind, step, records))
  2535. };
  2536. let Some(bounded) = bounded else {
  2537. self.window = None;
  2538. why("not bounded (no clamp, or arguments not 4-byte aligned)");
  2539. return false;
  2540. };
  2541. self.host_pipeline = 0;
  2542. self.host_roots[1] = 0;
  2543. self.window = windowed.then(|| Window {
  2544. copy: args.id(),
  2545. kind,
  2546. stride,
  2547. step,
  2548. base: offset,
  2549. records,
  2550. scratch: bounded.clone(),
  2551. });
  2552. (bounded, 0)
  2553. }
  2554. };
  2555. let ran = match kind {
  2556. DRAW | INDEXED => self.prepare(list, kind == INDEXED),
  2557. MESH => self.prepare_for(list, false, true),
  2558. DISPATCH => self.bind(list, p, true),
  2559. _ => false,
  2560. };
  2561. if !ran {
  2562. why("prepare failed");
  2563. return false;
  2564. }
  2565. #[cfg(feature = "diagnostics")]
  2566. list.note_op(|| {
  2567. self.op_text(format!("indirect kind {kind} max {max} at {arguments:#x}"), kind == DISPATCH)
  2568. });
  2569. if kind == MESH {
  2570. self.mesh_scissor(list, true);
  2571. }
  2572. // SAFETY: an open list with everything set; the scratch buffer and
  2573. // host copies are kept alive by the list, and the signature is cached.
  2574. unsafe {
  2575. list.list.ExecuteIndirect(
  2576. &signature,
  2577. max,
  2578. &bounded,
  2579. at,
  2580. counter.as_ref().map(|(s, _)| &s.buffer),
  2581. counter.as_ref().map_or(0, |(s, at)| s.offset(*at)),
  2582. )
  2583. };
  2584. if kind == MESH {
  2585. self.mesh_scissor(list, false);
  2586. }
  2587. // The scratch buffer stays readable as arguments: the next draw of
  2588. // the window reads it with no barrier, and the next clamp moves it
  2589. // back (`crate::indirect`).
  2590. if kind == DISPATCH {
  2591. DISPATCHED.fetch_add(1, Ordering::Relaxed);
  2592. } else {
  2593. DRAWN.fetch_add(1, Ordering::Relaxed);
  2594. }
  2595. true
  2596. }
  2597. }
  2598. /// The host command signature for one argument of `kind` with records
  2599. /// `stride` bytes apart (no root arguments, so no root signature), made
  2600. /// once.
  2601. fn host_signature(kind: u32, stride: u32) -> Option<ID3D12CommandSignature> {
  2602. static MADE: std::sync::Mutex<Vec<((u32, u32), ID3D12CommandSignature)>> =
  2603. std::sync::Mutex::new(Vec::new());
  2604. let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
  2605. if let Some((_, s)) = made.iter().find(|(k, _)| *k == (kind, stride)) {
  2606. return Some(s.clone());
  2607. }
  2608. let argument = D3D12_INDIRECT_ARGUMENT_DESC {
  2609. Type: D3D12_INDIRECT_ARGUMENT_TYPE(kind as i32),
  2610. ..Default::default()
  2611. };
  2612. let desc = D3D12_COMMAND_SIGNATURE_DESC {
  2613. ByteStride: stride,
  2614. NumArgumentDescs: 1,
  2615. pArgumentDescs: &argument,
  2616. NodeMask: 0,
  2617. };
  2618. let mut signature: Option<ID3D12CommandSignature> = None;
  2619. // SAFETY: a description of one argument; no root arguments.
  2620. let result = unsafe {
  2621. crate::host::host()?.device.CreateCommandSignature(
  2622. &desc,
  2623. None::<&ID3D12RootSignature>,
  2624. &mut signature,
  2625. )
  2626. };
  2627. if let Err(e) = result {
  2628. once!(error = %e, kind, stride, "host command signature refused");
  2629. return None;
  2630. }
  2631. let signature = signature?;
  2632. made.push(((kind, stride), signature.clone()));
  2633. Some(signature)
  2634. }
  2635. /// Gets what a shader reads or writes through a view ready: buffer data
  2636. /// copied, textures moved to the state they need.
  2637. fn view_kind(view: &View) -> Option<ResourceType> {
  2638. match view {
  2639. View::Shader(..) | View::Placed(false, ..) => Some(ResourceType::Srv),
  2640. View::Unordered(..) | View::Placed(true, ..) => Some(ResourceType::Uav),
  2641. _ => None,
  2642. }
  2643. }
  2644. /// The host state a depth view needs of its texture: the read state if the
  2645. /// view writes no plane the format has (the title's read-only flags), else
  2646. /// the write state.
  2647. /// shortcut: whole textures have one state, so a view that writes one of
  2648. /// two planes counts as writing.
  2649. fn depth_state(texture: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>) -> u32 {
  2650. // D16_UNORM and D32_FLOAT: depth formats without a stencil plane.
  2651. const ONE_PLANE: [i32; 2] = [55, 40];
  2652. let Some(desc) = desc else {
  2653. return DEPTH_WRITE;
  2654. };
  2655. let format = if desc.Format.0 == 0 {
  2656. // SAFETY: a live texture; a view without a format has its own.
  2657. unsafe { texture.GetDesc() }.Format.0
  2658. } else {
  2659. desc.Format.0
  2660. };
  2661. let mut needed = D3D12_DSV_FLAG_READ_ONLY_DEPTH.0;
  2662. if !ONE_PLANE.contains(&format) {
  2663. needed |= D3D12_DSV_FLAG_READ_ONLY_STENCIL.0;
  2664. }
  2665. if desc.Flags.0 & needed == needed {
  2666. DEPTH_READ
  2667. } else {
  2668. DEPTH_WRITE
  2669. }
  2670. }
  2671. fn readable(list: &HostList, kind: ResourceType, view: &View) {
  2672. const UNORDERED_ACCESS: u32 = 0x8;
  2673. let placed = crate::descriptor::host::placed_texture(view);
  2674. let view = placed.as_ref().unwrap_or(view);
  2675. // Buffer views read title memory: their range is copied at submission;
  2676. // what shaders write through unordered access goes back to it after.
  2677. if let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(view) {
  2678. shadow.refresh(list, address, len);
  2679. if kind == ResourceType::Uav {
  2680. // A shader that cannot store to buffers leaves the range as
  2681. // the title has it: nothing to find afterwards.
  2682. if STORES.get() || !write_skip() {
  2683. #[cfg(feature = "diagnostics")]
  2684. crate::host::wide_write(address, len, 0);
  2685. shadow.gpu_writes(list, address, len);
  2686. } else {
  2687. #[cfg(feature = "diagnostics")]
  2688. {
  2689. crate::copystat::add(crate::copystat::C::GpuWritesLeftOut, 1);
  2690. crate::copystat::add(crate::copystat::C::GpuWritesLeftOutBytes, len);
  2691. }
  2692. }
  2693. }
  2694. }
  2695. match (view, kind) {
  2696. (View::Shader(resource, _), ResourceType::Srv) => {
  2697. // A view the title placed, in another format, in the memory of
  2698. // a texture the host writes: that texture's texels, copied on
  2699. // the host (title memory does not have them).
  2700. let aliased = crate::resource::alias_of(*resource as This)
  2701. .is_some_and(|source| crate::texture::alias(list, *resource as This, source));
  2702. if !aliased
  2703. && let Some(t) = crate::resource::host_resource(*resource as This)
  2704. && crate::texture::title_written(t)
  2705. {
  2706. crate::texture::upload(list, *resource as This, t);
  2707. }
  2708. // A depth texture shaders also write: what they wrote, first.
  2709. list.twin_use(*resource as This, false, false);
  2710. // The depth target the draw only tests is read in both ways at
  2711. // once: both read states, which its preparation asks for too.
  2712. let (tested, _) = TESTED_DEPTH.get();
  2713. let state = if tested != 0 && tested == *resource {
  2714. TESTED_DEPTH.set((tested, true));
  2715. DEPTH_READ | SHADER_RESOURCE
  2716. } else {
  2717. SHADER_RESOURCE
  2718. };
  2719. crate::list::ensure_state(list, *resource as This, state);
  2720. #[cfg(feature = "diagnostics")]
  2721. if let Some(t) = crate::resource::host_resource(*resource as This) {
  2722. // SAFETY: a live resource.
  2723. let d = unsafe { t.GetDesc() };
  2724. if d.Flags.0 & 7 == 0 {
  2725. tracing::debug!(
  2726. resource = format_args!("{resource:#x}"),
  2727. ?d,
  2728. "a shader reads a texture the title fills"
  2729. );
  2730. }
  2731. }
  2732. }
  2733. (View::Unordered(resource, _, _), ResourceType::Uav) => {
  2734. #[cfg(feature = "diagnostics")]
  2735. crate::capture::note_target(*resource as This);
  2736. // Unordered access to a depth texture is its colour twin's.
  2737. if !list.twin_use(*resource as This, true, true) {
  2738. crate::list::ensure_state(list, *resource as This, UNORDERED_ACCESS);
  2739. }
  2740. }
  2741. _ => {}
  2742. }
  2743. }
  2744. /// A view in a few words (diagnostics builds).
  2745. #[cfg(feature = "diagnostics")]
  2746. fn describe(view: Option<&View>) -> String {
  2747. let texture = |r: This| {
  2748. crate::resource::host_made(r).map(|t| {
  2749. // SAFETY: a live resource.
  2750. let d = unsafe { t.GetDesc() };
  2751. format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0)
  2752. })
  2753. };
  2754. match view {
  2755. None => "no view".into(),
  2756. Some(v @ View::Shader(r, _)) => texture(*r as This)
  2757. .unwrap_or_else(|| format!("buffer {:?}", crate::descriptor::host::buffer_range(v))),
  2758. Some(v @ View::Unordered(r, ..)) => match texture(*r as This) {
  2759. Some(t) => format!("uav texture {t}"),
  2760. None => format!(
  2761. "uav resource {r:#x} buffer {:?}",
  2762. crate::descriptor::host::buffer_range(v)
  2763. ),
  2764. },
  2765. Some(View::Placed(u, r, d)) => format!(
  2766. "placed uav={u} dim {} {}x{} f{} layout {:#x} at {:#x}",
  2767. r[0],
  2768. u64::from(r[4]) | u64::from(r[5]) << 32,
  2769. r[6],
  2770. r[8],
  2771. r[11],
  2772. u64::from(d[10]) | u64::from(d[11]) << 32
  2773. ),
  2774. // The first four values, as a colour rectangle's constants are.
  2775. Some(View::Constant(address, size))
  2776. if *size >= 16 && crate::texture::committed(*address as *const u8, 16) =>
  2777. {
  2778. // SAFETY: 16 committed bytes of title memory.
  2779. let v = unsafe { (*address as *const [f32; 4]).read_unaligned() };
  2780. format!("Constant({address:#x}, {size}) {v:?}")
  2781. }
  2782. Some(v) => format!("{v:?}").chars().take(60).collect(),
  2783. }
  2784. }
  2785. /// The console's own primitive topologies.
  2786. const TRIANGLE_FAN: u32 = 6;
  2787. const RECTANGLES: u32 = 17;
  2788. const LINE_LOOP: u32 = 18;
  2789. const QUADS: u32 = 19;
  2790. const QUAD_STRIP: u32 = 20;
  2791. /// Fixed-function state, straight onto the host list.
  2792. pub(crate) fn viewports(list: &HostList, viewports: &[D3D12_VIEWPORT]) {
  2793. // SAFETY: an open list.
  2794. unsafe { list.list.RSSetViewports(viewports) };
  2795. }
  2796. pub(crate) fn scissors(list: &HostList, rects: &[RECT]) {
  2797. // SAFETY: an open list.
  2798. unsafe { list.list.RSSetScissorRects(rects) };
  2799. }
  2800. pub(crate) fn blend_factor(list: &HostList, factor: Option<&[f32; 4]>) {
  2801. // SAFETY: an open list.
  2802. unsafe { list.list.OMSetBlendFactor(factor) };
  2803. }
  2804. pub(crate) fn stencil_ref(list: &HostList, reference: u32) {
  2805. #[cfg(feature = "diagnostics")]
  2806. crate::capture::op(std::ptr::from_ref(list) as usize, || format!("STENCIL REF {reference:#x}"));
  2807. // SAFETY: an open list.
  2808. unsafe { list.list.OMSetStencilRef(reference) };
  2809. }
  2810. pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) {
  2811. #[cfg(feature = "diagnostics")]
  2812. crate::capture::op(std::ptr::from_ref(list) as usize, || {
  2813. format!("DEPTH BOUNDS {min}..{max}")
  2814. });
  2815. if crate::host::host().is_some_and(|h| h.depth_bounds())
  2816. && let Ok(l1) = list.list.cast::<ID3D12GraphicsCommandList1>()
  2817. {
  2818. // SAFETY: an open list on a device that supports depth bounds.
  2819. unsafe { l1.OMSetDepthBounds(min, max) };
  2820. }
  2821. }
  2822. /// Per-frame texture staging byte budget scaled from the adapter's local VRAM
  2823. /// budget (`None` keeps the 192 MiB 12 GiB baseline).
  2824. fn staging_budget_per_frame(vram_budget: Option<u64>) -> u64 {
  2825. const GIB: u64 = 1 << 30;
  2826. const MIB: u64 = 1 << 20;
  2827. match vram_budget {
  2828. Some(budget) if budget <= 6 * GIB => 96 * MIB,
  2829. Some(budget) if budget >= 20 * GIB => 384 * MIB,
  2830. Some(budget) if budget > 12 * GIB => 256 * MIB,
  2831. _ => 192 * MIB,
  2832. }
  2833. }
  2834. #[cfg(test)]
  2835. mod tests {
  2836. use super::staging_budget_per_frame;
  2837. #[test]
  2838. fn staging_budget_scales_with_vram_budget() {
  2839. const GIB: u64 = 1 << 30;
  2840. const MIB: u64 = 1 << 20;
  2841. assert_eq!(staging_budget_per_frame(None), 192 * MIB);
  2842. assert_eq!(staging_budget_per_frame(Some(4 * GIB)), 96 * MIB);
  2843. assert_eq!(staging_budget_per_frame(Some(6 * GIB)), 96 * MIB);
  2844. assert_eq!(staging_budget_per_frame(Some(8 * GIB)), 192 * MIB);
  2845. assert_eq!(staging_budget_per_frame(Some(12 * GIB)), 192 * MIB);
  2846. assert_eq!(staging_budget_per_frame(Some(13 * GIB)), 256 * MIB);
  2847. assert_eq!(staging_budget_per_frame(Some(14 * GIB)), 256 * MIB);
  2848. assert_eq!(staging_budget_per_frame(Some(16 * GIB)), 256 * MIB);
  2849. assert_eq!(staging_budget_per_frame(Some(20 * GIB)), 384 * MIB);
  2850. assert_eq!(staging_budget_per_frame(Some(24 * GIB)), 384 * MIB);
  2851. assert_eq!(staging_budget_per_frame(Some(32 * GIB)), 384 * MIB);
  2852. }
  2853. }