host.rs 171 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891
  1. //! Host descriptor heaps behind the title's shader-visible heaps (decision
  2. //! 0007, step 3). Translated shaders index the heaps directly at the
  3. //! title's descriptor positions, so each host heap keeps the title heap's
  4. //! order: slot `i` is made from what the title wrote at slot `i`, when it
  5. //! writes it (view creation and descriptor copies) and again when a draw
  6. //! reads it through a table and finds the slot changed.
  7. use std::sync::Mutex;
  8. use windows::Win32::Graphics::Direct3D12::*;
  9. use windows::Win32::Graphics::Dxgi::Common::*;
  10. use super::{VIEW_TAG, View, view_at};
  11. use crate::host::host;
  12. pub(crate) struct HostHeap {
  13. pub(crate) heap: ID3D12DescriptorHeap,
  14. cpu: usize,
  15. step: u32,
  16. /// Slots mirroring the title's; view heaps have `dynamic` more.
  17. count: u32,
  18. /// Dynamic slots past `count`: [`DYNAMIC`] in view heaps, none in
  19. /// sampler heaps. (Upstream falls back to 2^16 on a capped host heap;
  20. /// ours keeps 2^18 there: 2^16 and 2^17 both ran out in this title.)
  21. dynamic: u32,
  22. sampler: bool,
  23. /// The record (view index and generation) each slot was last made from.
  24. made: Mutex<Vec<u64>>,
  25. /// The same for a slot whose descriptor is made and stays (else 0): what
  26. /// [`HostHeap::mirror`] asks first, without the lock. Changed under it.
  27. quick: Vec<std::sync::atomic::AtomicU64>,
  28. /// The records of the title's heap as the pass over records copied in
  29. /// as bytes last saw them ([`HostHeap::copied_changes`]). Made on first
  30. /// use.
  31. copied: Mutex<Vec<u8>>,
  32. /// New ones of them that wait for a draw ([`HostHeap::copied_wait`]),
  33. /// by the frame they were found in.
  34. waiting: Mutex<std::collections::VecDeque<(u64, Vec<u32>)>>,
  35. /// The slots made from a texture whose memory was found away, with what
  36. /// they were made from and when that was
  37. /// ([`HostHeap::texture_slot_gone`]).
  38. away: Mutex<std::collections::HashMap<u32, (u64, u64)>>,
  39. /// The host resource each slot views, held while the slot does: shaders
  40. /// index heaps directly, so a slot the title has not rewritten since it
  41. /// released the resource may still be read, and a freed host resource
  42. /// read there is a GPU page fault (the console reads stale memory).
  43. kept: Mutex<Vec<Option<ID3D12Resource>>>,
  44. /// Where the search for free dynamic slots starts, and which are taken
  45. /// (by lists not yet reset).
  46. next: Mutex<(u32, Vec<bool>)>,
  47. /// How many dynamic slots are free (changed under `next`'s lock): with
  48. /// fewer than a table needs, the search is not made. Once the world
  49. /// had taken them all, every later table of the frame searched every
  50. /// slot before it was refused.
  51. free: std::sync::atomic::AtomicU32,
  52. /// The shortest table that found no run of free slots since slots were
  53. /// last given back (changed under `next`'s lock; `u32::MAX`: none).
  54. /// Until something is given back the free runs only shrink, so a table
  55. /// of that length or longer is refused without the search. Enough
  56. /// slots were free, but in pieces, and every such table walked the
  57. /// whole ring before it was refused: 0.33 ms each with 131,072 slots,
  58. /// 1.0 s of the recording threads in a frame that refused 3,143 (run
  59. /// 45), under the lock all of them need. (A free run that lies across
  60. /// the place the search starts from is seen by neither.)
  61. too_long: std::sync::atomic::AtomicU32,
  62. /// View heaps: the bytes per element of the buffer view at each title
  63. /// slot, for shaders that pick a buffer by an index they compute
  64. /// (`victory_shader::emit::SLOT_STRIDES`): an upload buffer of
  65. /// `SLOT_STRIDES_COUNT` dwords, its GPU address and its mapping.
  66. strides: Option<(ID3D12Resource, u64, usize)>,
  67. /// Title slots holding buffer views. Such a view gets its host slot
  68. /// (and its memory a host copy) only when something reads it: a draw
  69. /// through a table, or [`HostHeap::buffer_slots`] for shaders that pick
  70. /// buffers from the whole heap.
  71. buffers: Mutex<std::collections::BTreeSet<u32>>,
  72. /// Of those and of the slots that left the set: the ones written since
  73. /// [`HostHeap::buffer_changes`] last took them.
  74. changed: Mutex<std::collections::HashSet<u32>>,
  75. /// Title slots holding a view of a texture the title may fill itself (a
  76. /// placed texture, a texture object), with the frame from which they
  77. /// are due: such a texture is uploaded when a draw reads it through a
  78. /// table; one a shader picks by a computed index is brought up to date
  79. /// from here ([`HostHeap::texture_slots_due`]).
  80. textures: Mutex<TextureQueue>,
  81. /// Per title slot, the frame (plus one; 0: never) in which a draw last
  82. /// read it through a table, or made a table it lies in (with
  83. /// [`TABLED_READ`] set if the draw read it). The draw that
  84. /// reads such a slot brings its texture up to date itself and the slot
  85. /// then leaves `textures`; a write of a slot that was a table's within
  86. /// the last [`TABLED_FRAMES`] frames is due only [`TABLED_GRACE`]
  87. /// frames later, by when its draw has read it. A title that builds a
  88. /// table per draw writes thousands of texture views a frame into slots
  89. /// only tables read (the title: some 2,500 a frame in its
  90. /// opening cutscene, a few hundred textures over and over), and every
  91. /// one of them stood in the queue of textures picked by index, ahead
  92. /// of or behind the ones shaders do pick by index.
  93. tabled: Vec<std::sync::atomic::AtomicU32>,
  94. /// The title memory each placed texture view of this heap describes,
  95. /// by slot and by address ([`Spans`]): which slots a newer view of
  96. /// other memory there makes stale, and which to look at again when the
  97. /// runtime maps, unmaps or writes memory ([`remapped`]).
  98. placed: std::sync::Arc<Mutex<Spans>>,
  99. }
  100. /// The spans of every view heap made ([`HostHeap::placed`]), for the
  101. /// texture code, which has no heap at hand ([`next_start`],
  102. /// [`first_viewed`]).
  103. static PLACED_SPANS: Mutex<Vec<std::sync::Weak<Mutex<Spans>>>> = Mutex::new(Vec::new());
  104. /// Where the next texture placed inside `[start, end)` starts, past the
  105. /// first bytes of the one at `start` ([`HEAD`]): what is there of the
  106. /// texture at `start` ends there, whatever its full size. `None`: no view
  107. /// in a slot shaders pick by index describes memory in that range.
  108. pub(crate) fn next_start(start: u64, end: u64) -> Option<u64> {
  109. let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner());
  110. heaps
  111. .iter()
  112. .filter_map(std::sync::Weak::upgrade)
  113. .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end))
  114. .min()
  115. }
  116. /// The lowest level that a view of the placed texture at `start` shows,
  117. /// over the slots shaders pick by index that hold one now. The title
  118. /// views a texture from the first level it holds. `None`: no such slot.
  119. pub(crate) fn first_viewed(start: u64) -> Option<u32> {
  120. let heaps = PLACED_SPANS.lock().unwrap_or_else(|e| e.into_inner());
  121. heaps
  122. .iter()
  123. .filter_map(std::sync::Weak::upgrade)
  124. .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start))
  125. .min()
  126. }
  127. /// Levels on demand (`crate::tiles`): where the placed textures start
  128. /// whose first level with memory changed since a texture pass last took
  129. /// them ([`HostHeap::texture_views_remade`]).
  130. static RESHOWN: Mutex<Vec<u64>> = Mutex::new(Vec::new());
  131. /// The first level with memory of the placed texture at `start` changed:
  132. /// its slots are made again at the next texture pass.
  133. pub(crate) fn levels_changed(start: u64) {
  134. RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start);
  135. }
  136. /// Levels on demand (`crate::tiles`): where the placed textures start
  137. /// whose last upload left a held level without tiles (the card had no
  138. /// room, or no heap could be had), and when (`crate::host::moment`). A
  139. /// texture pass makes their slots due again once the card has room
  140. /// ([`HostHeap::texture_slots_waiting`]).
  141. static WAITING: Mutex<std::collections::BTreeMap<u64, u64>> = Mutex::new(std::collections::BTreeMap::new());
  142. /// The last upload of the placed texture at `start` left a held level
  143. /// without tiles. A texture picked by index is uploaded once and then
  144. /// only when its memory is found changed, and its staging buffer goes
  145. /// with the upload: without this the level stayed empty (the texture
  146. /// blurred, or black if no level had tiles) for as long as the title left
  147. /// its memory alone, where a texture refused for want of room is tried
  148. /// again.
  149. pub(crate) fn levels_waiting(start: u64) {
  150. WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment());
  151. }
  152. /// Placed textures (by the start of their memory) filled while the runtime
  153. /// was remapping with less than was mapped of them
  154. /// (`crate::texture::fill_unlocked`), whose slots the next texture pass
  155. /// makes due again; and how often in a row that was, which ends it: memory
  156. /// that is shown and cannot be read would be uploaded again every frame.
  157. static SHORT: Mutex<(std::collections::BTreeSet<u64>, std::collections::BTreeMap<u64, u32>)> =
  158. Mutex::new((std::collections::BTreeSet::new(), std::collections::BTreeMap::new()));
  159. /// Fillings in a row of one texture that got less than was mapped, after
  160. /// which its slots wait for the next notice of its memory.
  161. const SHORT_IN_A_ROW: u32 = 8;
  162. /// The placed texture at `start` was filled with less than was mapped.
  163. pub(crate) fn read_short(start: u64) {
  164. let mut short = SHORT.lock().unwrap_or_else(|e| e.into_inner());
  165. let times = short.1.entry(start).or_insert(0);
  166. *times += 1;
  167. if *times <= SHORT_IN_A_ROW {
  168. short.0.insert(start);
  169. }
  170. }
  171. /// The placed texture at `start` was filled with all that was mapped.
  172. pub(crate) fn read_all(start: u64) {
  173. let mut short = SHORT.lock().unwrap_or_else(|e| e.into_inner());
  174. if !short.1.is_empty() {
  175. short.1.remove(&start);
  176. }
  177. }
  178. /// Title memory by the placed texture views that describe it: per span of
  179. /// memory (its start, its end at full size) the title slots holding a
  180. /// view of a texture that takes exactly that span. A console title need
  181. /// not clear a descriptor when it streams a texture out, so a newer view
  182. /// that cannot be there together with an older one is all that says the
  183. /// older one is stale ([`Rule`] says when that is). Views of one span with
  184. /// different descriptions (the formats of one family, say) are one
  185. /// texture's.
  186. ///
  187. /// Spans may overlap: a texture's smallest levels lie at the start of its
  188. /// memory, and a title that holds only those puts the next texture where
  189. /// the larger ones would be (the title: three 512x256 textures
  190. /// of 0x2c000 bytes each whose starts are 0x2000 and 0x4000 apart, all
  191. /// three read by the same frame's draws, run 188). What is there of a
  192. /// texture ends where the next one starts.
  193. /// No host heap is needed, so it is tested without one.
  194. #[derive(Default)]
  195. pub(crate) struct Spans {
  196. /// When a newer view makes an older one stale.
  197. rule: Rule,
  198. by_start: std::collections::BTreeMap<u64, (u64, std::collections::BTreeSet<u32>)>,
  199. by_slot: std::collections::HashMap<u32, u64>,
  200. /// The level each slot's view starts at ([`Spans::shows`]).
  201. first: std::collections::HashMap<u32, u32>,
  202. /// The bytes a placed texture takes, by resource description: worked
  203. /// out once for each (a title writes the views of a few thousand
  204. /// descriptions, thousands of times a frame).
  205. sizes: std::collections::HashMap<[u32; 14], Option<u64>>,
  206. }
  207. /// When a view the title writes makes an older view of other memory stale.
  208. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
  209. pub(crate) enum Rule {
  210. /// When it starts where the older one starts: at the same address
  211. /// with another length, or within the older one's first [`HEAD`]
  212. /// bytes (or the older within its own). No two textures share the
  213. /// block of their smallest levels. A view that only reaches into the
  214. /// address range of an older texture's larger levels says nothing.
  215. #[default]
  216. Start,
  217. /// Whenever their spans at full size overlap (the rule until run
  218. /// 188, where it made null the slots of textures packed as above:
  219. /// each view written took its neighbours out of the queue and off the
  220. /// card, for good). `VICTORY_STALE_TEXTURES=overlap`.
  221. Overlap,
  222. /// Never; a view that would be stale under [`Rule::Overlap`] is left
  223. /// out of the spans instead. `VICTORY_STALE_TEXTURES=0`, as before.
  224. Never,
  225. }
  226. /// The first bytes of a placed texture that are its own under
  227. /// [`Rule::Start`]: the 4 KiB block its smallest levels share. (Of 129
  228. /// pairs of overlapping neighbours in the listings of runs 188 and 189,
  229. /// none starts closer than 0x2000 to the one before it.)
  230. const HEAD: u64 = 4096;
  231. impl Spans {
  232. /// The bytes of title memory a placed texture with the resource
  233. /// description `desc` takes (`crate::resource::placed_bytes`).
  234. fn bytes(&mut self, desc: &[u32; 14]) -> Option<u64> {
  235. if let Some(&known) = self.sizes.get(desc) {
  236. return known;
  237. }
  238. let bytes = crate::resource::placed_bytes(desc);
  239. self.sizes.insert(*desc, bytes);
  240. bytes
  241. }
  242. /// The starts of the spans that overlap `[start, end)`, each taken to
  243. /// end where the next one starts: the last span that starts before
  244. /// `start`, if it reaches past it at full size, and every span that
  245. /// starts inside.
  246. fn overlapping(&self, start: u64, end: u64) -> Vec<u64> {
  247. let before = self
  248. .by_start
  249. .range(..start)
  250. .next_back()
  251. .filter(|(_, span)| span.0 > start)
  252. .map(|(at, _)| *at);
  253. before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect()
  254. }
  255. /// Slot `index` holds a view of a texture in `[start, end)`. `newer`:
  256. /// the title wrote it now, so the slots whose views cannot be there
  257. /// with it ([`Rule`]) are stale: they are returned, and forgotten.
  258. /// Otherwise (a draw made the slot from what it held), and under
  259. /// [`Rule::Never`], a view that clashes with other spans is left out.
  260. fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec<u32> {
  261. let same = |span: Option<&(u64, std::collections::BTreeSet<u32>)>| span.is_some_and(|s| s.0 == end);
  262. if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) {
  263. return Vec::new();
  264. }
  265. self.forget(index);
  266. if end <= start {
  267. return Vec::new();
  268. }
  269. let rule = self.rule;
  270. // The spans the view cannot be there with.
  271. let clashing: Vec<u64> = match rule {
  272. Rule::Start => self
  273. .by_start
  274. .range(start.saturating_sub(HEAD - 1)..start.saturating_add(HEAD))
  275. .map(|(at, _)| *at)
  276. .collect(),
  277. Rule::Overlap | Rule::Never => self.overlapping(start, end),
  278. };
  279. let mut stale = Vec::new();
  280. for at in clashing {
  281. if at == start && same(self.by_start.get(&at)) {
  282. continue;
  283. }
  284. if !newer || rule == Rule::Never {
  285. return stale;
  286. }
  287. if let Some((old_end, slots)) = self.by_start.remove(&at) {
  288. // The first of them are said with both spans, to tell a
  289. // replacement from a neighbour in one launch's log.
  290. static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  291. if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 48 {
  292. tracing::info!(
  293. slot = index,
  294. start = format_args!("{start:#x}"),
  295. end = format_args!("{end:#x}"),
  296. stale_start = format_args!("{at:#x}"),
  297. stale_end = format_args!("{old_end:#x}"),
  298. stale_slots = slots.len(),
  299. rule = ?rule,
  300. "a placed texture view makes older views of other memory stale"
  301. );
  302. }
  303. for slot in slots {
  304. self.by_slot.remove(&slot);
  305. stale.push(slot);
  306. }
  307. }
  308. }
  309. self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index);
  310. self.by_slot.insert(index, start);
  311. stale
  312. }
  313. /// The view in slot `index` starts at level `first` of its texture.
  314. fn shows(&mut self, index: u32, first: u32) {
  315. self.first.insert(index, first);
  316. }
  317. /// The lowest level a view of the texture at `start` starts at.
  318. fn first_viewed(&self, start: u64) -> Option<u32> {
  319. self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied()
  320. }
  321. /// The first span that starts inside `[start, end)` past the first
  322. /// [`HEAD`] bytes of it.
  323. fn next_start(&self, start: u64, end: u64) -> Option<u64> {
  324. self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at)
  325. }
  326. /// The slots that hold a view of the texture at `start`.
  327. fn slots_at(&self, start: u64) -> Vec<u32> {
  328. self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default()
  329. }
  330. /// Slot `index` holds no placed texture view any more.
  331. fn forget(&mut self, index: u32) {
  332. self.first.remove(&index);
  333. let Some(start) = self.by_slot.remove(&index) else {
  334. return;
  335. };
  336. if let Some(span) = self.by_start.get_mut(&start) {
  337. span.1.remove(&index);
  338. if span.1.is_empty() {
  339. self.by_start.remove(&start);
  340. }
  341. }
  342. }
  343. /// The slots whose texture's memory overlaps `[start, end)`.
  344. fn slots_in(&self, start: u64, end: u64) -> Vec<u32> {
  345. self.overlapping(start, end)
  346. .iter()
  347. .filter_map(|at| self.by_start.get(at))
  348. .flat_map(|span| span.1.iter().copied())
  349. .collect()
  350. }
  351. /// The slots of the textures that hold bytes of `[start, end)`, for a
  352. /// write there: as [`Spans::slots_in`], but when a texture starts at
  353. /// `start` itself the one before it is left out (it ends where that
  354. /// one starts, and a request that fills a texture begins at its first
  355. /// byte: `slots_in` would name its neighbour with every such write).
  356. fn slots_holding(&self, start: u64, end: u64) -> Vec<u32> {
  357. if end <= start {
  358. return Vec::new();
  359. }
  360. let before = if self.by_start.contains_key(&start) {
  361. None
  362. } else {
  363. self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span)
  364. };
  365. before
  366. .into_iter()
  367. .chain(self.by_start.range(start..end).map(|(_, span)| span))
  368. .flat_map(|span| span.1.iter().copied())
  369. .collect()
  370. }
  371. }
  372. /// Title memory written behind the guards' back whose bytes are there
  373. /// (DirectStorage's reads into physical pages, at the addresses the title
  374. /// has them mapped; `crate::watch::title_memory_written`), since a texture
  375. /// pass last took the ranges ([`page_written`]). Kept apart from
  376. /// [`REMAPPED`] so that what such writes do is counted by itself.
  377. static PAGE_WRITTEN: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
  378. /// Since the start: such ranges kept for a pass; ranges dropped because no
  379. /// pass took them; slots of placed textures that held bytes of them when a
  380. /// pass took them; of those, the slots whose texture had been uploaded
  381. /// before the write (out of the queue, or in it after an upload): they are
  382. /// the ones that kept the bytes from before, and the ones made due when
  383. /// `VICTORY_PAGE_WRITES` asks for it.
  384. pub(crate) static PAGE_WRITES: [std::sync::atomic::AtomicU64; 4] =
  385. [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  386. /// Frames from the pass that takes a written range to the look at its
  387. /// slots: the levels of one texture arrive in a few requests, and a look
  388. /// two frames on takes those of the next frame with it.
  389. const PAGE_WRITE_AFTER: u64 = 2;
  390. /// The bytes of a write the guards do not see are in title memory `[at,
  391. /// at + len)`: the placed textures there changed with no descriptor
  392. /// written and nothing mapped. Kept for the next texture pass
  393. /// ([`HostHeap::texture_slots_page_written`]), as [`remapped`] keeps its
  394. /// ranges; locks one mutex and calls nothing.
  395. pub(crate) fn page_written(at: usize, len: usize) {
  396. use std::sync::atomic::Ordering::Relaxed;
  397. /// Ranges kept until a pass takes them.
  398. const MOST: usize = 1 << 15;
  399. let (start, end) = (at as u64, at.saturating_add(len) as u64);
  400. if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) {
  401. return;
  402. }
  403. let mut ranges = PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
  404. PAGE_WRITES[0].fetch_add(1, Relaxed);
  405. if let Some(last) = ranges.last_mut()
  406. && last.1 == start
  407. {
  408. last.1 = end;
  409. return;
  410. }
  411. if ranges.len() >= MOST {
  412. PAGE_WRITES[1].fetch_add(ranges.len() as u64, Relaxed);
  413. ranges.clear();
  414. }
  415. ranges.push((start, end));
  416. }
  417. /// Title memory the runtime mapped, unmapped or is about to write since a
  418. /// texture pass last took the ranges ([`remapped`]).
  419. static REMAPPED: Mutex<Vec<(u64, u64)>> = Mutex::new(Vec::new());
  420. /// The lowest start and the highest end of any span of [`Spans`] so far
  421. /// (the start is `u64::MAX` until there is one): what the runtime does to
  422. /// memory outside is none of the texture pass's business.
  423. static SPANNED: [std::sync::atomic::AtomicU64; 2] = [
  424. std::sync::atomic::AtomicU64::new(u64::MAX),
  425. std::sync::atomic::AtomicU64::new(0),
  426. ];
  427. /// Since the start: slots whose view a newer view of other memory there
  428. /// made stale; ranges of memory noted as mapped, unmapped or written;
  429. /// ranges dropped because no pass took them; slots made due by such
  430. /// ranges; and made slots whose memory was found unmapped (made null).
  431. pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] =
  432. [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  433. /// When a view the title writes makes older views of other memory stale
  434. /// ([`Rule`]): where it starts in the block of their smallest levels, by
  435. /// default; `VICTORY_STALE_TEXTURES=0`: never, as before;
  436. /// `VICTORY_STALE_TEXTURES=overlap`: wherever their spans overlap, the rule
  437. /// until run 188.
  438. fn stale_rule() -> Rule {
  439. static RULE: std::sync::OnceLock<Rule> = std::sync::OnceLock::new();
  440. *RULE.get_or_init(|| match std::env::var("VICTORY_STALE_TEXTURES").as_deref() {
  441. Ok("0") => Rule::Never,
  442. Ok("overlap") => Rule::Overlap,
  443. _ => Rule::Start,
  444. })
  445. }
  446. /// The runtime mapped or unmapped title memory `[at, at + len)`, or is
  447. /// about to write it through the kernel (`crate::watch`): the placed
  448. /// textures there may have arrived, gone, or changed with no descriptor
  449. /// written. The range is kept for the next texture pass
  450. /// ([`HostHeap::texture_slots_remapped`]). Called with the runtime's own
  451. /// locks held: this locks one mutex of its own and calls nothing.
  452. pub(crate) fn remapped(at: usize, len: usize) {
  453. use std::sync::atomic::Ordering::Relaxed;
  454. /// Ranges kept until a pass takes them.
  455. const MOST: usize = 1 << 15;
  456. let (start, end) = (at as u64, at.saturating_add(len) as u64);
  457. if end <= SPANNED[0].load(Relaxed) || start >= SPANNED[1].load(Relaxed) {
  458. return;
  459. }
  460. let mut ranges = REMAPPED.lock().unwrap_or_else(|e| e.into_inner());
  461. STALE[1].fetch_add(1, Relaxed);
  462. // Pages are mapped one after the other.
  463. if let Some(last) = ranges.last_mut()
  464. && last.1 == start
  465. {
  466. last.1 = end;
  467. return;
  468. }
  469. if ranges.len() >= MOST {
  470. // No pass runs (no shader that picks textures by index is bound):
  471. // the slots there are looked at when they are due, as before.
  472. STALE[2].fetch_add(ranges.len() as u64, Relaxed);
  473. ranges.clear();
  474. }
  475. ranges.push((start, end));
  476. }
  477. /// Frames for which a slot a draw read through a table counts as a table's
  478. /// slot ([`HostHeap::tabled`]).
  479. const TABLED_FRAMES: u64 = 240;
  480. /// Frames a write of a table's slot waits in the queue for the draw that
  481. /// reads it, before the slot is taken for one shaders pick by index.
  482. /// Frames as `crate::frame::current` counts them: in its opening cutscene
  483. /// The title begins two or three of them per frame it presents
  484. /// (435 begun in the 353 s of run 52's, for some 140 presented).
  485. const TABLED_GRACE: u64 = 8;
  486. /// Frames for which a record copied into a slot a draw read through a
  487. /// table is left to such a draw ([`HostHeap::copied_tabled`]).
  488. const COPIED_FRAMES: u32 = 8;
  489. /// Frames a record copied into any other slot waits for one, before it is
  490. /// taken for one shaders pick by index ([`HostHeap::copied_wait`]).
  491. const COPIED_GRACE: u64 = 4;
  492. /// In [`HostHeap::tabled`]: a draw read the slot in that frame.
  493. const TABLED_READ: u32 = 1 << 31;
  494. /// Since the start: writes of texture views into slots that count as a
  495. /// table's (due later), and slots that left the queue because a draw read
  496. /// them through a table.
  497. pub(crate) static TABLED_WRITES: [std::sync::atomic::AtomicU64; 2] =
  498. [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  499. /// Whether slots draws read through tables leave the queue of textures
  500. /// picked by index; `VICTORY_TABLED_TEXTURES=1` keeps them in it as
  501. /// before.
  502. fn tabled_out() -> bool {
  503. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  504. *ON.get_or_init(|| std::env::var_os("VICTORY_TABLED_TEXTURES").is_none_or(|v| v != "1"))
  505. }
  506. /// What the queue of textures picked by index knows of a title slot.
  507. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  508. struct Waiting {
  509. /// The frame from which the slot is due.
  510. due: u64,
  511. /// The frame it was written in.
  512. written: u64,
  513. /// Which write of the queue put it here: the pass hands it back with
  514. /// what it did, so a slot written again meanwhile stays as written.
  515. write: u64,
  516. /// Looks in a row that found nothing to upload (its memory not mapped,
  517. /// or no more of it than at the last upload).
  518. looks: u8,
  519. /// Bytes of its memory that were mapped when it was last uploaded
  520. /// without all of it there; 0: not uploaded yet.
  521. mapped: u64,
  522. /// For a slot uploaded whole and looked at again
  523. /// ([`TextureQueue::recheck`]): where its memory is (address, bytes),
  524. /// the fingerprint it had at the upload, how many looks found it
  525. /// unchanged, and the frame of the upload. A fingerprint of 0: none.
  526. checked: (u64, u64, u64, u8, u64),
  527. }
  528. /// The queue of title slots whose texture view waits to be brought up to
  529. /// date for shaders that pick textures by index: which are due, and in
  530. /// which order (no host heap needed, so it is tested without one).
  531. #[derive(Default)]
  532. pub(crate) struct TextureQueue {
  533. slots: std::collections::BTreeMap<u32, Waiting>,
  534. writes: u64,
  535. /// Slots held back because the card had no room for the host copy
  536. /// they need ([`TextureQueue::hold`]), each with the write it was
  537. /// held as.
  538. held: std::collections::BTreeMap<u32, u64>,
  539. }
  540. impl TextureQueue {
  541. /// A texture view was written into slot `index` in `frame`, due from
  542. /// frame `due`. `seen`: it was not written, a draw or the pass made
  543. /// the host slot from a view the queue may hold already, which then
  544. /// stays as it is.
  545. fn written(&mut self, index: u32, frame: u64, due: u64, seen: bool) {
  546. if seen && self.slots.contains_key(&index) {
  547. return;
  548. }
  549. self.writes += 1;
  550. let write = self.writes;
  551. self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) });
  552. }
  553. fn remove(&mut self, index: u32) {
  554. self.slots.remove(&index);
  555. }
  556. /// Up to `max` slots due at `frame`, each with its write number, in
  557. /// the order to serve them:
  558. /// - first the ones looked at before (their memory was not mapped, or
  559. /// only part of it): the look is a query, and memory that has
  560. /// arrived since is what the title streamed in last;
  561. /// - then the others, the newest write first and the oldest next, in
  562. /// turns: slot order served the low slots of a backlog of
  563. /// 25,000-40,000 while the textures of the shot on screen waited
  564. /// (run 52: 98% of the drawn pixels had no colour texture in the
  565. /// first 3D frames).
  566. fn due(&self, frame: u64, max: usize) -> Vec<(u32, u64)> {
  567. let mut again: Vec<(u64, u32, u64)> = Vec::new();
  568. let mut fresh: Vec<(u64, u32, u64)> = Vec::new();
  569. for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) {
  570. let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh };
  571. class.push((w.written, index, w.write));
  572. }
  573. // By the number of the write, counted over the run.
  574. let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2);
  575. again.sort_unstable_by(newest_first);
  576. fresh.sort_unstable_by(newest_first);
  577. let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect();
  578. let (mut new, mut old) = (0, fresh.len());
  579. while new < old && order.len() < max {
  580. order.push((fresh[new].1, fresh[new].2));
  581. new += 1;
  582. if new < old && order.len() < max {
  583. old -= 1;
  584. order.push((fresh[old].1, fresh[old].2));
  585. }
  586. }
  587. order.truncate(max);
  588. order
  589. }
  590. /// The entry of `index` if it is still the write the pass was handed.
  591. fn same(&mut self, index: u32, write: u64) -> Option<&mut Waiting> {
  592. self.slots.get_mut(&index).filter(|w| w.write == write)
  593. }
  594. /// Slot `index` is up to date: out of the queue until written again.
  595. fn done(&mut self, index: u32, write: u64) {
  596. if self.same(index, write).is_some() {
  597. self.slots.remove(&index);
  598. }
  599. }
  600. /// Nothing to upload at slot `index` now: looked at again after 1, 2,
  601. /// 4, ... frames, at most `most`.
  602. fn later(&mut self, index: u32, write: u64, frame: u64, most: u64) {
  603. if let Some(w) = self.same(index, write) {
  604. w.due = frame + (1u64 << w.looks.min(16)).min(most.max(1));
  605. w.looks = w.looks.saturating_add(1);
  606. }
  607. }
  608. /// The card has no room for the host copy slot `index` needs: it is
  609. /// not handed out again before frame `due`, or before the card has
  610. /// room again ([`TextureQueue::room`]). Nothing else of it changes: it
  611. /// is not a slot "waiting for its memory", and when it is due it has
  612. /// its old place among the slots never looked at. (It stayed due, so
  613. /// every pass on a full card looked at the same few hundred slots
  614. /// again and stopped there, and the slots behind them were never
  615. /// reached: the ones whose host copy exists and only wants bringing up
  616. /// to date, and the ones whose memory went, which is what lets host
  617. /// copies go and makes room.)
  618. fn hold(&mut self, index: u32, write: u64, due: u64) {
  619. if let Some(w) = self.same(index, write) {
  620. w.due = w.due.max(due);
  621. self.held.insert(index, write);
  622. }
  623. }
  624. /// The card has room again at `frame`: the slots held back for lack of
  625. /// it are due now, as if they had never been held. Returns how many.
  626. fn room(&mut self, frame: u64) -> usize {
  627. let held = std::mem::take(&mut self.held);
  628. let mut back = 0;
  629. for (index, write) in held {
  630. if let Some(w) = self.same(index, write) {
  631. w.due = w.due.min(frame);
  632. back += 1;
  633. }
  634. }
  635. back
  636. }
  637. /// Slot `index` was uploaded with `mapped` bytes of its memory there,
  638. /// not all of it: looked at again from frame `due`.
  639. fn partly(&mut self, index: u32, write: u64, due: u64, mapped: u64) {
  640. if let Some(w) = self.same(index, write) {
  641. (w.due, w.looks, w.mapped) = (due, 0, mapped.max(1));
  642. }
  643. }
  644. /// Slot `index` was uploaded whole from memory `at` (address, bytes)
  645. /// with fingerprint `print`: looked at again from frame `due`, for a
  646. /// title that fills a texture's memory after it wrote the view (the
  647. /// `looks`-th such look; `uploaded` is the upload's frame).
  648. #[allow(clippy::too_many_arguments)]
  649. fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) {
  650. if let Some(w) = self.same(index, write) {
  651. (w.due, w.looks, w.mapped) = (due, 1, 0);
  652. w.checked = (at.0, at.1, print, looks, uploaded);
  653. }
  654. }
  655. /// What [`TextureQueue::recheck`] noted of slot `index`, if it is
  656. /// waiting for such a look.
  657. fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> {
  658. self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0)
  659. }
  660. /// The memory slot `index`'s texture lies in was mapped, unmapped or
  661. /// written in `frame`: the slot is looked at from frame `due` as one
  662. /// written now, whatever was known of it (a pass at work on it does
  663. /// not take it out).
  664. fn changed(&mut self, index: u32, frame: u64, due: u64) {
  665. self.writes += 1;
  666. let write = self.writes;
  667. let due = self.slots.get(&index).map_or(due, |w| w.due.min(due));
  668. self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) });
  669. }
  670. /// Bytes of slot `index`'s memory that were mapped at its last upload
  671. /// (0: not uploaded, or all of it was).
  672. fn mapped(&self, index: u32) -> u64 {
  673. self.slots.get(&index).map_or(0, |w| w.mapped)
  674. }
  675. /// For the frame line: slots in the queue; of them due at `frame`;
  676. /// waiting for their memory (looked at, never uploaded); uploaded in
  677. /// part; and the frames the oldest due one has waited since its write.
  678. fn census(&self, frame: u64) -> [u64; 5] {
  679. let mut c = [self.slots.len() as u64, 0, 0, 0, 0];
  680. for w in self.slots.values() {
  681. if w.mapped > 0 {
  682. c[3] += 1;
  683. } else if w.looks > 0 {
  684. c[2] += 1;
  685. }
  686. if w.due <= frame {
  687. c[1] += 1;
  688. c[4] = c[4].max(frame.saturating_sub(w.written));
  689. }
  690. }
  691. c
  692. }
  693. }
  694. /// Whether `view` is of a texture the title may fill itself: a texture it
  695. /// placed in memory, or a texture object.
  696. pub(crate) fn is_texture_view(view: &View) -> bool {
  697. match view {
  698. View::Placed(false, resource, _) => resource[0] != 1,
  699. View::Shader(r, _) => crate::resource::buffer_bytes(*r as crate::object::This).is_none(),
  700. _ => false,
  701. }
  702. }
  703. /// Buffer views left null because the host would refuse them
  704. /// ([`buffer_view_ok`]), since the start.
  705. pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  706. /// Whether the host device is gone, and why (the first time it is asked
  707. /// after that): for passes that make many views, to name the one that did
  708. /// it.
  709. pub(crate) fn device_removed() -> Option<String> {
  710. let host = host()?;
  711. // SAFETY: a plain query.
  712. let reason = unsafe { host.device.GetDeviceRemovedReason() };
  713. reason.err().map(|e| e.to_string())
  714. }
  715. /// Writes of title view-heap slots with a placed texture view and with a
  716. /// view of a texture object, since the start (diagnostic counts).
  717. pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  718. pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  719. /// Bytes per element of a buffer view, as the console's descriptor holds
  720. /// them for indexed reads (structured: the stride; raw: 1, the index is the
  721. /// byte; typed: the format's); `None` if `view` is not a buffer view.
  722. fn view_stride(view: &View) -> Option<u32> {
  723. let (stride, raw, format) = view_elements(view)?;
  724. Some(if stride > 0 {
  725. stride
  726. } else if raw {
  727. 1
  728. } else {
  729. crate::resource::element(format).map_or(0, |(bytes, _)| bytes as u32)
  730. })
  731. }
  732. /// A buffer view's structure stride, whether it is raw, and its format;
  733. /// `None` if `view` is not a buffer view.
  734. fn view_elements(view: &View) -> Option<(u32, bool, u32)> {
  735. const BUFFER: u32 = 1;
  736. let (words, unordered): (&[u32; 10], bool) = match view {
  737. View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false),
  738. View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true),
  739. View::Placed(unordered, resource, d) if resource[0] == BUFFER => {
  740. (d[..10].try_into().ok()?, *unordered)
  741. }
  742. _ => return None,
  743. };
  744. // SAFETY: buffer views' union members.
  745. Some(unsafe {
  746. if unordered {
  747. let d = uav_desc(words);
  748. let b = d.Anonymous.Buffer;
  749. (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format.0 as u32)
  750. } else {
  751. let d = srv_desc(words);
  752. let b = d.Anonymous.Buffer;
  753. (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format.0 as u32)
  754. }
  755. })
  756. }
  757. /// Whether a buffer view that begins `offset` bytes into its host copy begins
  758. /// where no host view can: raw views begin on 16 bytes, others on a multiple
  759. /// of their elements (`stride` of a structured one, which is made raw where it
  760. /// can be, `element` of a typed one). The console's begin on any dword, and
  761. /// the title puts parameter blocks at ring positions: a raw view of 128 bytes
  762. /// at 8 (the colour table bakes'), structured ones of elements that are no
  763. /// divisor of their place (the culling's 456-byte constants). Such a view gets
  764. /// a copy of its own bytes ([`crate::shadow::exact`]). (A typed view of
  765. /// 12-byte elements at a multiple of 16 that is none of 12 is one of them: it
  766. /// was passed over, and stayed null.)
  767. fn off_elements(offset: u64, stride: u32, raw: bool, element: u64) -> bool {
  768. if raw {
  769. !offset.is_multiple_of(16)
  770. } else if stride > 0 {
  771. !offset.is_multiple_of(16) && !offset.is_multiple_of(u64::from(stride))
  772. } else {
  773. element > 0 && !offset.is_multiple_of(element)
  774. }
  775. }
  776. /// Whether views off their copy's elements get a copy of their own bytes. On by
  777. /// default; `VICTORY_VIEW_BYTES=0` leaves them null, as before.
  778. fn view_bytes() -> bool {
  779. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  780. *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_BYTES").is_none_or(|v| v != "0"))
  781. }
  782. /// The copy the buffer view of `[start, start + len)` is made on: `shadow`, the one
  783. /// its buffer has, or one of the view's own bytes ([`off_elements`]).
  784. fn view_home(
  785. shadow: std::sync::Arc<crate::shadow::Shadow>,
  786. start: u64,
  787. len: u64,
  788. (stride, raw, format): (u32, bool, u32),
  789. ) -> std::sync::Arc<crate::shadow::Shadow> {
  790. let Some(offset) = shadow.offset_in(start).map(|_| shadow.offset(start)) else {
  791. return shadow;
  792. };
  793. if !view_bytes() {
  794. return shadow;
  795. }
  796. let element = crate::resource::element(format).map_or(0, |(bytes, _)| bytes);
  797. if !off_elements(offset, stride, raw, element) {
  798. return shadow;
  799. }
  800. crate::shadow::exact(start, len).unwrap_or(shadow)
  801. }
  802. /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for
  803. /// device-removed reports: a shader indexing a heap past its end faults.
  804. static GPU_RANGES: Mutex<Vec<(u64, u64, u64, bool)>> = Mutex::new(Vec::new());
  805. /// For device-removed reports: where host GPU address `va` lies against
  806. /// the host descriptor heaps.
  807. pub(crate) fn near_heaps(va: u64) -> String {
  808. let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner());
  809. let mut text = String::new();
  810. for &(start, bytes, step, sampler) in ranges.iter() {
  811. let kind = if sampler { "sampler" } else { "view" };
  812. let place = if va < start {
  813. format!("{:#x} below", start - va)
  814. } else if va < start + bytes {
  815. format!("inside, slot {}", (va - start) / step)
  816. } else {
  817. format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step)
  818. };
  819. text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}"));
  820. }
  821. text
  822. }
  823. /// The host's limit for shader-visible view heaps on resource binding
  824. /// tiers 1 and 2; tier 3 hardware may take more.
  825. const PORTABLE_VIEWS: u32 = 1_000_000;
  826. /// The size of every host view heap on a host that takes more than
  827. /// [`PORTABLE_VIEWS`] (AMD): the title's heap (a little over 1,000,000
  828. /// views in the retail game) plus [`DYNAMIC`] fits with room to spare, and
  829. /// the last slot is the null slot every view index at or past it reads.
  830. const UNCAPPED_VIEWS: u32 = 1 << 21;
  831. /// Picks, once, the null slot at the end of every host view heap and tells
  832. /// the translator now (`set_view_heap_limit`) instead of when the title's
  833. /// heap is made: a shader keeps the limit it was translated with, and the
  834. /// title makes 25 pipelines (their shaders translated at once) before it
  835. /// makes its view heap. Called before a shader is translated and before a
  836. /// view heap is made.
  837. ///
  838. /// Every host clamps. A host that caps view heaps at [`PORTABLE_VIEWS`]
  839. /// (NVIDIA) hung on a view index past the heap; one that does not (AMD
  840. /// RDNA3, RX 7900 XT) took a page fault and removed the device on entering
  841. /// the world: a compute program read view slot 16,777,088 (0xffff80) of a
  842. /// heap of 1,507,328, past its end. Unclamped, that index is undefined on
  843. /// any host.
  844. pub(crate) fn probe_view_limit() {
  845. static ONCE: std::sync::Once = std::sync::Once::new();
  846. ONCE.call_once(|| {
  847. let Some(host) = host() else { return };
  848. let fits = |count: u32| {
  849. // SAFETY: plain heap creation; the heap is released at once.
  850. let made: windows::core::Result<ID3D12DescriptorHeap> = unsafe {
  851. host.device
  852. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  853. Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  854. NumDescriptors: count,
  855. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  856. NodeMask: 0,
  857. })
  858. };
  859. made.is_ok()
  860. };
  861. let views = if fits(UNCAPPED_VIEWS) {
  862. UNCAPPED_VIEWS
  863. } else {
  864. PORTABLE_VIEWS
  865. };
  866. tracing::info!(
  867. views,
  868. "host view heaps hold {views} views; view indices are clamped to the null slot at the end from the first shader on"
  869. );
  870. victory_shader::emit::set_view_heap_limit(views - 1);
  871. });
  872. }
  873. /// Slots past the title's in a view heap, for tables a draw needs made
  874. /// afresh (constant buffers copied per draw). A list holds the slots it
  875. /// took until it is reset (its submissions have run) or released.
  876. /// 2^16 ran out in the world ("no free dynamic descriptor slots", run 11;
  877. /// upstream PR #336 takes 2^18). On a host heap capped at 1,000,000 views
  878. /// (NVIDIA) these come out of the title's slots, whose highest seen is
  879. /// about 720,000: 2^17 left 868,000 of them, and ran out in the opening
  880. /// cutscene (a frame asks for up to 16,000 tables while the frame before
  881. /// still holds its own; a draw refused its table read slots never made
  882. /// for it, and the card stopped within frames). 2^18 leaves 737,000; a
  883. /// table past them is made afresh in these slots like any other.
  884. pub(crate) const DYNAMIC: u32 = 1 << 18;
  885. /// [`DYNAMIC`] for a heap of `count` title slots whose null slot is `null`
  886. /// (0: none): up to four times as many where the host heap has the room (a
  887. /// host that takes more than [`PORTABLE_VIEWS`]; `VICTORY_DYNAMIC_SLOTS`
  888. /// sets the most). 2^18 ran out in the title's bigger places (session
  889. /// play-1125-0127: 27,000 to 35,000 tables a frame, up to 3,285 of them
  890. /// refused, with 2,639 indirect draws and dispatches).
  891. fn dynamic_slots(count: u32, null: u32) -> u32 {
  892. static MOST: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  893. let most = *MOST.get_or_init(|| {
  894. std::env::var("VICTORY_DYNAMIC_SLOTS")
  895. .ok()
  896. .and_then(|v| v.trim().parse().ok())
  897. .unwrap_or(DYNAMIC << 2)
  898. });
  899. if null < PORTABLE_VIEWS {
  900. return DYNAMIC;
  901. }
  902. null.saturating_sub(count).min(most).max(DYNAMIC)
  903. }
  904. impl HostHeap {
  905. pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> {
  906. let host = host()?;
  907. let kind = if sampler {
  908. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
  909. } else {
  910. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
  911. };
  912. let make = |count: u32| -> windows::core::Result<ID3D12DescriptorHeap> {
  913. // SAFETY: plain heap creation.
  914. unsafe {
  915. host.device
  916. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  917. Type: kind,
  918. NumDescriptors: count,
  919. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  920. NodeMask: 0,
  921. })
  922. }
  923. };
  924. // A view heap ends at the null slot shaders clamp view indices to
  925. // (`probe_view_limit`), whatever the title's own count: the title's
  926. // slots, then the dynamic ones, then null up to and with that slot.
  927. if !sampler {
  928. probe_view_limit();
  929. }
  930. let null = if sampler {
  931. 0
  932. } else {
  933. victory_shader::emit::view_heap_limit()
  934. };
  935. let extra = if sampler { 0 } else { dynamic_slots(count, null) };
  936. let (heap, count, size) = if null == 0 {
  937. match make(count + extra) {
  938. Ok(heap) => (heap, count, count + extra),
  939. Err(e) => {
  940. tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
  941. return None;
  942. }
  943. }
  944. } else {
  945. let size = null + 1;
  946. let fitted = if count + extra <= null {
  947. count
  948. } else {
  949. // shortcut: descriptors past the host's limit are left out; a title that reaches
  950. // them needs remapping. They read the null slot instead.
  951. tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot");
  952. null - extra
  953. };
  954. match make(size) {
  955. Ok(heap) => (heap, fitted, size),
  956. Err(e) => {
  957. tracing::warn!(error = %e, count, size, "no host view heap");
  958. return None;
  959. }
  960. }
  961. };
  962. // SAFETY: a live heap.
  963. let (cpu, step) = unsafe {
  964. (
  965. heap.GetCPUDescriptorHandleForHeapStart().ptr,
  966. host.device.GetDescriptorHandleIncrementSize(kind),
  967. )
  968. };
  969. tracing::debug!(count, sampler, "host descriptor heap");
  970. // SAFETY: a live shader-visible heap.
  971. let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr };
  972. GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((
  973. gpu,
  974. u64::from(size) * u64::from(step),
  975. u64::from(step),
  976. sampler,
  977. ));
  978. let strides = (!sampler)
  979. .then(|| {
  980. let bytes = u64::from(victory_shader::emit::SLOT_STRIDES_COUNT) * 4;
  981. let (buffer, data) = host.upload_buffer(bytes)?;
  982. // SAFETY: the buffer's whole mapping; a live buffer.
  983. let gpu = unsafe {
  984. std::ptr::write_bytes(data, 0, bytes as usize);
  985. buffer.GetGPUVirtualAddress()
  986. };
  987. crate::host::name(&buffer, || "element strides by view heap slot".to_owned());
  988. Some((buffer, gpu, data as usize))
  989. })
  990. .flatten();
  991. let h = HostHeap {
  992. heap,
  993. cpu,
  994. step,
  995. count,
  996. dynamic: extra,
  997. sampler,
  998. made: Mutex::new(vec![0; count as usize]),
  999. quick: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(),
  1000. copied: Mutex::new(Vec::new()),
  1001. waiting: Mutex::default(),
  1002. away: Mutex::default(),
  1003. kept: Mutex::new(vec![None; (count + extra) as usize]),
  1004. next: Mutex::new((0, vec![false; extra as usize])),
  1005. free: std::sync::atomic::AtomicU32::new(extra),
  1006. too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
  1007. strides,
  1008. buffers: Mutex::default(),
  1009. changed: Mutex::default(),
  1010. textures: Mutex::default(),
  1011. tabled: (0..if sampler { 0 } else { count })
  1012. .map(|_| std::sync::atomic::AtomicU32::new(0))
  1013. .collect(),
  1014. placed: {
  1015. let spans = std::sync::Arc::<Mutex<Spans>>::default();
  1016. if !sampler {
  1017. PLACED_SPANS
  1018. .lock()
  1019. .unwrap_or_else(|e| e.into_inner())
  1020. .push(std::sync::Arc::downgrade(&spans));
  1021. }
  1022. spans
  1023. },
  1024. };
  1025. // A slot never written is undefined: shaders reading one (a slot
  1026. // the title wrote in a way we do not know, or a table entry no
  1027. // used-resource entry names) read a wild address. Every slot starts
  1028. // null instead.
  1029. let started = std::time::Instant::now();
  1030. if let Err(e) = h.fill_null(kind, size) {
  1031. tracing::warn!(error = %e, "host descriptor heap not made null");
  1032. }
  1033. tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null");
  1034. Some(h)
  1035. }
  1036. /// Makes the first `total` slots null: one null slot in a CPU-side heap,
  1037. /// doubled by copies to a block, the block copied over the heap.
  1038. fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> {
  1039. const BLOCK: u32 = 1 << 16;
  1040. let Some(host) = host() else { return Ok(()) };
  1041. // SAFETY: plain heap creation and copies inside live heaps.
  1042. unsafe {
  1043. let block: ID3D12DescriptorHeap =
  1044. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  1045. Type: kind,
  1046. NumDescriptors: BLOCK,
  1047. ..Default::default()
  1048. })?;
  1049. let start = block.GetCPUDescriptorHandleForHeapStart();
  1050. let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE {
  1051. ptr: start.ptr + (i * self.step) as usize,
  1052. };
  1053. if self.sampler {
  1054. null_sampler(start);
  1055. } else {
  1056. null_view(start);
  1057. }
  1058. let mut filled = 1;
  1059. while filled < BLOCK {
  1060. let n = filled.min(BLOCK - filled);
  1061. host.device.CopyDescriptorsSimple(n, at(filled), start, kind);
  1062. filled += n;
  1063. }
  1064. let mut done = 0;
  1065. while done < total {
  1066. let n = BLOCK.min(total - done);
  1067. host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind);
  1068. done += n;
  1069. }
  1070. }
  1071. Ok(())
  1072. }
  1073. /// A plain point sampler at slot `index`, for sampler slots without a
  1074. /// view.
  1075. fn null_sampler(&self, index: u32) {
  1076. null_sampler(self.cpu(index));
  1077. }
  1078. }
  1079. /// A plain point sampler at `at`.
  1080. fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  1081. let Some(host) = host() else { return };
  1082. let desc = D3D12_SAMPLER_DESC {
  1083. Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
  1084. AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1085. AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1086. AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  1087. MaxAnisotropy: 1,
  1088. ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER,
  1089. ..Default::default()
  1090. };
  1091. // SAFETY: a slot of a sampler heap of ours.
  1092. unsafe { host.device.CreateSampler(&desc, at) };
  1093. }
  1094. impl HostHeap {
  1095. /// `n` consecutive free dynamic slots (view heaps only), taken until
  1096. /// [`HostHeap::release`]: the first's index.
  1097. pub(crate) fn dynamic(&self, n: u32) -> Option<u32> {
  1098. if self.sampler || n == 0 || n > self.dynamic {
  1099. return None;
  1100. }
  1101. #[cfg(feature = "diagnostics")]
  1102. let started = std::time::Instant::now();
  1103. #[cfg(feature = "diagnostics")]
  1104. crate::copystat::add(crate::copystat::C::DynamicAsked, 1);
  1105. let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
  1106. let (next, taken) = &mut *guard;
  1107. let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n
  1108. && n < self.too_long.load(std::sync::atomic::Ordering::Relaxed);
  1109. let n = n as usize;
  1110. // Search from `next` on, then from the start (extending past cursor by
  1111. // n - 1 so contiguous runs crossing the cursor are not missed).
  1112. let cursor = *next as usize;
  1113. let end = self.dynamic as usize;
  1114. let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end);
  1115. let starts = (cursor..end).chain(0..second_end);
  1116. let mut run = 0;
  1117. let mut found = None;
  1118. let mut last = usize::MAX;
  1119. for at in starts.take(if enough { usize::MAX } else { 0 }) {
  1120. // A run cannot wrap past the end.
  1121. if at != last.wrapping_add(1) {
  1122. run = 0;
  1123. }
  1124. last = at;
  1125. run = if taken[at] { 0 } else { run + 1 };
  1126. if run == n {
  1127. found = Some(at + 1 - n);
  1128. break;
  1129. }
  1130. }
  1131. let Some(first) = found else {
  1132. if enough {
  1133. self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed);
  1134. }
  1135. static ONCE: std::sync::Once = std::sync::Once::new();
  1136. ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made"));
  1137. #[cfg(feature = "diagnostics")]
  1138. {
  1139. use crate::copystat::{C, add};
  1140. add(C::DynamicRefused, 1);
  1141. add(C::DynamicNs, started.elapsed().as_nanos() as u64);
  1142. }
  1143. return None;
  1144. };
  1145. #[cfg(feature = "diagnostics")]
  1146. crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64);
  1147. taken[first..first + n].fill(true);
  1148. self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed);
  1149. *next = ((first + n) % end) as u32;
  1150. Some(self.count + first as u32)
  1151. }
  1152. /// The title slots this heap has host slots for; fewer than the title's
  1153. /// when the host caps its size.
  1154. pub(crate) fn count(&self) -> u32 {
  1155. self.count
  1156. }
  1157. /// The GPU address of the table of element strides by title slot (view
  1158. /// heaps).
  1159. pub(crate) fn strides_gpu(&self) -> Option<u64> {
  1160. self.strides.as_ref().map(|s| s.1)
  1161. }
  1162. /// The table's buffer, for a list to hold.
  1163. pub(crate) fn strides_buffer(&self) -> Option<&ID3D12Resource> {
  1164. self.strides.as_ref().map(|s| &s.0)
  1165. }
  1166. /// Up to `max` title slots whose texture view is due at `frame`, each
  1167. /// with its write number, in the order to serve them
  1168. /// ([`TextureQueue::due`]), and the queue's counts
  1169. /// ([`TextureQueue::census`]).
  1170. pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) {
  1171. let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1172. (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame))
  1173. }
  1174. /// Every title slot of the queue that is due at `frame`, and whether
  1175. /// it was uploaded before (in part, or whole and waiting for another
  1176. /// look): for the card accounting line
  1177. /// (`crate::resource::card_accounting`).
  1178. pub(crate) fn texture_slots_all_due(&self, frame: u64) -> Vec<(u32, bool)> {
  1179. let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1180. textures
  1181. .slots
  1182. .iter()
  1183. .filter(|(_, w)| w.due <= frame)
  1184. .map(|(&index, w)| (index, w.mapped > 0 || w.checked.2 != 0))
  1185. .collect()
  1186. }
  1187. /// The texture view of title slot `index` (as handed out with `write`)
  1188. /// was brought up to date: due again from frame `again` (uploaded with
  1189. /// that many bytes of its memory there, not all), or not until the
  1190. /// slot is written again.
  1191. pub(crate) fn texture_slot_done(&self, index: u32, write: u64, again: Option<(u64, u64)>) {
  1192. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1193. match again {
  1194. Some((frame, mapped)) => textures.partly(index, write, frame, mapped),
  1195. None => textures.done(index, write),
  1196. }
  1197. }
  1198. /// Title slot `index` was uploaded whole: see [`TextureQueue::recheck`].
  1199. #[allow(clippy::too_many_arguments)]
  1200. pub(crate) fn texture_slot_recheck(
  1201. &self,
  1202. index: u32,
  1203. write: u64,
  1204. due: u64,
  1205. at: (u64, u64),
  1206. print: u64,
  1207. looks: u8,
  1208. uploaded: u64,
  1209. ) {
  1210. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1211. textures.recheck(index, write, due, at, print, looks, uploaded);
  1212. }
  1213. /// See [`TextureQueue::checked`].
  1214. pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> {
  1215. self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index)
  1216. }
  1217. /// Nothing to upload at title slot `index` now (its memory is not
  1218. /// mapped, or no more of it than before): looked at again after 1, 2,
  1219. /// 4, ... frames, at most `most`.
  1220. pub(crate) fn texture_slot_later(&self, index: u32, write: u64, frame: u64, most: u64) {
  1221. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1222. textures.later(index, write, frame, most);
  1223. }
  1224. /// See [`TextureQueue::hold`].
  1225. pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) {
  1226. self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due);
  1227. }
  1228. /// See [`TextureQueue::room`].
  1229. pub(crate) fn texture_slots_room(&self, frame: u64) -> usize {
  1230. self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame)
  1231. }
  1232. /// Bytes of title slot `index`'s memory that were mapped when it was
  1233. /// last uploaded in part (0: not uploaded, or whole).
  1234. pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 {
  1235. self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index)
  1236. }
  1237. /// Takes the ranges of title memory the runtime mapped, unmapped or
  1238. /// wrote since the last call ([`remapped`]) and makes the slots whose
  1239. /// placed texture lies there due from the next frame (by when a write
  1240. /// under way has landed): memory that arrived is uploaded, memory that
  1241. /// went makes the slot null ([`HostHeap::texture_slot_gone`]), and a
  1242. /// texture streamed into the place of another of the same description
  1243. /// is uploaded although no descriptor says so. Slots tables read are
  1244. /// left to their draws. Returns how many slots it made due.
  1245. /// shortcut: the ranges are kept in one place for all heaps; the heap
  1246. /// whose pass runs first takes them (a title has one view heap).
  1247. pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
  1248. use std::sync::atomic::Ordering::Relaxed;
  1249. self.texture_slots_page_written(frame);
  1250. let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
  1251. if ranges.is_empty() {
  1252. return 0;
  1253. }
  1254. let mut slots: Vec<u32> = {
  1255. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1256. ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect()
  1257. };
  1258. slots.sort_unstable();
  1259. slots.dedup();
  1260. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1261. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1262. for &slot in &slots {
  1263. textures.changed(slot, frame, frame + 1);
  1264. }
  1265. STALE[3].fetch_add(slots.len() as u64, Relaxed);
  1266. slots.len()
  1267. }
  1268. /// Makes the slots of the textures filled with less than was mapped
  1269. /// ([`read_short`]) due from the next frame on. Returns how many.
  1270. pub(crate) fn texture_slots_short(&self, frame: u64) -> usize {
  1271. if self.sampler {
  1272. return 0;
  1273. }
  1274. let starts = std::mem::take(&mut SHORT.lock().unwrap_or_else(|e| e.into_inner()).0);
  1275. if starts.is_empty() {
  1276. return 0;
  1277. }
  1278. let mut slots: Vec<u32> = {
  1279. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1280. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1281. };
  1282. slots.sort_unstable();
  1283. slots.dedup();
  1284. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1285. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1286. for &slot in &slots {
  1287. textures.changed(slot, frame, frame + 1);
  1288. }
  1289. slots.len()
  1290. }
  1291. /// Takes the ranges of title memory written behind the guards' back
  1292. /// since the last call ([`page_written`]) and finds the slots whose
  1293. /// placed texture holds bytes of them ([`Spans::slots_holding`]). A
  1294. /// slot whose texture was uploaded before the write shows the bytes
  1295. /// from before: with `VICTORY_PAGE_WRITES` (`crate::watch::page_writes`,
  1296. /// bit 2) it is due again [`PAGE_WRITE_AFTER`] frames on, as memory
  1297. /// mapped under it would make it ([`HostHeap::texture_slots_remapped`]);
  1298. /// its host copy exists, so the upload needs no room on the card. A
  1299. /// slot still waiting for its first upload is left as it is: that
  1300. /// upload takes the bytes that are there by then. Slots tables read
  1301. /// are left to their draws. Counted either way; returns how many slots
  1302. /// it made due.
  1303. fn texture_slots_page_written(&self, frame: u64) -> usize {
  1304. let ranges = std::mem::take(&mut *PAGE_WRITTEN.lock().unwrap_or_else(|e| e.into_inner()));
  1305. if ranges.is_empty() {
  1306. return 0;
  1307. }
  1308. self.slots_written_under(&ranges, frame, crate::watch::page_writes() & 2 != 0)[2]
  1309. }
  1310. /// [`HostHeap::texture_slots_page_written`] for `ranges` (start, end):
  1311. /// the slots that held bytes of them, those of them uploaded before,
  1312. /// and those made due (the latter, if `due`).
  1313. fn slots_written_under(&self, ranges: &[(u64, u64)], frame: u64, due: bool) -> [usize; 3] {
  1314. use std::sync::atomic::Ordering::Relaxed;
  1315. let mut slots: Vec<u32> = {
  1316. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1317. ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect()
  1318. };
  1319. slots.sort_unstable();
  1320. slots.dedup();
  1321. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1322. let held = slots.len();
  1323. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1324. // Uploaded before: out of the queue, or in it after an upload (in
  1325. // part, or whole and being looked at again).
  1326. slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0));
  1327. PAGE_WRITES[2].fetch_add(held as u64, Relaxed);
  1328. PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed);
  1329. if !due {
  1330. return [held, slots.len(), 0];
  1331. }
  1332. for &slot in &slots {
  1333. textures.changed(slot, frame, frame + PAGE_WRITE_AFTER);
  1334. }
  1335. [held, slots.len(), slots.len()]
  1336. }
  1337. /// Whether host slot `index` is made from the very record the title
  1338. /// has at `handle` now. Its host texture then exists (a slot keeps what
  1339. /// it views), so bringing that texture up to date takes no memory of
  1340. /// the card.
  1341. pub(crate) fn texture_slot_made_from(&self, index: u32, handle: u64) -> bool {
  1342. if index >= self.count {
  1343. return false;
  1344. }
  1345. // SAFETY: the handle is a descriptor slot in title memory.
  1346. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  1347. let key = u64::from(generation) << 32 | u64::from(i);
  1348. if tag != VIEW_TAG {
  1349. return false;
  1350. }
  1351. // And the slot holds a host resource: a slot is also noted as made
  1352. // from a view the host could not make (`make` gave nothing, the
  1353. // slot is null and keeps nothing). The host copy of such a
  1354. // texture is held by no slot, may have been let go, and would be
  1355. // made anew here, with the card full. `made` first, then `kept`,
  1356. // as `mirror` takes them.
  1357. let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1358. made.get(index as usize).is_some_and(|&made| made != 0 && made == key)
  1359. && self
  1360. .kept
  1361. .lock()
  1362. .unwrap_or_else(|e| e.into_inner())
  1363. .get(index as usize)
  1364. .is_some_and(Option::is_some)
  1365. }
  1366. /// Levels on demand (`crate::tiles`): makes again the host slots of the
  1367. /// placed textures whose first level with memory changed since the
  1368. /// last call ([`levels_changed`]), each from the view it was made
  1369. /// from, so that it shows the texture from that level ([`make`]). Only
  1370. /// slots that are made; a slot draws read through a table is made by
  1371. /// its draw. Returns how many it made.
  1372. /// shortcut: the starts are kept in one place for all heaps; the heap
  1373. /// whose pass runs first takes them (a title has one view heap).
  1374. /// Levels on demand (`crate::tiles`): the card has room, so the slots
  1375. /// of up to [`Self::WAITING_A_PASS`] placed textures whose upload left
  1376. /// a held level without tiles at least a second ago
  1377. /// ([`levels_waiting`]) are due again from the next frame, as memory
  1378. /// mapped under them would make them
  1379. /// ([`HostHeap::texture_slots_remapped`]): the upload then gives the
  1380. /// level its tiles. To be called only while the card has room: without
  1381. /// it the upload would give nothing again. Slots tables read are left
  1382. /// to their draws (`texture.rs` `upload` asks again for those). Returns
  1383. /// how many slots it made due.
  1384. /// shortcut: kept in one place for all heaps, as the starts below.
  1385. pub(crate) fn texture_slots_waiting(&self, frame: u64) -> usize {
  1386. if self.sampler {
  1387. return 0;
  1388. }
  1389. let starts: Vec<u64> = {
  1390. let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
  1391. if waiting.is_empty() {
  1392. return 0;
  1393. }
  1394. let starts: Vec<u64> = waiting
  1395. .iter()
  1396. .filter(|&(_, &since)| crate::host::long_ago(since, 1000, 2))
  1397. .map(|(&start, _)| start)
  1398. .take(Self::WAITING_A_PASS)
  1399. .collect();
  1400. for start in &starts {
  1401. waiting.remove(start);
  1402. }
  1403. starts
  1404. };
  1405. if starts.is_empty() {
  1406. return 0;
  1407. }
  1408. let mut slots: Vec<u32> = {
  1409. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1410. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1411. };
  1412. slots.sort_unstable();
  1413. slots.dedup();
  1414. slots.retain(|&slot| !self.tabled_lately(slot, frame));
  1415. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1416. for &slot in &slots {
  1417. textures.changed(slot, frame, frame + 1);
  1418. }
  1419. crate::tiles::STATS[10].fetch_add(slots.len() as u64, std::sync::atomic::Ordering::Relaxed);
  1420. slots.len()
  1421. }
  1422. /// Textures a pass asks again for their levels
  1423. /// ([`HostHeap::texture_slots_waiting`]): the first ones given tiles
  1424. /// may take the room the others were asked for, and an upload that
  1425. /// gives nothing is a whole texture staged and copied for nothing.
  1426. const WAITING_A_PASS: usize = 128;
  1427. pub(crate) fn texture_views_remade(&self) -> usize {
  1428. if self.sampler {
  1429. return 0;
  1430. }
  1431. let starts = std::mem::take(&mut *RESHOWN.lock().unwrap_or_else(|e| e.into_inner()));
  1432. if starts.is_empty() {
  1433. return 0;
  1434. }
  1435. let slots: Vec<u32> = {
  1436. let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1437. starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
  1438. };
  1439. let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1440. let mut remade = 0;
  1441. for slot in slots {
  1442. let Some(&key) = made.get(slot as usize) else {
  1443. continue;
  1444. };
  1445. if key == 0 {
  1446. continue;
  1447. }
  1448. let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
  1449. continue;
  1450. };
  1451. if let Some(kept) = make(&view, self.cpu(slot)) {
  1452. self.keep(slot, kept);
  1453. remade += 1;
  1454. }
  1455. }
  1456. remade
  1457. }
  1458. /// The memory of the texture title slot `index` views is not mapped
  1459. /// (any more): a host slot made from it becomes null again, so that
  1460. /// the host copy can be let go (`crate::resource::let_go_idle`; a slot
  1461. /// keeps what it views). True if the slot was made.
  1462. ///
  1463. /// Not at the first look: a title that moves a texture in its streaming
  1464. /// memory unmaps it before it maps it again, and what was shown went
  1465. /// black for the pictures in between (session play-1125-0127: faces,
  1466. /// books, posters and sleeves for 0.3 to 2 s). Only when it is still
  1467. /// away `AWAY_MS` after it was first found away
  1468. /// (`VICTORY_TEXTURE_AWAY_MS`; 0: at once, as before).
  1469. pub(crate) fn texture_slot_gone(&self, index: u32) -> bool {
  1470. const AWAY_MS: u64 = 3000;
  1471. static WAIT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1472. let wait = *WAIT.get_or_init(|| {
  1473. std::env::var("VICTORY_TEXTURE_AWAY_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(AWAY_MS)
  1474. });
  1475. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1476. let Some(key) = made.get(index as usize).copied().filter(|&key| key != 0) else {
  1477. return false;
  1478. };
  1479. let now = crate::host::now_ms();
  1480. {
  1481. let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner());
  1482. match away.get(&index) {
  1483. Some(&(was, since)) if was == key && now.saturating_sub(since) < wait => return false,
  1484. Some(&(was, _)) if was == key => {
  1485. away.remove(&index);
  1486. }
  1487. _ if wait == 0 => {}
  1488. _ => {
  1489. away.insert(index, (key, now));
  1490. return false;
  1491. }
  1492. }
  1493. }
  1494. self.unmake(&mut made, index);
  1495. STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1496. true
  1497. }
  1498. /// The memory of the texture title slot `index` views is there (again):
  1499. /// see [`HostHeap::texture_slot_gone`].
  1500. pub(crate) fn texture_slot_here(&self, index: u32) {
  1501. let mut away = self.away.lock().unwrap_or_else(|e| e.into_inner());
  1502. if !away.is_empty() {
  1503. away.remove(&index);
  1504. }
  1505. }
  1506. /// Makes host slot `index` null again, as it is before its view is
  1507. /// made: a null view of the kind it held.
  1508. fn unmake(&self, made: &mut [u64], index: u32) {
  1509. self.quick_is(index, 0);
  1510. let Some(key) = made.get_mut(index as usize).map(std::mem::take) else {
  1511. return;
  1512. };
  1513. if key == 0 {
  1514. return;
  1515. }
  1516. match view_at(key as u32, (key >> 32) as u32) {
  1517. Some(view) => null_for(&view, self.cpu(index)),
  1518. None => null_view(self.cpu(index)),
  1519. }
  1520. self.keep(index, None);
  1521. }
  1522. /// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a
  1523. /// draw read it through the table and brought what it views up to
  1524. /// date, so the slot leaves the queue of textures picked by index; the
  1525. /// caller makes the host slot in place ([`HostHeap::mirror`]), as the
  1526. /// pass would have, for a shader that picks it by index all the same.
  1527. pub(crate) fn texture_slot_tabled(&self, index: u32, read: bool) {
  1528. self.tabled_in(index, read, crate::frame::current());
  1529. }
  1530. /// [`HostHeap::texture_slot_tabled`] in frame `frame`.
  1531. fn tabled_in(&self, index: u32, read: bool, frame: u64) {
  1532. use std::sync::atomic::Ordering::Relaxed;
  1533. let Some(stamp) = self.tabled.get(index as usize) else {
  1534. return;
  1535. };
  1536. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1537. let old = stamp.load(Relaxed);
  1538. if !read {
  1539. if old & !TABLED_READ != now {
  1540. stamp.store(now, Relaxed);
  1541. }
  1542. return;
  1543. }
  1544. // Once per slot and frame: tables are read by every draw.
  1545. if old != now | TABLED_READ {
  1546. stamp.store(now | TABLED_READ, Relaxed);
  1547. if tabled_out() {
  1548. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1549. if textures.slots.remove(&index).is_some() {
  1550. TABLED_WRITES[1].fetch_add(1, Relaxed);
  1551. }
  1552. }
  1553. }
  1554. }
  1555. /// Whether title slot `index` was a table's within the last
  1556. /// [`TABLED_FRAMES`] frames before `frame` (never, if such slots are
  1557. /// to be queued as any other).
  1558. fn tabled_lately(&self, index: u32, frame: u64) -> bool {
  1559. let stamp = self.tabled_stamp(index) & !TABLED_READ;
  1560. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1561. tabled_out() && stamp != 0 && u64::from(now.wrapping_sub(stamp)) <= TABLED_FRAMES
  1562. }
  1563. /// What `tabled` holds for title slot `index`; 0: never a table's.
  1564. fn tabled_stamp(&self, index: u32) -> u32 {
  1565. self.tabled
  1566. .get(index as usize)
  1567. .map_or(0, |s| s.load(std::sync::atomic::Ordering::Relaxed))
  1568. }
  1569. /// The queue's part of a write of title slot `index` in `frame`:
  1570. /// `texture`, whether it now holds a view of a texture the title may
  1571. /// fill; `seen` as for [`HostHeap::note_buffer`].
  1572. fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) {
  1573. let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 };
  1574. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1575. // A table's slot lately: the draw that reads it uploads its
  1576. // texture, so its write waits for that draw.
  1577. let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES;
  1578. // Made now by a draw of this frame that read it through a table:
  1579. // up to date.
  1580. let read_now = seen && stamp == now | TABLED_READ;
  1581. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1582. if texture && !read_now {
  1583. let due = if lately && !seen {
  1584. TABLED_WRITES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1585. frame + TABLED_GRACE
  1586. } else {
  1587. 0
  1588. };
  1589. textures.written(index, frame, due, seen);
  1590. } else {
  1591. textures.remove(index);
  1592. }
  1593. }
  1594. /// Title slot `index` lies in a table a draw reads or had made afresh:
  1595. /// what it holds is the draw's to make ([`HostHeap::copied_tabled`]).
  1596. pub(crate) fn slot_tabled(&self, index: u32) {
  1597. self.tabled_in(index, false, crate::frame::current());
  1598. }
  1599. /// The title slots that hold buffer views.
  1600. pub(crate) fn buffer_slots(&self) -> Vec<u32> {
  1601. let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1602. buffers.iter().copied().collect()
  1603. }
  1604. /// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every
  1605. /// slot is in the same part each time.
  1606. pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec<u32> {
  1607. let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1608. buffers.iter().copied().filter(|slot| slot % parts == part).collect()
  1609. }
  1610. /// The title slots whose buffer view was written, or went, since the
  1611. /// last call.
  1612. pub(crate) fn buffer_changes(&self) -> Vec<u32> {
  1613. let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner());
  1614. std::mem::take(&mut *changed).into_iter().collect()
  1615. }
  1616. /// Records what title slot `index` now holds for shaders that pick
  1617. /// buffers from the heap: its element stride in the table, and whether
  1618. /// it is a buffer view at all.
  1619. /// `seen`: the slot was not written now, a draw or a pass made its
  1620. /// host slot from what it held.
  1621. /// Returns the title slots whose placed texture view the write made
  1622. /// stale ([`Spans`]): out of the queue of textures already, their host
  1623. /// slots are the caller's to make null (it holds `made`).
  1624. fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec<u32> {
  1625. if self.sampler {
  1626. return Vec::new();
  1627. }
  1628. // Measured for the texture side of the same gap (textures a shader
  1629. // picks by a computed index are neither made, if placed, nor
  1630. // uploaded): slots written with a placed texture view, and with a
  1631. // view of a texture object.
  1632. let texture = match view {
  1633. Some(View::Placed(false, resource, _)) if resource[0] != 1 => {
  1634. PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1635. true
  1636. }
  1637. Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => {
  1638. OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1639. true
  1640. }
  1641. _ => false,
  1642. };
  1643. self.queue_texture(index, texture, seen, crate::frame::current());
  1644. // The memory a placed texture view describes. Not for a slot
  1645. // tables read (thousands of writes a frame, each read by its
  1646. // draw): no pass looks at it, and the same texture's view in a
  1647. // slot shaders pick by index says what it says.
  1648. let placed_view = match view {
  1649. Some(View::Placed(false, resource, desc))
  1650. if resource[0] != 1 && !self.tabled_lately(index, crate::frame::current()) =>
  1651. {
  1652. // (And the level the view starts at: word 4 of a texture
  1653. // view's description, after format, dimension, mapping
  1654. // and a pad.)
  1655. Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4]))
  1656. }
  1657. _ => None,
  1658. };
  1659. let stale = {
  1660. use std::sync::atomic::Ordering::Relaxed;
  1661. let mut placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
  1662. let span = placed_view.and_then(|(resource, start, first)| {
  1663. Some((start, start.saturating_add(placed.bytes(resource)?), first))
  1664. });
  1665. match span {
  1666. Some((start, end, first)) => {
  1667. SPANNED[0].fetch_min(start, Relaxed);
  1668. SPANNED[1].fetch_max(end, Relaxed);
  1669. placed.rule = stale_rule();
  1670. let stale = placed.note(index, start, end, !seen);
  1671. placed.shows(index, first);
  1672. stale
  1673. }
  1674. None => {
  1675. placed.forget(index);
  1676. Vec::new()
  1677. }
  1678. }
  1679. };
  1680. if !stale.is_empty() {
  1681. STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed);
  1682. let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  1683. for &slot in &stale {
  1684. textures.remove(slot);
  1685. }
  1686. }
  1687. let stride = view.and_then(view_stride);
  1688. if let Some((_, _, data)) = &self.strides
  1689. && index < victory_shader::emit::SLOT_STRIDES_COUNT
  1690. {
  1691. // SAFETY: inside the mapping; shaders read it while we write (a
  1692. // dword, either value is one the slot had).
  1693. unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) };
  1694. }
  1695. let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
  1696. let was = if stride.is_some() {
  1697. buffers.insert(index);
  1698. true
  1699. } else {
  1700. buffers.remove(&index)
  1701. };
  1702. if was {
  1703. self.changed
  1704. .lock()
  1705. .unwrap_or_else(|e| e.into_inner())
  1706. .insert(index);
  1707. }
  1708. stale
  1709. }
  1710. /// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
  1711. /// returned).
  1712. ///
  1713. /// [`dynamic`]: HostHeap::dynamic
  1714. pub(crate) fn release(&self, first: u32, n: u32) {
  1715. let Some(at) = first.checked_sub(self.count) else {
  1716. return;
  1717. };
  1718. let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
  1719. let end = (at + n).min(self.dynamic) as usize;
  1720. if let Some(slots) = guard.1.get_mut(at as usize..end) {
  1721. let given = slots.iter().filter(|taken| **taken).count() as u32;
  1722. self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed);
  1723. self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed);
  1724. slots.fill(false);
  1725. }
  1726. }
  1727. /// Makes slot `index` (a dynamic one) from `view`; a null view if the
  1728. /// host cannot.
  1729. pub(crate) fn make_at(&self, index: u32, view: &View) {
  1730. let kept = make(view, self.cpu(index));
  1731. if kept.is_none() {
  1732. null_for(view, self.cpu(index));
  1733. }
  1734. self.keep(index, kept.flatten());
  1735. }
  1736. /// Makes slot `index` read nothing: a null view, or a plain sampler.
  1737. pub(crate) fn make_null(&self, index: u32) {
  1738. if self.sampler {
  1739. self.null_sampler(index);
  1740. } else {
  1741. null_view(self.cpu(index));
  1742. }
  1743. self.keep(index, None);
  1744. }
  1745. /// Slot `index` now views `resource` (or nothing of the host's).
  1746. fn keep(&self, index: u32, resource: Option<ID3D12Resource>) {
  1747. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  1748. if let Some(slot) = kept.get_mut(index as usize) {
  1749. // A running submission may still read the old resource through
  1750. // this slot.
  1751. if let Some(old) = std::mem::replace(slot, resource) {
  1752. crate::host::retire(old);
  1753. }
  1754. }
  1755. }
  1756. /// Makes slot `index` (a dynamic one) a raw buffer view of `len` bytes
  1757. /// of `buffer` from byte `offset` (a multiple of 16): a root SRV with a
  1758. /// size, whose reads past it return zeros instead of reaching whatever
  1759. /// the host placed after the buffer.
  1760. pub(crate) fn raw_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) {
  1761. let Some(host) = host() else { return };
  1762. let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32;
  1763. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  1764. Format: DXGI_FORMAT_R32_TYPELESS,
  1765. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  1766. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  1767. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  1768. Buffer: D3D12_BUFFER_SRV {
  1769. FirstElement: offset / 4,
  1770. NumElements: elements,
  1771. StructureByteStride: 0,
  1772. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  1773. },
  1774. },
  1775. };
  1776. // SAFETY: a slot of our heap and a live buffer covering the range.
  1777. unsafe {
  1778. host.device
  1779. .CreateShaderResourceView(buffer, Some(&desc), self.cpu(index))
  1780. };
  1781. self.keep(index, Some(buffer.clone()));
  1782. }
  1783. /// Makes slot `index` (a dynamic one) a raw buffer view that reads
  1784. /// zeros.
  1785. pub(crate) fn null_raw_at(&self, index: u32) {
  1786. null_buffer_view(self.cpu(index));
  1787. self.keep(index, None);
  1788. }
  1789. /// Makes slot `index` (a dynamic one) a raw unordered access view of
  1790. /// `len` bytes of `buffer` from byte `offset` (a multiple of 16): a
  1791. /// root UAV with a size, whose accesses past it do nothing instead of
  1792. /// reaching whatever the host placed after the buffer.
  1793. pub(crate) fn raw_uav_at(&self, index: u32, buffer: &ID3D12Resource, offset: u64, len: u64) {
  1794. let Some(host) = host() else { return };
  1795. let elements = (len / 4).clamp(1, u64::from(u32::MAX)) as u32;
  1796. let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  1797. Format: DXGI_FORMAT_R32_TYPELESS,
  1798. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  1799. Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
  1800. Buffer: D3D12_BUFFER_UAV {
  1801. FirstElement: offset / 4,
  1802. NumElements: elements,
  1803. StructureByteStride: 0,
  1804. CounterOffsetInBytes: 0,
  1805. Flags: D3D12_BUFFER_UAV_FLAG_RAW,
  1806. },
  1807. },
  1808. };
  1809. // SAFETY: a slot of our heap and a live buffer covering the range.
  1810. unsafe {
  1811. host.device.CreateUnorderedAccessView(
  1812. buffer,
  1813. None::<&ID3D12Resource>,
  1814. Some(&desc),
  1815. self.cpu(index),
  1816. )
  1817. };
  1818. self.keep(index, Some(buffer.clone()));
  1819. }
  1820. /// Makes slot `index` (a dynamic one) a raw unordered access view of
  1821. /// nothing: reads give zeros, writes are dropped.
  1822. pub(crate) fn null_raw_uav_at(&self, index: u32) {
  1823. self.keep(index, None);
  1824. let Some(host) = host() else { return };
  1825. let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  1826. Format: DXGI_FORMAT_R32_TYPELESS,
  1827. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  1828. Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
  1829. Buffer: D3D12_BUFFER_UAV {
  1830. NumElements: 1,
  1831. Flags: D3D12_BUFFER_UAV_FLAG_RAW,
  1832. ..Default::default()
  1833. },
  1834. },
  1835. };
  1836. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  1837. unsafe {
  1838. host.device.CreateUnorderedAccessView(
  1839. None::<&ID3D12Resource>,
  1840. None::<&ID3D12Resource>,
  1841. Some(&desc),
  1842. self.cpu(index),
  1843. )
  1844. };
  1845. }
  1846. /// The shader-visible handle of slot `index`.
  1847. pub(crate) fn gpu_handle(&self, index: u32) -> D3D12_GPU_DESCRIPTOR_HANDLE {
  1848. // SAFETY: a live shader-visible heap.
  1849. let start = unsafe { self.heap.GetGPUDescriptorHandleForHeapStart().ptr };
  1850. D3D12_GPU_DESCRIPTOR_HANDLE {
  1851. ptr: start + u64::from(index) * u64::from(self.step),
  1852. }
  1853. }
  1854. /// Makes slot `index` (a dynamic one) a constant buffer view of host
  1855. /// memory (the list's own, which it holds).
  1856. pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) {
  1857. self.keep(index, None);
  1858. let Some(host) = host() else { return };
  1859. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
  1860. BufferLocation: gpu,
  1861. SizeInBytes: constant_bytes(size),
  1862. };
  1863. // SAFETY: a slot of our heap; the memory is the caller's.
  1864. unsafe {
  1865. host.device
  1866. .CreateConstantBufferView(Some(&desc), self.cpu(index))
  1867. };
  1868. }
  1869. fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  1870. D3D12_CPU_DESCRIPTOR_HANDLE {
  1871. ptr: self.cpu + index as usize * self.step as usize,
  1872. }
  1873. }
  1874. /// For a run of records of the title's heap from slot `first`, `step`
  1875. /// bytes each, on a page that changed with no call
  1876. /// (`super::sync_heaps`: the title copies records into its heap as
  1877. /// bytes): the slots whose record is not the one this last saw there.
  1878. ///
  1879. /// The page says only that something on it was written, and `mirror`
  1880. /// by itself would take every buffer or placed-texture record on it for
  1881. /// newly written each time (it leaves such a slot unmade until a draw
  1882. /// or a pass uses it): the texture queue's entry for the slot would
  1883. /// start again, and the buffer pass would look at 2,048 slots for one
  1884. /// that changed.
  1885. /// `records`: their bytes as the caller read them (through the
  1886. /// kernel, which fails on a page the title unmapped meanwhile where a
  1887. /// read in place would fault: the title unmaps heap pages too).
  1888. pub(crate) fn copied_changes(&self, first: u32, records: &[u8], step: usize, out: &mut Vec<u32>) {
  1889. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  1890. if copied.is_empty() {
  1891. // Nothing there: a slot never looked at that holds nothing is
  1892. // as it was.
  1893. copied.resize(self.count as usize * step, 0);
  1894. }
  1895. let at = first as usize * step;
  1896. let end = (at + records.len()).min(copied.len());
  1897. let Some(last) = copied.get_mut(at..end) else {
  1898. return;
  1899. };
  1900. let records = &records[..last.len()];
  1901. changed_records(last, records, step, first, out);
  1902. }
  1903. /// Whether new records of draws' tables are left to the draws
  1904. /// (`VICTORY_HEAP_SYNC=all`: every new record is mirrored at once, as
  1905. /// it first was).
  1906. ///
  1907. /// The title builds each draw's tables in its heap by copying records
  1908. /// there as bytes: 60,000 to 210,000 a frame in its world (session
  1909. /// play-1125-0127), 0.9 microseconds each on the submitting thread and
  1910. /// 1.4 more in the buffer pass they were all handed to, 120 to 600 ms
  1911. /// of every frame, and the draws make what they read of them anyway.
  1912. pub(crate) fn copied_waits(&self) -> bool {
  1913. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1914. *ON.get_or_init(|| std::env::var_os("VICTORY_HEAP_SYNC").is_none_or(|v| v != "all"))
  1915. }
  1916. /// Whether a draw read title slot `index` through a table within the
  1917. /// last few frames before `frame` ([`HostHeap::tabled`]): what it holds
  1918. /// is such a draw's to make.
  1919. pub(crate) fn copied_tabled(&self, index: u32, frame: u64) -> bool {
  1920. if !self.copied_waits() {
  1921. return false;
  1922. }
  1923. let stamp = self.tabled_stamp(index) & !TABLED_READ;
  1924. let now = (frame as u32).wrapping_add(1) & !TABLED_READ;
  1925. stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES
  1926. }
  1927. /// New records the title copied into slots `slots` in `frame` wait for
  1928. /// the draw that may read them through a table.
  1929. pub(crate) fn copied_wait(&self, frame: u64, slots: Vec<u32>) {
  1930. self.waiting.lock().unwrap_or_else(|e| e.into_inner()).push_back((frame, slots));
  1931. }
  1932. /// The slots that have waited long enough at `frame`
  1933. /// ([`HostHeap::copied_wait`]), each once.
  1934. pub(crate) fn copied_before(&self, frame: u64) -> Vec<u32> {
  1935. let mut waiting = self.waiting.lock().unwrap_or_else(|e| e.into_inner());
  1936. let mut out = Vec::new();
  1937. while waiting.front().is_some_and(|(written, _)| written + COPIED_GRACE <= frame) {
  1938. out.extend(waiting.pop_front().into_iter().flat_map(|(_, slots)| slots));
  1939. }
  1940. drop(waiting);
  1941. out.sort_unstable();
  1942. out.dedup();
  1943. out
  1944. }
  1945. /// Makes host slot `index` from the record the title has at `handle`
  1946. /// if it changed since, and returns the view recorded there. Buffer
  1947. /// views are made only for draws (`for_draw`), which also copy their
  1948. /// data: a host copy of a buffer is made on first use.
  1949. pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> {
  1950. if index >= self.count {
  1951. // Diagnostic (NVIDIA heap cap): the highest title slot past the
  1952. // host heap seen so far.
  1953. static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  1954. if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index {
  1955. tracing::warn!(
  1956. index,
  1957. count = self.count,
  1958. for_draw,
  1959. "title slot past the host heap"
  1960. );
  1961. }
  1962. return None;
  1963. }
  1964. // SAFETY: the handle is a descriptor slot in title memory.
  1965. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  1966. // Generations start at 1, so a made slot's key is never 0.
  1967. let key = u64::from(generation) << 32 | u64::from(i);
  1968. // Made from this record, and nothing has changed it: most of the
  1969. // asks, from five recording threads, behind one lock while another
  1970. // held it to make a descriptor (15 % of a recording thread's time in
  1971. // the opening, profile cpu-1).
  1972. if tag == VIEW_TAG
  1973. && quick_mirror()
  1974. && self.quick.get(index as usize).is_some_and(|k| k.load(std::sync::atomic::Ordering::Acquire) == key)
  1975. && let Some(view) = view_at(i, generation)
  1976. {
  1977. return Some(view);
  1978. }
  1979. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  1980. let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten();
  1981. let Some(view) = view else {
  1982. // Not a view of ours (never written, or of a resource the
  1983. // title released): nothing to read.
  1984. if made[index as usize] != 0 {
  1985. self.quick_is(index, 0);
  1986. made[index as usize] = 0;
  1987. self.make_null(index);
  1988. let _ = self.note_buffer(index, None, false);
  1989. } else if for_draw {
  1990. // Left for later and stale since: out of the sets and the stride table.
  1991. let _ = self.note_buffer(index, None, false);
  1992. }
  1993. return None;
  1994. };
  1995. if made[index as usize] != key {
  1996. // Views of other textures in the memory this one describes
  1997. // are stale: their host slots read nothing from here on, and
  1998. // let go of the host copies they held.
  1999. for stale in self.note_buffer(index, Some(&view), for_draw) {
  2000. if stale != index {
  2001. self.unmake(&mut made, stale);
  2002. }
  2003. }
  2004. // A view of a texture object that has no host copy yet waits
  2005. // for it, as buffer views wait for a draw: the slot is made
  2006. // when the texture is first used (`super::make_waiting`), or
  2007. // here when a draw reads the slot through a table.
  2008. let waiting = if for_draw { None } else { view.waiting_texture() };
  2009. if let Some(texture) = waiting {
  2010. super::wait_for(texture, handle);
  2011. }
  2012. let later = !for_draw && (view.is_buffer() || waiting.is_some());
  2013. // Another view of the placed texture the slot shows already (a
  2014. // title that streams a texture in writes its view again with
  2015. // more mips each time some arrive): the slot goes on showing
  2016. // the old view until a draw or the texture pass makes the new
  2017. // one and uploads what it shows. Made null here, the texture
  2018. // read as nothing for as long as it waited in the queue, every
  2019. // time it got sharper.
  2020. if later
  2021. && keep_views()
  2022. && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32)
  2023. .is_some_and(|old| same_placed_texture(&old, &view))
  2024. {
  2025. KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2026. return Some(view);
  2027. }
  2028. self.quick_is(index, 0);
  2029. made[index as usize] = if later { 0 } else { key };
  2030. let kept = if later {
  2031. None
  2032. } else {
  2033. make(&view, self.cpu(index))
  2034. };
  2035. if kept.is_none() && !self.sampler {
  2036. null_for(&view, self.cpu(index));
  2037. }
  2038. self.keep(index, kept.flatten());
  2039. self.quick_is(index, made[index as usize]);
  2040. }
  2041. Some(view)
  2042. }
  2043. /// Slot `index` is made from record `key` and stays so (0: not). Under
  2044. /// the lock of `made`.
  2045. fn quick_is(&self, index: u32, key: u64) {
  2046. if let Some(quick) = self.quick.get(index as usize) {
  2047. quick.store(key, std::sync::atomic::Ordering::Release);
  2048. }
  2049. }
  2050. /// Whether slot `index` is backed by a made host descriptor (tests).
  2051. #[cfg(test)]
  2052. pub(crate) fn made(&self, index: u32) -> bool {
  2053. self.made
  2054. .lock()
  2055. .unwrap_or_else(|e| e.into_inner())
  2056. .get(index as usize)
  2057. .is_some_and(|&key| key != 0)
  2058. }
  2059. /// Whether host slot `index` shows `buffer`; `None` if it shows no
  2060. /// resource (diagnostics: a buffer view's slot must show the host copy
  2061. /// that is brought up to date for it).
  2062. #[cfg(feature = "diagnostics")]
  2063. pub(crate) fn shows(&self, index: u32, buffer: &ID3D12Resource) -> Option<bool> {
  2064. let kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  2065. let shown = kept.get(index as usize)?.as_ref()?;
  2066. Some(windows::core::Interface::as_raw(shown) == windows::core::Interface::as_raw(buffer))
  2067. }
  2068. /// What the queue of textures picked by index knows of title slot
  2069. /// `index` at `frame`, in a few words (diagnostics).
  2070. #[cfg(feature = "diagnostics")]
  2071. pub(crate) fn texture_slot_state(&self, index: u32, frame: u64) -> String {
  2072. let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
  2073. match textures.slots.get(&index) {
  2074. None => "not queued".into(),
  2075. Some(w) => format!(
  2076. "queued due={} written@{} looks={} part_mapped={} recheck={}",
  2077. if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) },
  2078. w.written,
  2079. w.looks,
  2080. w.mapped,
  2081. w.checked.2 != 0
  2082. ),
  2083. }
  2084. }
  2085. /// The view host slot `index` was made from, in a few words, with the
  2086. /// title and host addresses of a buffer view (diagnostics). "null" for
  2087. /// a slot never made or left null.
  2088. #[cfg(feature = "diagnostics")]
  2089. pub(crate) fn describe_slot(&self, index: u32) -> Option<String> {
  2090. let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?;
  2091. if key == 0 {
  2092. return Some("null".into());
  2093. }
  2094. let view = view_at(key as u32, (key >> 32) as u32)?;
  2095. let mut text: String = format!("{view:?}").chars().take(120).collect();
  2096. if let Some((address, len)) = buffer_range(&view) {
  2097. let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address));
  2098. text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}"));
  2099. }
  2100. Some(text)
  2101. }
  2102. }
  2103. /// Logs `what` the first time it happens.
  2104. macro_rules! once {
  2105. ($($arg:tt)*) => {{
  2106. static ONCE: std::sync::Once = std::sync::Once::new();
  2107. ONCE.call_once(|| tracing::warn!($($arg)*));
  2108. }};
  2109. }
  2110. /// A view description from its words, with the format as the host has it.
  2111. fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC {
  2112. let mut words = *words;
  2113. words[0] = crate::resource::pc_format(words[0]);
  2114. // SAFETY: 40 bytes in the host's layout.
  2115. unsafe {
  2116. std::ptr::from_ref(&words)
  2117. .cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>()
  2118. .read_unaligned()
  2119. }
  2120. }
  2121. fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2122. let mut words = *words;
  2123. words[0] = crate::resource::pc_format(words[0]);
  2124. // SAFETY: 40 bytes in the host's layout.
  2125. unsafe {
  2126. std::ptr::from_ref(&words)
  2127. .cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>()
  2128. .read_unaligned()
  2129. }
  2130. }
  2131. /// A buffer view of title memory at `address` on its host copy: the first
  2132. /// element moves by the copy's offset.
  2133. /// Bytes per element of a buffer view.
  2134. fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 {
  2135. // SAFETY: a buffer view's union member.
  2136. let buffer = unsafe { desc.Anonymous.Buffer };
  2137. if buffer.StructureByteStride > 0 {
  2138. u64::from(buffer.StructureByteStride)
  2139. } else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 {
  2140. 4
  2141. } else {
  2142. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2143. }
  2144. }
  2145. /// The title memory a buffer shader or unordered access view reads: its
  2146. /// address and length.
  2147. pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
  2148. let (base, words): (u64, &[u32; 10]) = match view {
  2149. View::Shader(r, Some(desc)) => (
  2150. crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64,
  2151. desc,
  2152. ),
  2153. View::Placed(false, resource, desc) if resource[0] == 1 => (
  2154. u64::from(desc[10]) | u64::from(desc[11]) << 32,
  2155. desc[..10].try_into().ok()?,
  2156. ),
  2157. View::Unordered(r, _, Some(desc)) => {
  2158. let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64;
  2159. return unordered_range(base, desc);
  2160. }
  2161. View::Placed(true, resource, desc) if resource[0] == 1 => {
  2162. let base = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2163. return unordered_range(base, desc[..10].try_into().ok()?);
  2164. }
  2165. _ => return None,
  2166. };
  2167. let desc = srv_desc(words);
  2168. let element = element_size(&desc);
  2169. // SAFETY: a buffer view's union member.
  2170. let buffer = unsafe { desc.Anonymous.Buffer };
  2171. Some((
  2172. base + buffer.FirstElement * element,
  2173. u64::from(buffer.NumElements) * element,
  2174. ))
  2175. }
  2176. /// The address a shader finds in a descriptor of title memory: where a
  2177. /// buffer view starts, or the ray-tracing structure of a structure's view
  2178. /// (no resource: the view's description holds the address, and the shader
  2179. /// walks the structure from there itself).
  2180. pub(crate) fn view_address(view: &View) -> Option<u64> {
  2181. const STRUCTURE: u32 = D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32;
  2182. match view {
  2183. View::Shader(_, Some(desc)) if desc[1] == STRUCTURE => {
  2184. Some(u64::from(desc[4]) | u64::from(desc[5]) << 32)
  2185. }
  2186. _ => buffer_range(view).map(|range| range.0),
  2187. }
  2188. }
  2189. /// The title memory the host slot of buffer view `view` is made on
  2190. /// (address, bytes): the whole buffer the view is of, which is what
  2191. /// [`make`] finds the host copy by. [`buffer_range`] is the part of it the
  2192. /// view reads.
  2193. pub(crate) fn buffer_extent(view: &View) -> Option<(u64, u64)> {
  2194. match view {
  2195. View::Shader(r, Some(_)) | View::Unordered(r, _, Some(_)) => {
  2196. let (data, len) = crate::resource::buffer_bytes(*r as crate::object::This)?;
  2197. Some((data as u64, len))
  2198. }
  2199. View::Placed(_, resource, desc) if resource[0] == 1 => Some((
  2200. u64::from(desc[10]) | u64::from(desc[11]) << 32,
  2201. u64::from(resource[4]) | u64::from(resource[5]) << 32,
  2202. )),
  2203. _ => None,
  2204. }
  2205. }
  2206. /// Whether a buffer view is brought up to date in the host copy its slot
  2207. /// shows ([`buffer_copy`]). On by default; `VICTORY_VIEW_EXTENT=0` looks the
  2208. /// copy up by the view's range alone, as before.
  2209. fn view_extent() -> bool {
  2210. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2211. *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_EXTENT").is_none_or(|v| v != "0"))
  2212. }
  2213. /// The host copy buffer view `view` reads, and the title range (address,
  2214. /// bytes) it reads there; `None` for other views and empty ranges.
  2215. ///
  2216. /// The copy is the one the view's slot shows: [`make`] finds it by the
  2217. /// whole buffer the view is of ([`buffer_extent`]). Looked up by the range
  2218. /// the view reads, as it was, the copy is another one wherever the two
  2219. /// lookups differ: for memory outside buffer objects, a view of a part of a
  2220. /// buffer that crosses a window line (the buffer's window is two cells, the
  2221. /// part's one), and for buffer objects, a part that also lies in a smaller
  2222. /// buffer object. The slot then showed a copy nothing brought up to date,
  2223. /// and what shaders wrote through it was looked for in the other copy.
  2224. pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc<crate::shadow::Shadow>, u64, u64)> {
  2225. let (address, len) = buffer_range(view)?;
  2226. if len == 0 {
  2227. return None;
  2228. }
  2229. if view_extent()
  2230. && let Some((base, width)) = buffer_extent(view)
  2231. // (The console is lax: a view may begin past its buffer's end.)
  2232. && address >= base
  2233. && address - base < width.max(1)
  2234. && let Some(shadow) = crate::shadow::find(base, width)
  2235. {
  2236. return Some((view_home(shadow, address, len, view_elements(view)?), address, len));
  2237. }
  2238. let shadow = crate::shadow::find(address, len)?;
  2239. Some((view_home(shadow, address, len, view_elements(view)?), address, len))
  2240. }
  2241. /// [`buffer_range`] of an unordered access view of memory at `base`.
  2242. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
  2243. let desc = uav_desc(words);
  2244. // SAFETY: a buffer view's union member.
  2245. let buffer = unsafe { desc.Anonymous.Buffer };
  2246. let element = if buffer.StructureByteStride > 0 {
  2247. u64::from(buffer.StructureByteStride)
  2248. } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2249. 4
  2250. } else {
  2251. crate::resource::element(desc.Format.0 as u32)?.0
  2252. };
  2253. Some((
  2254. base + buffer.FirstElement * element,
  2255. u64::from(buffer.NumElements) * element,
  2256. ))
  2257. }
  2258. /// The host resource a slot made by [`make`] views, if any.
  2259. type Kept = Option<ID3D12Resource>;
  2260. /// A structured buffer view (`first`, `count` elements of `stride` bytes,
  2261. /// `offset` bytes into its host copy) as a raw view of the same bytes:
  2262. /// its first dword and its dwords. Translated shaders read untyped buffers
  2263. /// as raw bytes at `element * stride + offset` (the stride from the
  2264. /// used-resource entry, or from the table by heap slot for a buffer picked
  2265. /// by index), and a raw read through a structured view gives zeros on
  2266. /// NVIDIA (reported upstream with PR #193; structured reads through raw
  2267. /// views were right there). So the host's view is raw whenever it can be:
  2268. /// the bytes must start on 16 (the host's raw view alignment) and be whole
  2269. /// dwords. A view that cannot stays structured.
  2270. fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, u32)> {
  2271. if stride == 0 {
  2272. return None;
  2273. }
  2274. let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?;
  2275. let bytes = u64::from(count) * u64::from(stride);
  2276. (start % 16 == 0 && bytes % 4 == 0)
  2277. .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords)))
  2278. .flatten()
  2279. }
  2280. /// Whether the host accepts a buffer view with these fields of a buffer of
  2281. /// `width` bytes. It removes the device for one it does not (view creation
  2282. /// returns nothing), and the console is laxer: the title's heap holds
  2283. /// views past their memory's end, of no elements, of typeless formats
  2284. /// without the raw flag, with strides the host has no structured buffers
  2285. /// for. Since every buffer view of the heap is made for shaders that pick
  2286. /// them by index, one such view ended the run (2026-11-24, run 10).
  2287. fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool {
  2288. use crate::resource::family;
  2289. let f = format.0 as u32;
  2290. let element = if raw {
  2291. // raw: R32 typeless, counted in dwords, starting on 16 bytes
  2292. if format != DXGI_FORMAT_R32_TYPELESS || stride != 0 || !first.is_multiple_of(4) {
  2293. return false;
  2294. }
  2295. 4
  2296. } else if stride > 0 {
  2297. // structured: no format, a stride the host takes
  2298. if format != DXGI_FORMAT_UNKNOWN || stride > 2048 || !stride.is_multiple_of(4) {
  2299. return false;
  2300. }
  2301. u64::from(stride)
  2302. } else {
  2303. // typed: a format with a size that is not typeless
  2304. let typeless = family(f) == f && family(f + 1) == f;
  2305. match crate::resource::element(f) {
  2306. Some((bytes, 1)) if f != 0 && !typeless && bytes > 0 => bytes,
  2307. _ => return false,
  2308. }
  2309. };
  2310. count > 0
  2311. && first
  2312. .checked_add(u64::from(count))
  2313. .and_then(|end| end.checked_mul(element))
  2314. .is_some_and(|end| end <= width)
  2315. }
  2316. fn buffer_srv(
  2317. address: u64,
  2318. len: u64,
  2319. mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC,
  2320. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  2321. ) -> Option<Kept> {
  2322. let mut shadow = crate::shadow::find(address, len)?;
  2323. let mut offset = shadow.offset(address);
  2324. let unit = element_size(&desc);
  2325. // SAFETY: a buffer view's union member.
  2326. let own = unsafe { &mut desc.Anonymous.Buffer };
  2327. let start = address + own.FirstElement * unit;
  2328. let kind = (own.StructureByteStride, own.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, desc.Format.0 as u32);
  2329. let home = view_home(shadow.clone(), start, u64::from(own.NumElements) * unit, kind);
  2330. if !std::sync::Arc::ptr_eq(&home, &shadow) {
  2331. // Its own bytes: it begins where they do.
  2332. (shadow, offset) = (home, 0);
  2333. own.FirstElement = 0;
  2334. }
  2335. // A structured view as a raw view of the same bytes (see `raw_window`).
  2336. // SAFETY: a buffer view's union member.
  2337. let structured = unsafe { desc.Anonymous.Buffer };
  2338. let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
  2339. .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride))
  2340. .flatten();
  2341. if let Some((first, count)) = window {
  2342. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2343. desc.Anonymous.Buffer = D3D12_BUFFER_SRV {
  2344. FirstElement: first,
  2345. NumElements: count,
  2346. StructureByteStride: 0,
  2347. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  2348. };
  2349. }
  2350. let element = element_size(&desc);
  2351. // SAFETY: a buffer view's union member.
  2352. let buffer = unsafe { &mut desc.Anonymous.Buffer };
  2353. if window.is_none() {
  2354. if element == 0 || offset % element != 0 {
  2355. once!(
  2356. offset,
  2357. element,
  2358. "buffer view not on an element of its host copy"
  2359. );
  2360. return None;
  2361. }
  2362. buffer.FirstElement += offset / element;
  2363. }
  2364. let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride);
  2365. let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0;
  2366. // SAFETY: a live buffer.
  2367. let width = unsafe { shadow.buffer.GetDesc() }.Width;
  2368. if !buffer_view_ok(desc.Format, first, count, stride, raw, width) {
  2369. REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2370. once!(
  2371. format = desc.Format.0,
  2372. first,
  2373. count,
  2374. stride,
  2375. raw,
  2376. width,
  2377. "buffer view the host would refuse left null"
  2378. );
  2379. return None;
  2380. }
  2381. // The console has no component mapping; one the host does not know is the default's.
  2382. if desc.Shader4ComponentMapping != D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING {
  2383. desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  2384. }
  2385. let host = host()?;
  2386. // SAFETY: a live buffer and a slot of our heap.
  2387. unsafe {
  2388. host.device
  2389. .CreateShaderResourceView(&shadow.buffer, Some(&desc), at)
  2390. };
  2391. Some(Some(shadow.buffer.clone()))
  2392. }
  2393. /// An unordered access view of title buffer memory at `address` (`len`
  2394. /// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be
  2395. /// written by shaders (upload memory).
  2396. /// shortcut: what shaders write stays in the host copy; title memory (and
  2397. /// so the CPU, and copies run on the CPU) does not see it.
  2398. fn buffer_uav(
  2399. address: u64,
  2400. len: u64,
  2401. mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC,
  2402. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  2403. ) -> Option<Kept> {
  2404. let mut shadow = crate::shadow::find(address, len)?;
  2405. let unit = {
  2406. // SAFETY: a buffer view's union member.
  2407. let b = unsafe { desc.Anonymous.Buffer };
  2408. if b.StructureByteStride > 0 {
  2409. u64::from(b.StructureByteStride)
  2410. } else if b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2411. 4
  2412. } else {
  2413. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2414. }
  2415. };
  2416. // SAFETY: a buffer view's union member.
  2417. let own = unsafe { &mut desc.Anonymous.Buffer };
  2418. let start = address + own.FirstElement * unit;
  2419. let kind = (own.StructureByteStride, own.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, desc.Format.0 as u32);
  2420. let home = view_home(shadow.clone(), start, u64::from(own.NumElements) * unit, kind);
  2421. let mut address = address;
  2422. if !std::sync::Arc::ptr_eq(&home, &shadow) {
  2423. // Its own bytes: it begins where they do.
  2424. (shadow, address) = (home, start);
  2425. own.FirstElement = 0;
  2426. }
  2427. // SAFETY: a live buffer.
  2428. let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
  2429. if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
  2430. once!("unordered access to a buffer whose host copy shaders cannot write");
  2431. return None;
  2432. }
  2433. // SAFETY: a buffer view's union member.
  2434. let buffer = unsafe { &mut desc.Anonymous.Buffer };
  2435. let element = if buffer.StructureByteStride > 0 {
  2436. u64::from(buffer.StructureByteStride)
  2437. } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  2438. 4
  2439. } else {
  2440. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  2441. };
  2442. let offset = shadow.offset(address);
  2443. // A structured view as a raw view of the same bytes (see `raw_window`).
  2444. let window = (desc.Format == DXGI_FORMAT_UNKNOWN)
  2445. .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride))
  2446. .flatten();
  2447. if let Some((first, count)) = window {
  2448. buffer.FirstElement = first;
  2449. buffer.NumElements = count;
  2450. buffer.StructureByteStride = 0;
  2451. buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  2452. } else {
  2453. if element == 0 || offset % element != 0 {
  2454. once!(offset, element, "unordered buffer view not on an element of its host copy");
  2455. return None;
  2456. }
  2457. buffer.FirstElement += offset / element;
  2458. }
  2459. buffer.CounterOffsetInBytes = 0;
  2460. let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride);
  2461. let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0;
  2462. if window.is_some() {
  2463. // (Left out at first: every structured unordered access view was then
  2464. // refused by `buffer_view_ok` and left null, runs 15 and 16.)
  2465. desc.Format = DXGI_FORMAT_R32_TYPELESS;
  2466. }
  2467. // SAFETY: a live buffer.
  2468. let width = unsafe { shadow.buffer.GetDesc() }.Width;
  2469. if !buffer_view_ok(desc.Format, first, count, stride, raw, width) {
  2470. REFUSED_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2471. once!(
  2472. format = desc.Format.0,
  2473. first,
  2474. count,
  2475. stride,
  2476. raw,
  2477. width,
  2478. "unordered buffer view the host would refuse left null"
  2479. );
  2480. return None;
  2481. }
  2482. let host = host()?;
  2483. // SAFETY: a live buffer and a slot of our heap.
  2484. unsafe {
  2485. host.device
  2486. .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at)
  2487. };
  2488. Some(Some(shadow.buffer.clone()))
  2489. }
  2490. /// Whether the host can make a shader (or unordered access) view of
  2491. /// `texture` in `format` (none: the texture's own). The console allows any
  2492. /// view; the host refuses (and removes the device for) views without the
  2493. /// resource's permission, of typed depth, and in another format than a
  2494. /// typed resource's. A view of a typed texture in another format of its
  2495. /// family takes the texture's format.
  2496. /// shortcut: such a view (sRGB of UNORM, say) reads without its
  2497. /// conversion; cast with castable formats if colors come out wrong.
  2498. fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool {
  2499. use crate::resource::{DEPTH_FORMATS, family};
  2500. // SAFETY: a live resource.
  2501. let d = unsafe { texture.GetDesc() };
  2502. let allowed = if unordered {
  2503. d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0
  2504. } else {
  2505. d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0
  2506. };
  2507. let own = d.Format.0 as u32;
  2508. if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) {
  2509. if unordered {
  2510. crate::resource::DEPTH_UNORDERED[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2511. }
  2512. once!(
  2513. unordered,
  2514. format = own,
  2515. flags = d.Flags.0,
  2516. "view the host does not allow"
  2517. );
  2518. return false;
  2519. }
  2520. // Every family has more than one format, its typeless one first.
  2521. let typeless = family(own) == own && family(own + 1) == own;
  2522. if let Some(format) = format.as_deref_mut()
  2523. && unordered
  2524. && let Some(&(_, linear)) = crate::resource::SRGB
  2525. .iter()
  2526. .find(|&&(s, _)| s == format.0 as u32)
  2527. {
  2528. format.0 = linear as i32;
  2529. }
  2530. let view = format.as_ref().map_or(0, |f| f.0 as u32);
  2531. if view == 0 {
  2532. return !typeless;
  2533. }
  2534. // A view of a target whose format the host refuses, in the title's
  2535. // format: in the stand-in the host copy has.
  2536. if view != own && crate::resource::target_format(view) == own {
  2537. if let Some(format) = format {
  2538. *format = d.Format;
  2539. }
  2540. return true;
  2541. }
  2542. if family(view) != family(own) {
  2543. once!(view, own, "view format of another family");
  2544. return false;
  2545. }
  2546. if let Some(format) = format
  2547. && !typeless
  2548. {
  2549. *format = d.Format;
  2550. }
  2551. true
  2552. }
  2553. /// The title's unordered access view of a depth texture, as a view of the
  2554. /// texture's colour twin `twin` ([`crate::resource::Twin`]): the same mip
  2555. /// and slices, in the colour format of the twin's family for a depth or
  2556. /// typeless format (R16_UNORM for 16-bit depth, R32_FLOAT for 32-bit; the
  2557. /// bits are the same). Without a description: mip 0 of every slice.
  2558. /// The twin of a stencil plane (R8) stands for the views of that plane
  2559. /// only, which become R8_UINT views of its one plane; `None` for a view of
  2560. /// the depth plane, which the twin does not stand for. The depth plane has
  2561. /// a twin of its own, viewed as a depth texture's without stencil: a view
  2562. /// in the format of the depth plane of a depth-stencil format (21, 46)
  2563. /// takes the twin's colour format too.
  2564. fn twin_uav(
  2565. twin: &ID3D12Resource,
  2566. desc: Option<&D3D12_UNORDERED_ACCESS_VIEW_DESC>,
  2567. ) -> Option<D3D12_UNORDERED_ACCESS_VIEW_DESC> {
  2568. // SAFETY: a live resource.
  2569. let d = unsafe { twin.GetDesc() };
  2570. let mut desc = desc.cloned().unwrap_or_else(|| {
  2571. let mut all = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2572. ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
  2573. ..Default::default()
  2574. };
  2575. if d.DepthOrArraySize > 1 {
  2576. all.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  2577. all.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
  2578. ArraySize: u32::from(d.DepthOrArraySize),
  2579. ..Default::default()
  2580. };
  2581. }
  2582. all
  2583. });
  2584. // A stencil plane's twin (R8 typeless, 60): the title's view is of the
  2585. // stencil plane if it names plane 1 or a stencil view format (22, 47).
  2586. if d.Format.0 == 60 {
  2587. let mut plane = 0;
  2588. match desc.ViewDimension {
  2589. D3D12_UAV_DIMENSION_TEXTURE2D => {
  2590. // SAFETY: the member the dimension names.
  2591. let mut view = unsafe { desc.Anonymous.Texture2D };
  2592. plane = std::mem::take(&mut view.PlaneSlice);
  2593. desc.Anonymous.Texture2D = view;
  2594. }
  2595. D3D12_UAV_DIMENSION_TEXTURE2DARRAY => {
  2596. // SAFETY: the member the dimension names.
  2597. let mut view = unsafe { desc.Anonymous.Texture2DArray };
  2598. plane = std::mem::take(&mut view.PlaneSlice);
  2599. desc.Anonymous.Texture2DArray = view;
  2600. }
  2601. _ => {}
  2602. }
  2603. if plane != 1 && !matches!(desc.Format.0, 22 | 47) {
  2604. return None;
  2605. }
  2606. desc.Format.0 = 62;
  2607. return Some(desc);
  2608. }
  2609. // None, typeless and depth formats (R16: 0, 53, 55; R32: 0, 39, 40),
  2610. // and those of a depth-stencil format's depth plane (19 to 21, 44 to
  2611. // 46), for the twin of such a plane.
  2612. desc.Format.0 = match (desc.Format.0, d.Format.0) {
  2613. (0 | 53 | 55 | 19..=21 | 44..=46, 53) => 56,
  2614. (0 | 39 | 40 | 19..=21 | 44..=46, 39) => 41,
  2615. (other, _) => other,
  2616. };
  2617. Some(desc)
  2618. }
  2619. /// The bytes of the host's constant buffer view for a title's of `size`:
  2620. /// whole 256s, and at most the 64 KiB a shader can index. The host removes
  2621. /// the device for a larger view, and the title's heap holds such sizes in
  2622. /// slots it does not use.
  2623. fn constant_bytes(size: u32) -> u32 {
  2624. const LARGEST: u32 = 64 << 10;
  2625. size.min(LARGEST).next_multiple_of(256)
  2626. }
  2627. /// Makes the host descriptor for `view` at `at`: the host resource it
  2628. /// views, or `None` if it cannot.
  2629. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
  2630. let host = host()?;
  2631. let device = &host.device;
  2632. match view {
  2633. &View::Constant(address, size) => {
  2634. let shadow = crate::shadow::find(address, u64::from(size))?;
  2635. let gpu = shadow.gpu(address);
  2636. if gpu % 256 != 0 {
  2637. once!(
  2638. address = format_args!("{address:#x}"),
  2639. "constant buffer not 256-byte aligned on the host"
  2640. );
  2641. return None;
  2642. }
  2643. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
  2644. BufferLocation: gpu,
  2645. SizeInBytes: constant_bytes(size),
  2646. };
  2647. // SAFETY: a slot of our heap; the range lies in the host copy.
  2648. unsafe { device.CreateConstantBufferView(Some(&desc), at) };
  2649. Some(Some(shadow.buffer.clone()))
  2650. }
  2651. View::Shader(resource, desc) => {
  2652. let resource = *resource as crate::object::This;
  2653. if let Some(texture) = crate::resource::host_resource(resource) {
  2654. // The title's views of textures with a stencil plane, as it
  2655. // describes them (format, dimension, component mapping, a
  2656. // pad, then first level, levels, plane): each distinct one
  2657. // once. They say how its shaders read the stencil plane
  2658. // (the lighting takes each pixel's material class and its
  2659. // "inside a room" bit from it).
  2660. #[cfg(feature = "diagnostics")]
  2661. {
  2662. // SAFETY: a live resource.
  2663. let own = unsafe { texture.GetDesc() }.Format.0;
  2664. if matches!(own, 19..=22 | 44..=47) {
  2665. static SEEN: Mutex<Vec<(i32, Option<[u32; 10]>)>> = Mutex::new(Vec::new());
  2666. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  2667. if seen.len() < 64 && !seen.contains(&(own, *desc)) {
  2668. seen.push((own, *desc));
  2669. tracing::info!(
  2670. ?resource,
  2671. texture_format = own,
  2672. view = ?desc,
  2673. "shader view of a depth-stencil texture"
  2674. );
  2675. }
  2676. }
  2677. }
  2678. let mut desc = desc.as_ref().map(srv_desc);
  2679. if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
  2680. return None;
  2681. }
  2682. // Levels on demand (`crate::tiles`): a texture made level by
  2683. // level is shown from the first level that is the title's
  2684. // and has memory, if the title's view starts before it (a
  2685. // level without memory reads zeros: a black texture). The
  2686. // title's own view mostly starts there already.
  2687. if let Some(first) = crate::resource::first_shown(resource)
  2688. && first > 0
  2689. {
  2690. // SAFETY: a live resource.
  2691. let own = unsafe { texture.GetDesc() };
  2692. // The texture's own view (the title gave none): all of it.
  2693. let whole = D3D12_SHADER_RESOURCE_VIEW_DESC {
  2694. Format: own.Format,
  2695. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  2696. Shader4ComponentMapping: 5768,
  2697. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  2698. Texture2D: D3D12_TEX2D_SRV {
  2699. MostDetailedMip: 0,
  2700. MipLevels: u32::MAX,
  2701. PlaneSlice: 0,
  2702. ResourceMinLODClamp: 0.0,
  2703. },
  2704. },
  2705. };
  2706. crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels));
  2707. }
  2708. // SAFETY: a live texture and a slot of our heap.
  2709. unsafe {
  2710. device.CreateShaderResourceView(
  2711. texture,
  2712. desc.as_ref().map(std::ptr::from_ref),
  2713. at,
  2714. )
  2715. };
  2716. Some(Some(texture.clone()))
  2717. } else if let (Some((data, len)), Some(desc)) =
  2718. (crate::resource::buffer_bytes(resource), desc)
  2719. {
  2720. buffer_srv(data as u64, len, srv_desc(desc), at)
  2721. } else {
  2722. None
  2723. }
  2724. }
  2725. View::Unordered(resource, _counter, desc) => {
  2726. let resource = *resource as crate::object::This;
  2727. let Some(texture) = crate::resource::host_resource(resource) else {
  2728. return match (crate::resource::buffer_bytes(resource), desc) {
  2729. (Some((data, len)), Some(desc)) => {
  2730. buffer_uav(data as u64, len, uav_desc(desc), at)
  2731. }
  2732. _ => None,
  2733. };
  2734. };
  2735. // The first such views of depth textures are logged as the
  2736. // title describes them (format, dimension, then mip, slices and
  2737. // plane): they say which planes shaders write, and as what.
  2738. if crate::resource::depth_and_unordered(resource) {
  2739. static LOGGED: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  2740. if LOGGED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 512 {
  2741. tracing::info!(
  2742. ?resource,
  2743. view = ?desc,
  2744. "unordered access view of a depth texture"
  2745. );
  2746. }
  2747. }
  2748. let mut desc = desc.as_ref().map(uav_desc);
  2749. // A depth texture's unordered access is its colour twin's: the
  2750. // host gives a depth texture none.
  2751. let twin = crate::resource::twin_resource(resource)
  2752. .and_then(|twin| Some((twin, twin_uav(twin, desc.as_ref())?)))
  2753. // A view of the depth plane of a texture with a stencil
  2754. // plane: of that plane's own twin.
  2755. .or_else(|| {
  2756. let twin = crate::resource::twin_plane_resource(resource)?;
  2757. Some((twin, twin_uav(twin, desc.as_ref())?))
  2758. });
  2759. let texture = match twin {
  2760. Some((twin, view)) => {
  2761. desc = Some(view);
  2762. twin
  2763. }
  2764. None => texture,
  2765. };
  2766. if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
  2767. return None;
  2768. }
  2769. // SAFETY: a live texture and a slot of our heap.
  2770. unsafe {
  2771. device.CreateUnorderedAccessView(
  2772. texture,
  2773. None::<&ID3D12Resource>,
  2774. desc.as_ref().map(std::ptr::from_ref),
  2775. at,
  2776. )
  2777. };
  2778. Some(Some(texture.clone()))
  2779. }
  2780. View::Sampler(words) => {
  2781. // SAFETY: 13 words in the host's layout.
  2782. let desc = unsafe {
  2783. std::ptr::from_ref(words)
  2784. .cast::<D3D12_SAMPLER_DESC>()
  2785. .read_unaligned()
  2786. };
  2787. // SAFETY: a slot of our sampler heap.
  2788. unsafe { device.CreateSampler(&desc, at) };
  2789. Some(None)
  2790. }
  2791. View::ConsoleSampler(words) => {
  2792. let desc = crate::sampler::console(words);
  2793. // SAFETY: a slot of our sampler heap.
  2794. unsafe { device.CreateSampler(&desc, at) };
  2795. Some(None)
  2796. }
  2797. View::Placed(unordered, resource, desc) => {
  2798. if let Some(view) = placed_texture(view) {
  2799. return make(&view, at);
  2800. }
  2801. const BUFFER: u32 = 1;
  2802. if resource[0] != BUFFER {
  2803. // shortcut: unordered access to a texture the title placed
  2804. // itself is not mirrored; give it a resource as shader
  2805. // views of such textures get when a dispatch writes one.
  2806. // Each texture is said once (the first 64), with how many times
  2807. // such a view was asked for so far: what shaders write through
  2808. // them is lost.
  2809. static SAID: Mutex<std::collections::BTreeSet<u64>> = Mutex::new(std::collections::BTreeSet::new());
  2810. static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  2811. let times = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  2812. let at = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2813. let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
  2814. if (said.len() < 64 && said.insert(at)) || times.is_power_of_two() {
  2815. tracing::warn!(
  2816. address = format_args!("{at:#x}"),
  2817. times,
  2818. "placed unordered texture view not mirrored (null: writes through it are lost): resource {resource:?}, view {:?}",
  2819. &desc[..10]
  2820. );
  2821. }
  2822. return None;
  2823. }
  2824. // The resource description's width, after the alignment.
  2825. let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
  2826. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2827. let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]);
  2828. // An empty title buffer: nothing to view, and no host copy to
  2829. // look for (#70: such views were in flight at device removals).
  2830. if len == 0 {
  2831. return None;
  2832. }
  2833. if *unordered {
  2834. buffer_uav(address, len, uav_desc(words), at)
  2835. } else {
  2836. buffer_srv(address, len, srv_desc(words), at)
  2837. }
  2838. }
  2839. }
  2840. }
  2841. /// Writes of a slot with another view of the placed texture it showed,
  2842. /// since the start: the slot kept showing the old view.
  2843. pub(crate) static KEPT_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  2844. /// Whether a slot written with another view of the placed texture it
  2845. /// shows keeps showing the old one until the new is made;
  2846. /// `VICTORY_KEEP_VIEWS=0` makes it null at once, as before.
  2847. fn keep_views() -> bool {
  2848. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2849. *ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0"))
  2850. }
  2851. /// Whether a slot already made from its record is told so without the lock
  2852. /// (`VICTORY_QUICK_MIRROR=0`: with it, as before).
  2853. fn quick_mirror() -> bool {
  2854. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2855. *ON.get_or_init(|| std::env::var_os("VICTORY_QUICK_MIRROR").is_none_or(|v| v != "0"))
  2856. }
  2857. /// The records (`step` bytes each, the first is slot `first`) that differ
  2858. /// between `last` and `records` (of one length) go into `out` and `last`.
  2859. /// Most of a changed page is as it was: it is looked at sixteen records at a
  2860. /// time.
  2861. fn changed_records(last: &mut [u8], records: &[u8], step: usize, first: u32, out: &mut Vec<u32>) {
  2862. const AT_A_TIME: usize = 16;
  2863. let block = AT_A_TIME * step;
  2864. for (b, (old, new)) in last.chunks_mut(block).zip(records.chunks(block)).enumerate() {
  2865. if old == new {
  2866. continue;
  2867. }
  2868. for (n, (old, new)) in old.chunks_exact_mut(step).zip(new.chunks_exact(step)).enumerate() {
  2869. if old != new {
  2870. old.copy_from_slice(new);
  2871. out.push(first + (b * AT_A_TIME + n) as u32);
  2872. }
  2873. }
  2874. }
  2875. }
  2876. #[cfg(test)]
  2877. mod changed_records_tests {
  2878. use super::changed_records;
  2879. #[test]
  2880. fn changed_records_are_those_that_differ_one_by_one() {
  2881. for (step, count) in [(32usize, 128usize), (32, 2048), (16, 77), (32, 5), (32, 17)] {
  2882. let mut seed = 7u64;
  2883. let mut random = move || {
  2884. seed = seed.wrapping_mul(0x5851_F42D_4C95_7F2D).wrapping_add(0x1405_7B7E_F767_814F);
  2885. (seed >> 33) as usize
  2886. };
  2887. let mut last: Vec<u8> = (0..step * count).map(|_| random() as u8).collect();
  2888. let mut now = last.clone();
  2889. let mut differ = Vec::new();
  2890. for slot in 0..count {
  2891. if random() % 9 == 0 {
  2892. now[slot * step + random() % step] ^= 1 + (random() % 255) as u8;
  2893. differ.push(1000 + slot as u32);
  2894. }
  2895. }
  2896. let mut out = Vec::new();
  2897. changed_records(&mut last, &now, step, 1000, &mut out);
  2898. assert_eq!(out, differ);
  2899. assert_eq!(last, now);
  2900. out.clear();
  2901. changed_records(&mut last, &now, step, 1000, &mut out);
  2902. assert!(out.is_empty());
  2903. }
  2904. }
  2905. }
  2906. /// Whether both are shader views of one texture the title placed in
  2907. /// memory: the same address and the same resource description, whatever
  2908. /// part of it each shows.
  2909. fn same_placed_texture(a: &View, b: &View) -> bool {
  2910. match (a, b) {
  2911. (View::Placed(false, resource, desc), View::Placed(false, other, other_desc)) => {
  2912. resource[0] != 1 && resource == other && desc[10..12] == other_desc[10..12]
  2913. }
  2914. _ => false,
  2915. }
  2916. }
  2917. /// A shader view of a texture the title placed in memory itself, as a view
  2918. /// of the resource made for that memory (on first use).
  2919. pub(crate) fn placed_texture(view: &View) -> Option<View> {
  2920. const BUFFER: u32 = 1;
  2921. let View::Placed(false, resource, desc) = view else {
  2922. return None;
  2923. };
  2924. if resource[0] == BUFFER {
  2925. return None;
  2926. }
  2927. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  2928. let texture = crate::resource::texture_at(address, resource)?;
  2929. Some(View::Shader(texture as usize, desc[..10].try_into().ok()))
  2930. }
  2931. /// A null view of the kind `view` is, for a slot whose view the host
  2932. /// cannot make: unordered access (to a buffer or a 2D texture) or a shader
  2933. /// view. Writes to it are dropped, reads give zeros.
  2934. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  2935. let Some(host) = host() else { return };
  2936. let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some();
  2937. // Unordered views: whether a buffer, and the title's view dimension.
  2938. let (buffer, dimension) = match view {
  2939. View::Unordered(r, _, desc) => (
  2940. is_buffer(r) || desc.is_some_and(|d| d[1] == 1),
  2941. desc.map(|d| d[1]),
  2942. ),
  2943. View::Placed(true, resource, desc) => (resource[0] == 1, Some(desc[1])),
  2944. // Shader views of buffers read nothing through a null buffer view:
  2945. // a null 2D view where the shader expects a buffer is a mismatch
  2946. // the hardware does not survive in general (GPU-based validation
  2947. // reports it).
  2948. View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => {
  2949. return null_buffer_view(at);
  2950. }
  2951. View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at),
  2952. // Textures: a null view of the title's dimension (1D, arrays, 3D,
  2953. // cubes), not always 2D.
  2954. View::Shader(_, Some(desc)) => return null_like(desc, at),
  2955. View::Placed(false, _, desc) => {
  2956. return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at);
  2957. }
  2958. View::Constant(..) => {
  2959. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default();
  2960. // SAFETY: a slot of our heap; a zero location makes a null view.
  2961. return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) };
  2962. }
  2963. _ => return null_view(at),
  2964. };
  2965. let desc = if buffer {
  2966. D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2967. Format: DXGI_FORMAT_R32_UINT,
  2968. ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
  2969. ..Default::default()
  2970. }
  2971. } else {
  2972. null_uav_desc(dimension)
  2973. };
  2974. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  2975. unsafe {
  2976. host.device.CreateUnorderedAccessView(
  2977. None::<&ID3D12Resource>,
  2978. None::<&ID3D12Resource>,
  2979. Some(&desc),
  2980. at,
  2981. )
  2982. };
  2983. }
  2984. /// A null texture UAV of the title's view dimension (1D, 1D or 2D arrays,
  2985. /// 3D), 2D if it names none: a 2D null view where the shader writes a 3D
  2986. /// texture is a mismatch GPU-based validation reports (the world's wind
  2987. /// field, CS_CopyWindFieldBeforeUpdateWithSmooth, 2026-11-24).
  2988. fn null_uav_desc(dimension: Option<u32>) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2989. let mut desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  2990. Format: DXGI_FORMAT_R32_UINT,
  2991. ViewDimension: D3D12_UAV_DIMENSION_TEXTURE2D,
  2992. ..Default::default()
  2993. };
  2994. match dimension.map(|d| D3D12_UAV_DIMENSION(d as i32)) {
  2995. Some(D3D12_UAV_DIMENSION_TEXTURE1D) => {
  2996. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1D;
  2997. }
  2998. Some(D3D12_UAV_DIMENSION_TEXTURE1DARRAY) => {
  2999. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE1DARRAY;
  3000. desc.Anonymous.Texture1DArray = D3D12_TEX1D_ARRAY_UAV {
  3001. ArraySize: 1,
  3002. ..Default::default()
  3003. };
  3004. }
  3005. Some(D3D12_UAV_DIMENSION_TEXTURE2DARRAY) => {
  3006. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE2DARRAY;
  3007. desc.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_UAV {
  3008. ArraySize: 1,
  3009. ..Default::default()
  3010. };
  3011. }
  3012. Some(D3D12_UAV_DIMENSION_TEXTURE3D) => {
  3013. desc.ViewDimension = D3D12_UAV_DIMENSION_TEXTURE3D;
  3014. desc.Anonymous.Texture3D = D3D12_TEX3D_UAV {
  3015. WSize: u32::MAX,
  3016. ..Default::default()
  3017. };
  3018. }
  3019. _ => {}
  3020. }
  3021. desc
  3022. }
  3023. /// A buffer view that reads zeros (raw, as translated shaders mostly read
  3024. /// buffers).
  3025. fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3026. let Some(host) = host() else { return };
  3027. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3028. Format: DXGI_FORMAT_R32_TYPELESS,
  3029. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  3030. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  3031. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3032. Buffer: D3D12_BUFFER_SRV {
  3033. NumElements: 1,
  3034. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  3035. ..Default::default()
  3036. },
  3037. },
  3038. };
  3039. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3040. unsafe {
  3041. host.device
  3042. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3043. };
  3044. }
  3045. /// A texture view that reads zeros with the dimension (and mip and array
  3046. /// counts) of the title's description `words`; 2D if it names none.
  3047. fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3048. const TEXTURES: std::ops::RangeInclusive<u32> = 2..=10;
  3049. if !TEXTURES.contains(&words[1]) {
  3050. return null_view(at);
  3051. }
  3052. let Some(host) = host() else { return };
  3053. // One mip, one slice or cube, plane 0: fields a null view still checks.
  3054. let mut w = [0u32; 10];
  3055. w[1] = words[1];
  3056. match words[1] {
  3057. 6 => {}
  3058. 7 => w[5] = 1,
  3059. 3 | 5 | 10 => (w[5], w[7]) = (1, 1),
  3060. _ => w[5] = 1,
  3061. }
  3062. let mut desc = srv_desc(&w);
  3063. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  3064. desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  3065. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3066. unsafe {
  3067. host.device
  3068. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3069. };
  3070. }
  3071. /// A view that reads zeros, for slots whose view the host cannot make.
  3072. /// shortcut: slots with no view at all (kind unknown) get this null 2D
  3073. /// view; null buffer views there did not stop the world's low-address
  3074. /// page faults (2026-11-24, run w10), so they are not the cause.
  3075. fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  3076. let Some(host) = host() else { return };
  3077. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  3078. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  3079. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  3080. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  3081. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  3082. Texture2D: D3D12_TEX2D_SRV {
  3083. MipLevels: 1,
  3084. ..Default::default()
  3085. },
  3086. },
  3087. };
  3088. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  3089. unsafe {
  3090. host.device
  3091. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  3092. };
  3093. }
  3094. #[cfg(test)]
  3095. mod tests {
  3096. use super::*;
  3097. /// A texture filled with less than was mapped is looked at again, but
  3098. /// not for ever: memory that is shown and cannot be read ends it, and a
  3099. /// filling that got everything starts the count anew.
  3100. #[test]
  3101. fn a_short_filling_is_looked_at_again_a_few_times() {
  3102. // An address no other test names.
  3103. let start = 0x7fee_1234_0000u64;
  3104. let pending = || super::SHORT.lock().unwrap().0.remove(&start);
  3105. for _ in 0..super::SHORT_IN_A_ROW {
  3106. super::read_short(start);
  3107. assert!(pending());
  3108. }
  3109. super::read_short(start);
  3110. assert!(!pending());
  3111. super::read_all(start);
  3112. super::read_short(start);
  3113. assert!(pending());
  3114. super::read_all(start);
  3115. }
  3116. /// A null texture UAV keeps the title's dimension (3D for the world's
  3117. /// wind field), and is 2D when the title names none.
  3118. #[test]
  3119. fn null_uavs_keep_the_titles_dimension() {
  3120. let d = null_uav_desc(Some(8));
  3121. assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE3D);
  3122. // SAFETY: the member the dimension names.
  3123. assert_eq!(unsafe { d.Anonymous.Texture3D.WSize }, u32::MAX);
  3124. let d = null_uav_desc(Some(5));
  3125. assert_eq!(d.ViewDimension, D3D12_UAV_DIMENSION_TEXTURE2DARRAY);
  3126. // SAFETY: the member the dimension names.
  3127. assert_eq!(unsafe { d.Anonymous.Texture2DArray.ArraySize }, 1);
  3128. let dimension = |d| null_uav_desc(d).ViewDimension;
  3129. assert_eq!(dimension(Some(2)), D3D12_UAV_DIMENSION_TEXTURE1D);
  3130. assert_eq!(dimension(Some(4)), D3D12_UAV_DIMENSION_TEXTURE2D);
  3131. assert_eq!(dimension(None), D3D12_UAV_DIMENSION_TEXTURE2D);
  3132. // Multisampled UAVs need a cap; they stay 2D.
  3133. assert_eq!(dimension(Some(6)), D3D12_UAV_DIMENSION_TEXTURE2D);
  3134. }
  3135. /// What the texture code asks of the spans (levels on demand): where
  3136. /// the next texture starts inside a span, the lowest level a view of a
  3137. /// texture shows, and a texture's slots.
  3138. #[test]
  3139. fn spans_say_the_next_start_and_the_lowest_level_viewed() {
  3140. let mut spans = Spans::default();
  3141. // A 512x512 texture of 0x56000 bytes viewed from levels 3 and 1,
  3142. // and the next one 0x6000 after it (run 188).
  3143. spans.note(1, 0x1_0000, 0x1_0000 + 0x5_6000, true);
  3144. spans.shows(1, 3);
  3145. spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true);
  3146. spans.shows(2, 1);
  3147. spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true);
  3148. assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000));
  3149. assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None);
  3150. assert_eq!(spans.first_viewed(0x1_0000), Some(1));
  3151. assert_eq!(spans.first_viewed(0x1_6000), None);
  3152. assert_eq!(spans.slots_at(0x1_0000), vec![1, 2]);
  3153. // The view from level 1 goes: the texture is viewed from level 3.
  3154. spans.forget(2);
  3155. assert_eq!(spans.first_viewed(0x1_0000), Some(3));
  3156. }
  3157. /// Views of one placed texture are told from views of others by the
  3158. /// address and the resource description, not by what they show.
  3159. #[test]
  3160. fn views_of_one_placed_texture_are_told_by_address_and_description() {
  3161. let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
  3162. let view = |resource: [u32; 14], first_mip: u32, address: u32| {
  3163. let mut desc = [0u32; 16];
  3164. (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb);
  3165. View::Placed(false, resource, desc)
  3166. };
  3167. let low = view(texture, 3, 0x1000_0000);
  3168. // more mips of the same texture
  3169. assert!(same_placed_texture(&low, &view(texture, 0, 0x1000_0000)));
  3170. // another address, another description, a buffer, an unordered view
  3171. assert!(!same_placed_texture(&low, &view(texture, 3, 0x2000_0000)));
  3172. let mut wider = texture;
  3173. wider[4] = 1024;
  3174. assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000)));
  3175. let mut buffer = texture;
  3176. buffer[0] = 1;
  3177. assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000)));
  3178. let View::Placed(_, resource, desc) = low.clone() else { unreachable!() };
  3179. assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc)));
  3180. assert!(!same_placed_texture(&low, &View::Shader(0, None)));
  3181. }
  3182. /// A constant buffer view larger than the host takes is cut to what it
  3183. /// takes: the device, which such a view removes, stays.
  3184. #[test]
  3185. fn an_oversized_constant_buffer_view_leaves_the_device_alive() {
  3186. let Some(host) = host() else {
  3187. return; // no host GPU
  3188. };
  3189. let Some(heap) = HostHeap::new(false, 4) else {
  3190. return;
  3191. };
  3192. // SAFETY: a plain device query.
  3193. let alive = || unsafe { host.device.GetDeviceRemovedReason() }.is_ok();
  3194. // Made first: an allocation that fails on a removed device must not
  3195. // end the test early.
  3196. let (buffer, _) = host.upload_buffer(1 << 20).expect("an upload buffer");
  3197. let memory = vec![0u8; 2 << 20];
  3198. let at = (memory.as_ptr() as u64).next_multiple_of(64 << 10);
  3199. for size in [969_472u32, 896_256] {
  3200. assert!(make(&View::Constant(at, size), heap.cpu(0)).is_some());
  3201. assert!(alive(), "a view of {size} bytes");
  3202. }
  3203. // SAFETY: a live upload buffer.
  3204. heap.constant_at(1, unsafe { buffer.GetGPUVirtualAddress() }, 969_472);
  3205. assert!(alive(), "a view of the list's own memory");
  3206. assert_eq!(constant_bytes(480), 512);
  3207. assert_eq!(constant_bytes(64 << 10), 64 << 10);
  3208. assert_eq!(constant_bytes(u32::MAX), 64 << 10);
  3209. }
  3210. /// A null 3D UAV made on the real device leaves it alive.
  3211. #[test]
  3212. fn null_3d_uav_is_accepted_by_the_device() {
  3213. let Some(host) = host() else {
  3214. return; // no host GPU
  3215. };
  3216. let Some(heap) = HostHeap::new(false, 4) else {
  3217. return;
  3218. };
  3219. let view = View::Unordered(0, 0, Some([28, 8, 0, 0, 0, 0, 0, 0, 0, 0]));
  3220. null_for(&view, heap.cpu(0));
  3221. // SAFETY: a plain device query.
  3222. assert!(unsafe { host.device.GetDeviceRemovedReason() }.is_ok());
  3223. }
  3224. /// Dynamic slots stay taken until given back, and runs do not wrap.
  3225. #[test]
  3226. fn a_structured_view_made_raw_passes_the_host_check() {
  3227. // 100 elements of 20 bytes from element 8, in a copy that starts 32
  3228. // bytes before the view's memory: bytes 192..2192.
  3229. let (first, count) = raw_window(32, 8, 100, 20).unwrap();
  3230. assert_eq!((first, count), (48, 500));
  3231. assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096));
  3232. // the format a raw view must name; the structured one's is refused
  3233. assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096));
  3234. // past the buffer, not on 16 bytes, no elements
  3235. assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000));
  3236. assert!(raw_window(4, 0, 100, 20).is_none());
  3237. assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096));
  3238. // a structured view the host takes as it is
  3239. assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096));
  3240. }
  3241. /// Views that begin where no host view can: raw ones off 16 bytes,
  3242. /// structured ones off their elements (and off 16 bytes, where they are
  3243. /// made raw), typed ones off theirs.
  3244. #[test]
  3245. fn views_off_their_elements_are_told() {
  3246. // the colour table bakes' parameter block: raw, 8 bytes into its window
  3247. assert!(off_elements(8, 0, true, 4));
  3248. assert!(!off_elements(0, 0, true, 4));
  3249. assert!(!off_elements(48, 0, true, 4));
  3250. // 456-byte elements: at one of them, on 16 bytes, at neither
  3251. assert!(!off_elements(456, 456, false, 0));
  3252. assert!(!off_elements(32, 456, false, 0));
  3253. assert!(off_elements(100, 456, false, 0));
  3254. // A typed view of 12-byte elements on 16 bytes and not on an element.
  3255. assert!(off_elements(23_702_896, 0, false, 12));
  3256. assert!(!off_elements(48, 0, false, 12));
  3257. assert!(!off_elements(12, 0, false, 4));
  3258. assert!(off_elements(12, 0, false, 8));
  3259. }
  3260. /// Such a view is made on a copy of its own bytes, and that copy is the one
  3261. /// brought up to date for it; another's is its buffer's.
  3262. #[test]
  3263. fn views_off_their_elements_get_a_copy_of_their_bytes() {
  3264. let Some(host) = host() else {
  3265. return; // no host GPU here
  3266. };
  3267. let memory = vec![0u64; 1 << 13];
  3268. let start = (memory.as_ptr() as u64).next_multiple_of(4096);
  3269. // SAFETY: a plain CPU-side heap of one view.
  3270. let cpu: ID3D12DescriptorHeap = unsafe {
  3271. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  3272. Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
  3273. NumDescriptors: 1,
  3274. ..Default::default()
  3275. })
  3276. }
  3277. .unwrap();
  3278. // SAFETY: a live heap.
  3279. let at = unsafe { cpu.GetCPUDescriptorHandleForHeapStart() };
  3280. // Memory placed at `address`, seen as the title passes it: raw, 32
  3281. // dwords, or four 456-byte elements.
  3282. let view = |address: u64, raw: bool| {
  3283. let resource: [u32; 14] = [1, 0, 0, 0, 4 * 456, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
  3284. let mut desc = [0u32; 16];
  3285. let words = if raw {
  3286. [39, 1, 5768, 0, 0, 0, 32, 0, 1, 0]
  3287. } else {
  3288. [0, 1, 5768, 0, 0, 0, 4, 456, 0, 0]
  3289. };
  3290. desc[..10].copy_from_slice(&words);
  3291. (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
  3292. View::Placed(false, resource, desc)
  3293. };
  3294. let width = |v: &View| {
  3295. let made = make(v, at).expect("a view").expect("a buffer");
  3296. // SAFETY: a live buffer.
  3297. unsafe { made.GetDesc() }.Width
  3298. };
  3299. for (off, raw, len) in [(8, true, 128u64), (8, false, 4 * 456)] {
  3300. let v = view(start + off, raw);
  3301. assert_eq!(width(&v), len.next_multiple_of(256));
  3302. let (copy, address, bytes) = buffer_copy(&v).unwrap();
  3303. assert_eq!((copy.span(), address, bytes), ((start + off, len), start + off, len));
  3304. }
  3305. for (off, raw) in [(16, true), (32, false)] {
  3306. let v = view(start + off, raw);
  3307. let (copy, ..) = buffer_copy(&v).unwrap();
  3308. assert_ne!(copy.span().0, start + off, "its buffer's copy");
  3309. // SAFETY: a live buffer.
  3310. assert_eq!(width(&v), unsafe { copy.buffer.GetDesc() }.Width);
  3311. }
  3312. }
  3313. /// The queue of textures picked by index serves the slots looked at
  3314. /// before first, then the newest write and the oldest in turns; a
  3315. /// slot whose memory is not there is looked at again after
  3316. /// 1, 2, 4 frames up to the limit; and what the pass reports about a
  3317. /// slot written again meanwhile is dropped.
  3318. #[test]
  3319. fn the_texture_queue_serves_the_newest_writes_first() {
  3320. let mut q = TextureQueue::default();
  3321. // Slots 10..18 written in frames 1..9, slot 5 last.
  3322. for i in 0..8u32 {
  3323. q.written(10 + i, u64::from(i) + 1, 0, false);
  3324. }
  3325. q.written(5, 9, 0, false);
  3326. let order: Vec<u32> = q.due(9, 100).into_iter().map(|d| d.0).collect();
  3327. // newest, oldest, newest, oldest, and so on
  3328. assert_eq!(order, [5, 10, 17, 11, 16, 12, 15, 13, 14]);
  3329. assert_eq!(q.due(9, 2).len(), 2);
  3330. assert_eq!(q.census(9), [9, 9, 0, 0, 8]);
  3331. // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4.
  3332. let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1;
  3333. let w17 = write(&q, 17);
  3334. let mut frame = 9;
  3335. for wait in [1, 2, 4, 4] {
  3336. q.later(17, w17, frame, 4);
  3337. assert!(!q.due(frame + wait - 1, 100).iter().any(|d| d.0 == 17));
  3338. frame += wait;
  3339. // Due again, and ahead of every slot never looked at.
  3340. assert_eq!(q.due(frame, 100)[0].0, 17);
  3341. }
  3342. assert_eq!(q.census(9)[2], 1);
  3343. q.done(17, w17);
  3344. assert!(!q.due(u64::MAX, 100).iter().any(|d| d.0 == 17));
  3345. // Uploaded with part of its memory there: kept, with what was there.
  3346. let w16 = write(&q, 16);
  3347. q.partly(16, w16, 12, 4096);
  3348. assert_eq!(q.mapped(16), 4096);
  3349. assert_eq!(q.due(12, 100)[0].0, 16);
  3350. // The title writes slot 16 again while the pass works on it: what
  3351. // the pass then says about the old write changes nothing.
  3352. q.written(16, 13, 0, false);
  3353. q.done(16, w16);
  3354. q.later(16, w16, 13, 4);
  3355. assert_eq!(q.mapped(16), 0);
  3356. assert_eq!(q.due(13, 100)[0].0, 16);
  3357. // A draw that makes the host slot (`seen`) keeps what the queue knows,
  3358. let w15 = write(&q, 15);
  3359. q.partly(15, w15, 20, 8192);
  3360. q.written(15, 14, 0, true);
  3361. assert_eq!(q.mapped(15), 8192);
  3362. // and queues a slot the queue did not hold.
  3363. q.written(99, 14, 0, true);
  3364. assert!(q.due(14, 100).iter().any(|d| d.0 == 99));
  3365. // A write due later (a table's slot) is not handed out before.
  3366. q.written(98, 14, 16, false);
  3367. assert!(!q.due(15, 100).iter().any(|d| d.0 == 98));
  3368. assert!(q.due(16, 100).iter().any(|d| d.0 == 98));
  3369. }
  3370. /// Slots held back for lack of room on the card are not handed out
  3371. /// until their frame, keep their place, are not counted as waiting
  3372. /// for their memory, and all come back at once when the card has room;
  3373. /// a slot written again meanwhile is the title's new write.
  3374. #[test]
  3375. fn slots_held_for_lack_of_room_come_back_when_there_is_room() {
  3376. let mut q = TextureQueue::default();
  3377. for i in 0..4u32 {
  3378. q.written(20 + i, 1, 0, false);
  3379. }
  3380. let due = q.due(1, 100);
  3381. assert_eq!(due.len(), 4);
  3382. // The card is full: slots 20 and 21 are held back until frame 101.
  3383. for &(index, write) in due.iter().filter(|d| d.0 < 22) {
  3384. q.hold(index, write, 101);
  3385. }
  3386. let now: Vec<u32> = q.due(2, 100).into_iter().map(|d| d.0).collect();
  3387. assert!(!now.contains(&20) && !now.contains(&21));
  3388. assert!(now.contains(&22) && now.contains(&23));
  3389. assert_eq!(q.census(2)[2], 0, "held slots do not wait for their memory");
  3390. // Due again at their frame, in the order they had.
  3391. assert_eq!(q.due(101, 100), due);
  3392. // Slot 21 is written again while held: due as written.
  3393. q.written(21, 3, 0, false);
  3394. assert!(q.due(3, 100).iter().any(|d| d.0 == 21));
  3395. // Room again at frame 5: slot 20 is due at once, and only it was
  3396. // still held as it was.
  3397. assert_eq!(q.room(5), 1);
  3398. assert!(q.due(5, 100).iter().any(|d| d.0 == 20));
  3399. assert_eq!(q.room(6), 0);
  3400. }
  3401. /// Textures of which only the smallest levels are held, packed into
  3402. /// one another's address range (the three of run 188: 0x2c000 bytes
  3403. /// each at full size, their starts 0x2000 and 0x4000 apart): writing
  3404. /// any of them, in any order and again, leaves the others.
  3405. #[test]
  3406. fn packed_neighbours_stay() {
  3407. let mut spans = Spans::default();
  3408. assert_eq!(spans.rule, Rule::Start);
  3409. let at = 0xb_86bf_8000u64;
  3410. let (a, b, c) = (at, at + 0x2000, at + 0x6000);
  3411. assert!(spans.note(105_998, a, a + 0x2c000, true).is_empty());
  3412. assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty());
  3413. assert!(spans.note(108_521, c, c + 0x2c000, true).is_empty());
  3414. // The first written again (as a title does when levels arrive),
  3415. // from another slot too: its span reaches over the other two.
  3416. assert!(spans.note(7, a, a + 0x2c000, true).is_empty());
  3417. assert!(spans.note(106_004, b, b + 0x2c000, true).is_empty());
  3418. let mut all = spans.slots_in(0, u64::MAX);
  3419. all.sort_unstable();
  3420. assert_eq!(all, [7, 105_998, 106_004, 108_521]);
  3421. // A draw makes a slot of the second texture: it is one of them.
  3422. assert!(spans.note(9, b, b + 0x2c000, false).is_empty());
  3423. assert_eq!(spans.by_slot.get(&9), Some(&b));
  3424. }
  3425. /// A texture written where another starts replaces it: at the same
  3426. /// address with another length, or inside the block of its smallest
  3427. /// levels. The packed neighbours of the one replaced stay.
  3428. #[test]
  3429. fn a_texture_written_at_the_start_of_another_replaces_it() {
  3430. let mut spans = Spans::default();
  3431. let at = 0x7_0000_0000u64;
  3432. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  3433. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  3434. // Another length from the same start: slot 1 is stale, slot 2 not.
  3435. assert_eq!(spans.note(3, at, at + 0xb000, true), [1]);
  3436. // A start inside the first 4 KiB of slot 3's texture: stale too.
  3437. assert_eq!(spans.note(4, at + 0x800, at + 0x1800, true), [3]);
  3438. // And the other way: a texture that starts just before one.
  3439. assert_eq!(spans.note(5, at + 0x1800, at + 0x4800, true), [2]);
  3440. let mut left = spans.slots_in(0, u64::MAX);
  3441. left.sort_unstable();
  3442. assert_eq!(left, [4, 5]);
  3443. // Exactly 4 KiB apart: both there.
  3444. assert!(spans.note(6, at + 0x2800, at + 0x3800, true).is_empty());
  3445. // A draw's view that clashes is left out, and nothing is stale.
  3446. assert!(spans.note(8, at + 0x900, at + 0x2900, false).is_empty());
  3447. assert_eq!(spans.by_slot.get(&8), None);
  3448. assert_eq!(spans.by_slot.len(), 3);
  3449. }
  3450. /// A slot written with another texture leaves its old span; the same
  3451. /// view written again changes nothing.
  3452. #[test]
  3453. fn a_slot_rewritten_moves_to_its_new_span() {
  3454. let mut spans = Spans::default();
  3455. assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty());
  3456. assert!(spans.note(2, 0x12000, 0x3e000, true).is_empty());
  3457. assert!(spans.note(1, 0x10000, 0x3c000, true).is_empty());
  3458. assert_eq!(spans.slots_in(0x10000, 0x10001), [1]);
  3459. // Slot 1 now views a texture far away.
  3460. assert!(spans.note(1, 0x90000, 0x91000, true).is_empty());
  3461. assert_eq!(spans.slots_in(0x10000, 0x10001), [] as [u32; 0]);
  3462. assert_eq!(spans.slots_in(0x12000, 0x12001), [2]);
  3463. assert_eq!(spans.slots_in(0x90000, 0x90001), [1]);
  3464. spans.forget(1);
  3465. spans.forget(2);
  3466. assert!(spans.by_start.is_empty() && spans.by_slot.is_empty());
  3467. }
  3468. /// Memory the runtime maps, unmaps or writes names the textures that
  3469. /// are there: among packed neighbours the one whose held levels the
  3470. /// range lies in (it ends where the next one starts), and the ones
  3471. /// that start inside the range.
  3472. #[test]
  3473. fn memory_changed_under_packed_neighbours_names_the_ones_there() {
  3474. let mut spans = Spans::default();
  3475. let at = 0x7_0000_0000u64;
  3476. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  3477. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  3478. assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
  3479. // Inside the first one's held levels.
  3480. assert_eq!(spans.slots_in(at + 0x1000, at + 0x2000), [1]);
  3481. // Inside the second's: not the first, which ends where it starts.
  3482. assert_eq!(spans.slots_in(at + 0x3000, at + 0x4000), [2]);
  3483. // Past the last start: the last one.
  3484. assert_eq!(spans.slots_in(at + 0x20000, at + 0x21000), [3]);
  3485. // A range over all of them.
  3486. assert_eq!(spans.slots_in(at, at + 0x8000), [1, 2, 3]);
  3487. // Past the end of all: none.
  3488. assert_eq!(spans.slots_in(at + 0x32000, at + 0x33000), [] as [u32; 0]);
  3489. }
  3490. /// A write names the textures that hold its bytes: the one that
  3491. /// starts where the write starts, not the neighbour before it, whose
  3492. /// held levels end there.
  3493. #[test]
  3494. fn a_write_at_the_start_of_a_packed_texture_names_it_alone() {
  3495. let mut spans = Spans::default();
  3496. let at = 0x7_0000_0000u64;
  3497. assert!(spans.note(1, at, at + 0x2c000, true).is_empty());
  3498. assert!(spans.note(2, at + 0x2000, at + 0x2e000, true).is_empty());
  3499. assert!(spans.note(3, at + 0x6000, at + 0x32000, true).is_empty());
  3500. // A request that fills the second texture's held levels.
  3501. assert_eq!(spans.slots_in(at + 0x2000, at + 0x6000), [1, 2]);
  3502. assert_eq!(spans.slots_holding(at + 0x2000, at + 0x6000), [2]);
  3503. // From inside the first one's held levels on: both.
  3504. assert_eq!(spans.slots_holding(at + 0x1000, at + 0x3000), [1, 2]);
  3505. // A whole 64 KiB page: every texture that starts in it.
  3506. assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]);
  3507. // Past the last start, the last one; past all, or no bytes, none.
  3508. assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]);
  3509. assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]);
  3510. assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]);
  3511. }
  3512. /// A write behind the guards' back under a placed texture: a slot
  3513. /// waiting for its first upload is left alone, one uploaded before is
  3514. /// counted, and made due two frames on when that is asked for. (The
  3515. /// ranges are handed over here, not through the list all heaps share.)
  3516. #[test]
  3517. fn a_page_write_makes_an_uploaded_texture_slot_due_when_asked() {
  3518. let Some(heap) = HostHeap::new(false, 8) else {
  3519. return; // no host GPU
  3520. };
  3521. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  3522. // 64x64 BC7, one mip, at an address no test and no title uses.
  3523. let at = 0x7fed_0000_0000u64;
  3524. let mut desc = [0u32; 16];
  3525. (desc[10], desc[11]) = (at as u32, (at >> 32) as u32);
  3526. let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc);
  3527. assert!(heap.note_buffer(1, Some(&view), false).is_empty());
  3528. let written = [(at, at + 0x1000)];
  3529. // Waiting for its first upload: held, not uploaded, nothing done.
  3530. assert_eq!(heap.slots_written_under(&written, 50, true), [1, 0, 0]);
  3531. let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
  3532. assert_eq!(queued, 1);
  3533. heap.texture_slot_done(1, write, None);
  3534. assert_eq!(slots(u64::MAX), []);
  3535. // Uploaded and out of the queue. Memory elsewhere: nothing.
  3536. assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]);
  3537. // Under it, counted only: it stays out of the queue.
  3538. assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]);
  3539. assert_eq!(slots(u64::MAX), []);
  3540. // Under it, asked for: due two frames on, not before.
  3541. assert_eq!(heap.slots_written_under(&written, 60, true), [1, 1, 1]);
  3542. assert_eq!(slots(61), []);
  3543. assert_eq!(slots(62), [1]);
  3544. }
  3545. /// `VICTORY_STALE_TEXTURES=0`: nothing is ever stale, and a view that
  3546. /// overlaps others is left out of the spans, as before.
  3547. #[test]
  3548. fn never_stale_leaves_overlapping_views_out() {
  3549. let mut spans = Spans { rule: Rule::Never, ..Default::default() };
  3550. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
  3551. assert!(spans.note(2, 0x2000, 0x4000, true).is_empty());
  3552. assert!(spans.note(3, 0x1000, 0x2000, true).is_empty());
  3553. assert_eq!(spans.slots_in(0, u64::MAX), [1]);
  3554. }
  3555. /// The rule until run 188 (`VICTORY_STALE_TEXTURES=overlap`): a view
  3556. /// written over memory that older views describe otherwise makes
  3557. /// those stale; views of the same span are one texture's.
  3558. #[test]
  3559. fn a_newer_view_of_other_memory_makes_the_older_stale() {
  3560. let mut spans = Spans { rule: Rule::Overlap, ..Default::default() };
  3561. // Three textures side by side, the first in two slots.
  3562. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty());
  3563. assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
  3564. assert!(spans.note(3, 0x3000, 0x4000, true).is_empty());
  3565. assert!(spans.note(4, 0x8000, 0x9000, true).is_empty());
  3566. // The same slot written with the same span again: nothing changes.
  3567. assert!(spans.note(2, 0x1000, 0x3000, true).is_empty());
  3568. assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]);
  3569. assert_eq!(spans.slots_in(0x4000, 0x8000), [] as [u32; 0]);
  3570. // A draw makes a slot whose view overlaps them: left out, nothing stale.
  3571. assert!(spans.note(9, 0x2000, 0x3800, false).is_empty());
  3572. assert_eq!(spans.slots_in(0x2000, 0x3800), [1, 2, 3]);
  3573. // The title writes a texture over the end of the first and all of
  3574. // the second: their three slots are stale.
  3575. let mut stale = spans.note(5, 0x2000, 0x4000, true);
  3576. stale.sort_unstable();
  3577. assert_eq!(stale, [1, 2, 3]);
  3578. assert_eq!(spans.slots_in(0, u64::MAX), [5, 4]);
  3579. // Another start in the same memory: stale in turn. Another length
  3580. // from the same start too.
  3581. assert_eq!(spans.note(6, 0x2800, 0x3000, true), [5]);
  3582. assert_eq!(spans.note(7, 0x2800, 0x2c00, true), [6]);
  3583. // A slot that moves to another texture leaves its span behind.
  3584. assert!(spans.note(7, 0x8000, 0x9000, true).is_empty());
  3585. assert_eq!(spans.slots_in(0x2800, 0x2c00), [] as [u32; 0]);
  3586. assert_eq!(spans.slots_in(0x8000, 0x8001), [4, 7]);
  3587. spans.forget(4);
  3588. spans.forget(7);
  3589. assert!(spans.by_start.is_empty() && spans.by_slot.is_empty());
  3590. }
  3591. /// Memory the runtime maps under a slot's texture makes the slot due
  3592. /// again from the next frame; a stale slot leaves the queue.
  3593. #[test]
  3594. fn remapped_memory_makes_its_texture_slots_due() {
  3595. let Some(heap) = HostHeap::new(false, 8) else {
  3596. return; // no host GPU
  3597. };
  3598. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  3599. // 64x64 BC7, one mip, at an address no test and no title uses.
  3600. let at = 0x7fee_0000_0000u64;
  3601. let view = |address: u64, width: u32| {
  3602. let mut desc = [0u32; 16];
  3603. (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
  3604. View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc)
  3605. };
  3606. let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap();
  3607. assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty());
  3608. let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0];
  3609. assert_eq!(queued, 1);
  3610. heap.texture_slot_done(1, write, None);
  3611. assert_eq!(slots(u64::MAX), []);
  3612. // Memory elsewhere: nothing. Under the texture: due from the next frame.
  3613. remapped((at + 2 * len) as usize, 0x1000);
  3614. remapped(at as usize, 0x1000);
  3615. assert_eq!(heap.texture_slots_remapped(50), 1);
  3616. assert_eq!(slots(50), []);
  3617. assert_eq!(slots(51), [1]);
  3618. // A wider texture written at the same address: slot 1 is stale.
  3619. assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]);
  3620. assert_eq!(slots(u64::MAX), [2]);
  3621. }
  3622. /// A slot a draw read through a table leaves the queue; the title's
  3623. /// next write of it waits for its draw, and is due after the grace
  3624. /// frames if none reads it.
  3625. #[test]
  3626. fn slots_read_through_tables_leave_the_texture_queue() {
  3627. let Some(heap) = HostHeap::new(false, 8) else {
  3628. return; // no host GPU
  3629. };
  3630. let frame = 100;
  3631. let slots = |at: u64| -> Vec<u32> { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() };
  3632. let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]);
  3633. assert!(is_texture_view(&texture));
  3634. heap.queue_texture(2, true, false, frame);
  3635. heap.queue_texture(3, true, false, frame);
  3636. assert_eq!(slots(frame), [3, 2]);
  3637. heap.tabled_in(3, true, frame);
  3638. assert_eq!(slots(frame), [2]);
  3639. // Made in place by the draw that read it: still out.
  3640. heap.queue_texture(3, true, true, frame);
  3641. assert_eq!(slots(frame), [2]);
  3642. // Written again in the next frame: due once the grace frames have
  3643. // passed without a draw that reads it.
  3644. heap.queue_texture(3, true, false, frame + 1);
  3645. assert_eq!(slots(frame + TABLED_GRACE), [2]);
  3646. assert_eq!(slots(frame + 1 + TABLED_GRACE), [3, 2]);
  3647. // The draw comes after all: out again.
  3648. heap.tabled_in(3, true, frame + 1);
  3649. assert_eq!(slots(u64::MAX), [2]);
  3650. // A slot of a table no draw read stays queued; its next write waits.
  3651. heap.tabled_in(2, false, frame + 1);
  3652. assert_eq!(slots(frame + 1), [2]);
  3653. heap.queue_texture(2, true, false, frame + 2);
  3654. assert_eq!(slots(frame + 2), []);
  3655. // Long after the last table, a write is due at once.
  3656. heap.queue_texture(2, true, false, frame + 3 + TABLED_FRAMES);
  3657. assert_eq!(slots(frame + 3 + TABLED_FRAMES), [2]);
  3658. }
  3659. #[test]
  3660. fn dynamic_slots_are_held_until_released() {
  3661. let Some(heap) = HostHeap::new(false, 4) else {
  3662. return; // no host GPU
  3663. };
  3664. let a = heap.dynamic(heap.dynamic - 100).unwrap();
  3665. let b = heap.dynamic(60).unwrap();
  3666. assert_eq!((a, b), (4, 4 + heap.dynamic - 100));
  3667. // 40 left at the end: 50 do not fit until something is given back.
  3668. assert_eq!(heap.dynamic(50), None);
  3669. heap.release(a, 50);
  3670. assert_eq!(heap.dynamic(50), Some(4));
  3671. assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
  3672. }
  3673. #[test]
  3674. fn dynamic_search_can_find_a_run_across_the_cursor() {
  3675. let Some(heap) = HostHeap::new(false, 4) else {
  3676. eprintln!("no host descriptor heap; skipped");
  3677. return;
  3678. };
  3679. let first = heap.dynamic(1).unwrap();
  3680. let left = heap.dynamic(2).unwrap();
  3681. let right = heap.dynamic(2).unwrap();
  3682. let rest = heap.dynamic(heap.dynamic - 5).unwrap();
  3683. assert_eq!((first, left, right, rest), (4, 5, 7, 9));
  3684. // Reallocating the left half puts the cursor back in the middle.
  3685. heap.release(left, 2);
  3686. assert_eq!(heap.dynamic(2), Some(left));
  3687. heap.release(left, 2);
  3688. heap.release(right, 2);
  3689. assert_eq!(heap.dynamic(4), Some(left));
  3690. assert_eq!(heap.dynamic(1), None);
  3691. // A free slot at each physical end does not form a two-slot range.
  3692. heap.release(first, 1);
  3693. let last = first + heap.dynamic - 1;
  3694. heap.release(last, 1);
  3695. assert_eq!(heap.dynamic(2), None);
  3696. }
  3697. }