host.rs 204 KB

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