draw.rs 156 KB

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