resource.rs 171 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536
  1. //! Heaps, committed and placed resources, and resource sizes.
  2. //!
  3. //! Heaps and resources are host memory and a resource's GPU address is its
  4. //! CPU address, as on the console; textures also get a host copy, and
  5. //! buffers a host copy when a draw reads them (`shadow`).
  6. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  7. use std::alloc::{Layout, alloc_zeroed, dealloc};
  8. use std::ffi::c_void;
  9. use std::ptr::NonNull;
  10. use victory_formats::texture;
  11. use crate::object::{
  12. self, E_INVALIDARG, E_OUTOFMEMORY, HEAP, HRESULT, Iid, Object, RESOURCE, S_OK, Table, This,
  13. guid,
  14. };
  15. /// The interfaces every device child also answers for.
  16. pub(crate) const PAGEABLE_IIDS: [Iid; 3] = [
  17. guid(
  18. 0x63ee58fb,
  19. 0x1268,
  20. 0x4835,
  21. [0x86, 0xda, 0xf0, 0x08, 0xce, 0x62, 0xf0, 0xd6],
  22. ),
  23. guid(
  24. 0x905db94b,
  25. 0xa00c,
  26. 0x4140,
  27. [0x9d, 0xf5, 0x2b, 0x64, 0xca, 0x9e, 0xa3, 0x57],
  28. ),
  29. guid(
  30. 0xc4fec28f,
  31. 0x7966,
  32. 0x4e95,
  33. [0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8],
  34. ),
  35. ];
  36. const HEAP_IIDS: [Iid; 4] = [
  37. guid(
  38. 0x6b3b2502,
  39. 0x6e51,
  40. 0x45b3,
  41. [0x90, 0xee, 0x98, 0x84, 0x26, 0x5e, 0x8d, 0xf3],
  42. ),
  43. PAGEABLE_IIDS[0],
  44. PAGEABLE_IIDS[1],
  45. PAGEABLE_IIDS[2],
  46. ];
  47. const RESOURCE_IIDS: [Iid; 4] = [
  48. guid(
  49. 0x696442be,
  50. 0xa72e,
  51. 0x4059,
  52. [0xbc, 0x79, 0x5b, 0x5c, 0x98, 0x04, 0x0f, 0xad],
  53. ),
  54. PAGEABLE_IIDS[0],
  55. PAGEABLE_IIDS[1],
  56. PAGEABLE_IIDS[2],
  57. ];
  58. const KIB_64: u64 = 64 << 10;
  59. const MIB_4: u64 = 4 << 20;
  60. #[repr(C)]
  61. #[derive(Debug, Clone, Copy)]
  62. pub(crate) struct HeapProperties {
  63. kind: u32,
  64. cpu_pages: u32,
  65. pool: u32,
  66. creation_nodes: u32,
  67. visible_nodes: u32,
  68. }
  69. #[repr(C)]
  70. #[derive(Debug, Clone, Copy)]
  71. pub(crate) struct HeapDesc {
  72. size: u64,
  73. properties: HeapProperties,
  74. alignment: u64,
  75. flags: u32,
  76. }
  77. #[repr(C)]
  78. #[derive(Debug, Clone, Copy)]
  79. pub(crate) struct ResourceDesc {
  80. dimension: u32,
  81. alignment: u64,
  82. width: u64,
  83. height: u32,
  84. depth_or_array_size: u16,
  85. mip_levels: u16,
  86. format: u32,
  87. sample_count: u32,
  88. sample_quality: u32,
  89. layout: u32,
  90. flags: u32,
  91. }
  92. #[cfg(windows)]
  93. impl ResourceDesc {
  94. /// The texture of this one's levels from `base` on.
  95. fn from_level(&self, base: u32) -> ResourceDesc {
  96. let mut d = *self;
  97. if base > 0 {
  98. d.width = (d.width >> base).max(1);
  99. d.height = (d.height >> base).max(1);
  100. d.mip_levels -= base as u16;
  101. }
  102. d
  103. }
  104. }
  105. #[repr(C)]
  106. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  107. pub(crate) struct AllocationInfo {
  108. size: u64,
  109. alignment: u64,
  110. }
  111. const _: () = assert!(size_of::<HeapProperties>() == 20);
  112. const _: () = assert!(size_of::<HeapDesc>() == 48);
  113. const _: () = assert!(size_of::<ResourceDesc>() == 56);
  114. const BUFFER: u32 = 1;
  115. const TEXTURE_3D: u32 = 4;
  116. /// Bytes per element and the element's width in texels (4 for block
  117. /// compression), by DXGI format number. `None` for 1-bit and video
  118. /// formats. The console adds 116/117 (10-bit float color), 118-120 (16-bit
  119. /// depth with 8-bit stencil, two planes: 3 bytes per texel), 189 (signed
  120. /// 10-bit color), 190 (two 4-bit channels) and 191 (24/8 color).
  121. pub(crate) fn element(format: u32) -> Option<(u64, u64)> {
  122. Some(match format {
  123. 1..=4 => (16, 1),
  124. 5..=8 => (12, 1),
  125. 9..=22 => (8, 1),
  126. 23..=47 | 67 | 87..=93 | 116 | 117 | 189 | 191 => (4, 1),
  127. 118..=120 => (3, 1),
  128. 48..=59 | 68 | 69 | 85 | 86 | 115 => (2, 1),
  129. 60..=65 | 190 => (1, 1),
  130. 70..=72 | 79..=81 => (8, 4),
  131. 73..=78 | 82..=84 | 94..=99 => (16, 4),
  132. _ => return None,
  133. })
  134. }
  135. /// A texture's layout in console memory, as the console's layout library
  136. /// gives it (`victory-hle`'s `xg` serves the same): the description's
  137. /// layout field is `0x100 | swizzle mode`, 1 linear, 0 the library's pick.
  138. pub(crate) fn texture_layout(desc: &ResourceDesc) -> Option<texture::Texture> {
  139. use texture::{Dimension, Swizzle, TextureDesc};
  140. const TEXTURE_1D: u32 = 2;
  141. const TEXTURE_2D: u32 = 3;
  142. const RENDER_TARGET: u32 = 1;
  143. const DEPTH: u32 = 2;
  144. let dimension = match desc.dimension {
  145. TEXTURE_1D => Dimension::Tex1d,
  146. TEXTURE_2D => Dimension::Tex2d,
  147. TEXTURE_3D => Dimension::Tex3d,
  148. _ => return None,
  149. };
  150. let swizzle = match desc.layout {
  151. 0 if dimension == Dimension::Tex1d => Swizzle::LINEAR,
  152. 0 if desc.flags & DEPTH != 0 => Swizzle::SW_64KB_Z_X,
  153. 0 if desc.flags & RENDER_TARGET != 0 => Swizzle::SW_64KB_R_X,
  154. 0 => Swizzle::SW_4KB_S,
  155. 1 => Swizzle::LINEAR,
  156. l if l & !0xff == 0x100 => Swizzle(l & 0xff),
  157. _ => return None,
  158. };
  159. texture::Texture::new(&TextureDesc {
  160. dimension,
  161. width: u32::try_from(desc.width).ok()?,
  162. height: desc.height,
  163. depth_or_array: u32::from(desc.depth_or_array_size),
  164. mips: u32::from(desc.mip_levels),
  165. format: desc.format,
  166. samples: desc.sample_count.max(1),
  167. swizzle,
  168. })
  169. .ok()
  170. }
  171. /// Bytes and alignment a resource takes: buffers their width (64 KiB
  172. /// aligned), textures their console layout (formats it does not know:
  173. /// every mip of every array slice and sample, packed, 64 KiB aligned),
  174. /// rounded up to the alignment.
  175. fn footprint(desc: &ResourceDesc) -> Option<AllocationInfo> {
  176. if desc.dimension != BUFFER
  177. && let Some(t) = texture_layout(desc)
  178. {
  179. // As the console: the layout's own alignment unless more is asked
  180. // (4 KiB for 4 KiB modes, where PC says 64 KiB).
  181. // The title keeps these sizes in its texture tables, and its streaming
  182. // asserts when they disagree with the streamed layout.
  183. let alignment = desc.alignment.max(t.alignment);
  184. if !alignment.is_power_of_two() {
  185. return None;
  186. }
  187. return Some(AllocationInfo {
  188. size: t.size.checked_next_multiple_of(alignment)?,
  189. alignment,
  190. });
  191. }
  192. let bytes = if desc.dimension == BUFFER {
  193. desc.width
  194. } else {
  195. let (element, block) = element(desc.format)?;
  196. let (depth, slices) = if desc.dimension == TEXTURE_3D {
  197. (u64::from(desc.depth_or_array_size), 1)
  198. } else {
  199. (1, u64::from(desc.depth_or_array_size))
  200. };
  201. let height = u64::from(desc.height);
  202. let mips = mip_count(desc);
  203. let mut chain = 0u64;
  204. for mip in 0..mips.min(64) {
  205. let w = (desc.width >> mip).max(1).div_ceil(block);
  206. let h = (height >> mip).max(1).div_ceil(block);
  207. let d = (depth >> mip).max(1);
  208. chain = chain.checked_add(w.checked_mul(h)?.checked_mul(d)?.checked_mul(element)?)?;
  209. }
  210. chain
  211. .checked_mul(slices)?
  212. .checked_mul(u64::from(desc.sample_count.max(1)))?
  213. };
  214. if bytes == 0 {
  215. return None;
  216. }
  217. let minimum = if desc.sample_count > 1 { MIB_4 } else { KIB_64 };
  218. let alignment = desc.alignment.max(minimum);
  219. if !alignment.is_power_of_two() {
  220. return None;
  221. }
  222. Some(AllocationInfo {
  223. size: bytes.checked_next_multiple_of(KIB_64)?,
  224. alignment,
  225. })
  226. }
  227. /// A format as the host has it. The console's 16-bit depth with stencil
  228. /// (and its typeless views) has no PC format: the 24-bit ones stand in.
  229. pub(crate) fn pc_format(format: u32) -> u32 {
  230. match format {
  231. 118 => 45,
  232. 119 => 46,
  233. 120 => 47,
  234. other => other,
  235. }
  236. }
  237. /// The format of a texture the host GPU renders to or writes as unordered
  238. /// access, for the title's `format`. The console's GPU does both with the
  239. /// 16-bit colour formats B5G5R5A1 (86) and B4G4R4A4 (115), and
  240. /// the title has full-screen targets in both; a host that refuses either use
  241. /// (NVIDIA) refused the whole texture, so every pass that wrote it drew
  242. /// nothing. There 8-bit RGBA stands in: the same channels in the same
  243. /// order, every 4-bit level exact and every 5-bit level within 1/510.
  244. /// The title also renders to R9G9B9E5 (67), which no PC GPU does: 16-bit
  245. /// float RGBA stands in, with at least R9G9B9E5's precision and range.
  246. /// The title's pipelines and views of such targets name the stand-in too
  247. /// ([`view_format`], the host view checks).
  248. /// shortcut: copies between such a target and a texture the title fills
  249. /// itself in the 16-bit format are skipped ([`stands_in`]); convert them
  250. /// if a pass turns out to need one.
  251. pub(crate) fn target_format(format: u32) -> u32 {
  252. const STAND_INS: [(u32, u32); 3] = [(86, 28), (115, 28), (67, 10)];
  253. let Some(i) = STAND_INS.iter().position(|&(f, _)| f == format) else {
  254. return format;
  255. };
  256. #[cfg(windows)]
  257. {
  258. use windows::Win32::Graphics::Direct3D12::*;
  259. static REFUSED: std::sync::OnceLock<[bool; 3]> = std::sync::OnceLock::new();
  260. let refused = REFUSED.get_or_init(|| {
  261. STAND_INS.map(|(f, to)| {
  262. let Some(host) = crate::host::host() else {
  263. return false;
  264. };
  265. let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT {
  266. Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(f as i32),
  267. ..Default::default()
  268. };
  269. // SAFETY: a plain query into our own structure.
  270. let asked = unsafe {
  271. host.device.CheckFeatureSupport(
  272. D3D12_FEATURE_FORMAT_SUPPORT,
  273. (&raw mut support).cast(),
  274. size_of_val(&support) as u32,
  275. )
  276. };
  277. let both = D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0
  278. | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0;
  279. let refused = asked.is_err() || support.Support1.0 & both != both;
  280. if refused {
  281. tracing::info!(format = f, stand_in = to, "the host does not render to this format: a stand-in is used");
  282. }
  283. refused
  284. })
  285. });
  286. if refused[i] {
  287. return STAND_INS[i].1;
  288. }
  289. }
  290. format
  291. }
  292. /// Whether the host copy of the title texture `this` is in a stand-in
  293. /// format ([`target_format`]): its texels are not laid out as the title's.
  294. #[cfg(windows)]
  295. pub(crate) fn stands_in(this: This) -> bool {
  296. if this.is_null() {
  297. return false;
  298. }
  299. let own = pc_format(resource(this).desc.format);
  300. target_format(own) != own
  301. && host_resource(this)
  302. // SAFETY: a live resource.
  303. .is_some_and(|host| unsafe { host.GetDesc() }.Format.0 as u32 == target_format(own))
  304. }
  305. /// Depth textures the title also asks unordered access for (the console
  306. /// allows both; the host copy loses the unordered access): how many were
  307. /// made, and how often such a texture was bound as the depth target,
  308. /// cleared as depth, and asked for an unordered access view the host could
  309. /// not give. Measured to decide what such textures need (a colour twin, or
  310. /// to be colour textures altogether).
  311. pub(crate) static DEPTH_UNORDERED: [std::sync::atomic::AtomicU64; 4] =
  312. [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  313. /// Whether the title asked for both depth and unordered access for `this`.
  314. #[cfg(windows)]
  315. pub(crate) fn depth_and_unordered(this: This) -> bool {
  316. !this.is_null() && resource(this).desc.flags & 6 == 6
  317. }
  318. /// The colour twin of a depth texture the title also writes as unordered
  319. /// access. The console allows both on one texture; the host gives a depth
  320. /// texture no unordered access, so shaders write a colour texture of the
  321. /// same size and format family instead, and one is copied into the other
  322. /// when a side is used after the other was written
  323. /// (`HostList::twin_use`).
  324. /// shortcut: whole textures are copied, not the mips and slices written.
  325. /// A depth texture with a stencil plane gets a twin for each plane (
  326. /// the title's tiled lighting writes each pixel's material class into
  327. /// the depth plane and masks into the stencil plane, then draws each class
  328. /// with the depth test "equal"): the stencil plane's is copied through a
  329. /// buffer, the depth plane's is drawn into the plane by a pass of ours
  330. /// (`HostList::pass_plane`). Unordered access views of a multisampled
  331. /// texture stay null.
  332. #[cfg(windows)]
  333. pub(crate) struct Twin {
  334. /// The colour texture and the state it is in, as a host copy's.
  335. pub(crate) colour: std::sync::Arc<HostTexture>,
  336. /// Which side lacks what the other was written last, after the lists
  337. /// submitted so far: bit 0 the depth texture, bit 1 the twin.
  338. pub(crate) behind: std::sync::atomic::AtomicU32,
  339. /// For a depth texture with a stencil plane, `colour` is the twin of
  340. /// that plane (8 bits a texel) and this the buffer the two are copied
  341. /// through: no colour format shares a family with a depth-stencil
  342. /// format, but the host copies between a buffer and one plane.
  343. pub(crate) through: Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource>,
  344. /// For a depth texture with a stencil plane: the twin of its depth
  345. /// plane, 16 bits a texel for the console's 16-bit depth-stencil
  346. /// formats and a 32-bit float otherwise. No host colour format holds
  347. /// the bits of a 24-bit depth plane, so the two are not copied: a pass
  348. /// draws the twin into the plane.
  349. pub(crate) plane: Option<std::sync::Arc<HostTexture>>,
  350. }
  351. #[cfg(windows)]
  352. impl Drop for Twin {
  353. fn drop(&mut self) {
  354. TWINS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
  355. }
  356. }
  357. /// Colour twins alive, depth textures with unordered access left without
  358. /// one, and the copies recorded into depth textures and into twins since
  359. /// the last frame-rate line.
  360. #[cfg(windows)]
  361. pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] =
  362. [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  363. /// Depth planes drawn from their twins by the pass since the last
  364. /// frame-rate line; and since the start, how often a depth plane's twin
  365. /// lacked what was written to the plane (not given to it), and how often a
  366. /// depth plane was used in the list that had written its twin, before the
  367. /// pass (which runs when the list closes).
  368. #[cfg(windows)]
  369. pub(crate) static PLANES: [std::sync::atomic::AtomicU64; 3] =
  370. [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  371. /// The colour twin of title texture `this`, if it has one.
  372. #[cfg(windows)]
  373. pub(crate) fn twin(this: This) -> Option<std::sync::Arc<Twin>> {
  374. if this.is_null() {
  375. return None;
  376. }
  377. hosted(this, true).and_then(|made| made.1)
  378. }
  379. /// The twin's texture, for the unordered access views of `this`.
  380. #[cfg(windows)]
  381. pub(crate) fn twin_resource<'a>(
  382. this: This,
  383. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  384. if this.is_null() {
  385. return None;
  386. }
  387. let (_, twin) = hosted(this, true)?;
  388. // SAFETY: as in `host_resource`: the twin lives as long as the host
  389. // copy, which a depth texture keeps until the title releases it.
  390. twin.map(|t| unsafe { &*std::ptr::from_ref(&t.colour.texture) })
  391. }
  392. /// The texture of the twin of the depth plane of `this`, a depth texture
  393. /// with a stencil plane, for the unordered access views of that plane.
  394. #[cfg(windows)]
  395. pub(crate) fn twin_plane_resource<'a>(
  396. this: This,
  397. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  398. if this.is_null() {
  399. return None;
  400. }
  401. let (_, twin) = hosted(this, true)?;
  402. let twin = twin?;
  403. // SAFETY: as in `twin_resource`.
  404. twin.plane
  405. .as_ref()
  406. .map(|p| unsafe { &*std::ptr::from_ref(&p.texture) })
  407. }
  408. /// The colour twin for a texture described by `desc` whose host copy is
  409. /// `depth`, if the title asks for depth and unordered access both and the
  410. /// host can copy between the two: the same size, mips and slices in the
  411. /// depth format's typeless family (R16 for 16-bit depth, R32 for 32-bit),
  412. /// or R8 for the stencil plane of a format that has one, with unordered
  413. /// access only. A format with a stencil plane gets a twin for its depth
  414. /// plane too, R16 for the console's 16-bit depth-stencil formats and R32
  415. /// otherwise. `VICTORY_DEPTH_TWINS=0` makes none (such views stay null),
  416. /// `VICTORY_DEPTH_TWINS=stencil` only those of formats with a stencil
  417. /// plane, `VICTORY_DEPTH_TWINS=nodepth` none for the depth planes of such
  418. /// formats.
  419. #[cfg(windows)]
  420. fn twin_texture(
  421. desc: &ResourceDesc,
  422. depth: &windows::Win32::Graphics::Direct3D12::ID3D12Resource,
  423. ) -> Option<std::sync::Arc<Twin>> {
  424. use std::sync::atomic::Ordering::Relaxed;
  425. use windows::Win32::Graphics::Direct3D12::*;
  426. const DEPTH_AND_UNORDERED: u32 = 6;
  427. const UNORDERED: u32 = 4;
  428. const UNORDERED_ACCESS: u32 = 0x8;
  429. // R32 and R16 typeless: the families of the depth formats of one plane.
  430. const ONE_PLANE: [u32; 2] = [39, 53];
  431. if desc.dimension == BUFFER || desc.flags & DEPTH_AND_UNORDERED != DEPTH_AND_UNORDERED {
  432. return None;
  433. }
  434. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  435. if !*ON.get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_none_or(|v| v != "0")) {
  436. return None;
  437. }
  438. // R32G8X24 and R24G8 typeless: depth with a stencil plane, whose twin
  439. // is R8 typeless.
  440. const WITH_STENCIL: [u32; 2] = [19, 44];
  441. const R8_TYPELESS: u32 = 60;
  442. let typeless = family(pc_format(desc.format));
  443. let stencil = WITH_STENCIL.contains(&typeless);
  444. static STENCIL_ONLY: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  445. let stencil_only = *STENCIL_ONLY
  446. .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "stencil"));
  447. if !stencil && stencil_only {
  448. return None;
  449. }
  450. if !(stencil || ONE_PLANE.contains(&typeless)) || desc.sample_count > 1 {
  451. TWINS[1].fetch_add(1, Relaxed);
  452. return None;
  453. }
  454. let host = crate::host::host()?;
  455. let mut d = *desc;
  456. d.layout = 0;
  457. d.alignment = 0;
  458. d.flags = UNORDERED;
  459. d.format = if stencil { R8_TYPELESS } else { typeless };
  460. let heap = D3D12_HEAP_PROPERTIES {
  461. Type: D3D12_HEAP_TYPE_DEFAULT,
  462. ..Default::default()
  463. };
  464. let mut texture: Option<ID3D12Resource> = None;
  465. // SAFETY: the description has the host layout, as in `host_texture`;
  466. // the out pointer is ours.
  467. let made = unsafe {
  468. host.device.CreateCommittedResource(
  469. &heap,
  470. crate::host::not_resident(),
  471. (&raw const d).cast(),
  472. D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32),
  473. None,
  474. &mut texture,
  475. )
  476. };
  477. if let Err(e) = made {
  478. tracing::warn!(error = %e, desc = ?d, "no colour twin for a depth texture");
  479. }
  480. let Some(texture) = texture else {
  481. TWINS[1].fetch_add(1, Relaxed);
  482. return None;
  483. };
  484. let _ = crate::host::resident(&host.device, &texture);
  485. crate::host::name(&texture, || {
  486. format!("depth twin {}x{} f{}", d.width, d.height, d.format)
  487. });
  488. // The buffer a stencil plane and its twin are copied through: as big
  489. // as the plane's mips and slices laid out for a copy (they follow the
  490. // depth plane's in the texture's subresources).
  491. let through = if stencil {
  492. // SAFETY: a live texture.
  493. let of = unsafe { depth.GetDesc() };
  494. let planes = u32::from(of.MipLevels) * u32::from(of.DepthOrArraySize);
  495. let mut bytes = 0;
  496. // SAFETY: a plain query; the out pointer is ours.
  497. unsafe {
  498. host.device.GetCopyableFootprints(
  499. &of,
  500. planes,
  501. planes,
  502. 0,
  503. None,
  504. None,
  505. None,
  506. Some(&mut bytes),
  507. );
  508. }
  509. let Some(buffer) = host.uav_buffer(bytes) else {
  510. TWINS[1].fetch_add(1, Relaxed);
  511. return None;
  512. };
  513. Some(buffer)
  514. } else {
  515. None
  516. };
  517. // The twin of the depth plane of a format with a stencil plane: R16
  518. // typeless (53) for the console's 16-bit depth-stencil formats (118 to
  519. // 120), whose shaders write 16-bit steps, R32 typeless (39) otherwise.
  520. static NO_PLANE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  521. let no_plane = *NO_PLANE
  522. .get_or_init(|| std::env::var_os("VICTORY_DEPTH_TWINS").is_some_and(|v| v == "nodepth"));
  523. let plane = if stencil && !no_plane {
  524. d.format = if (118..=120).contains(&desc.format) {
  525. 53
  526. } else {
  527. 39
  528. };
  529. let mut texture: Option<ID3D12Resource> = None;
  530. // SAFETY: as for the first twin.
  531. let made = unsafe {
  532. host.device.CreateCommittedResource(
  533. &heap,
  534. crate::host::not_resident(),
  535. (&raw const d).cast(),
  536. D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32),
  537. None,
  538. &mut texture,
  539. )
  540. };
  541. if let Err(e) = made {
  542. tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane");
  543. }
  544. texture.map(|texture| {
  545. let _ = crate::host::resident(&host.device, &texture);
  546. crate::host::name(&texture, || {
  547. format!("depth plane twin {}x{} f{}", d.width, d.height, d.format)
  548. });
  549. std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS))
  550. })
  551. } else {
  552. None
  553. };
  554. TWINS[0].fetch_add(1, Relaxed);
  555. Some(std::sync::Arc::new(Twin {
  556. colour: std::sync::Arc::new(HostTexture::new(texture, UNORDERED_ACCESS)),
  557. behind: std::sync::atomic::AtomicU32::new(0),
  558. through,
  559. plane,
  560. }))
  561. }
  562. /// The typeless format of a format's family (itself if it has none).
  563. pub(crate) fn family(format: u32) -> u32 {
  564. const FAMILIES: [(u32, u32); 22] = [
  565. (1, 4),
  566. (5, 8),
  567. (9, 14),
  568. (15, 18),
  569. (19, 22),
  570. (23, 25),
  571. (27, 32),
  572. (33, 38),
  573. (39, 43),
  574. (44, 47),
  575. (48, 52),
  576. (53, 59),
  577. (60, 64),
  578. (70, 72),
  579. (73, 75),
  580. (76, 78),
  581. (79, 81),
  582. (82, 84),
  583. (90, 91),
  584. (92, 93),
  585. (94, 96),
  586. (97, 99),
  587. ];
  588. match format {
  589. 87 => 90,
  590. 88 => 92,
  591. f => FAMILIES
  592. .iter()
  593. .find(|&&(first, last)| (first..=last).contains(&f))
  594. .map_or(f, |&(first, _)| first),
  595. }
  596. }
  597. /// sRGB formats and their linear twins.
  598. pub(crate) const SRGB: [(u32, u32); 3] = [(29, 28), (91, 87), (93, 88)];
  599. /// The format a view of a title texture must name when its host copy is
  600. /// typeless (see [`DEPTH_FORMATS`], [`SRGB`]): the title's own; `None` if
  601. /// the host copy is typed.
  602. pub(crate) fn view_format(this: This) -> Option<u32> {
  603. // First: a view of no resource (a typed null view) has none.
  604. let host = host_resource(this)?;
  605. let own = pc_format(resource(this).desc.format);
  606. // SAFETY: a live resource.
  607. let format = unsafe { host.GetDesc() }.Format.0 as u32;
  608. // A stand-in target is typed.
  609. (format != own && format != target_format(own)).then_some(own)
  610. }
  611. /// Depth formats with their typeless family: depth textures that shaders
  612. /// read are made typeless on the host, which only allows views of
  613. /// typeless depth resources.
  614. pub(crate) const DEPTH_FORMATS: [(u32, u32); 4] = [(20, 19), (40, 39), (45, 44), (55, 53)];
  615. /// Mip levels, the full chain for 0.
  616. fn mip_count(desc: &ResourceDesc) -> u32 {
  617. let depth = if desc.dimension == TEXTURE_3D {
  618. u64::from(desc.depth_or_array_size)
  619. } else {
  620. 1
  621. };
  622. match desc.mip_levels {
  623. 0 => {
  624. 64 - desc
  625. .width
  626. .max(u64::from(desc.height))
  627. .max(depth)
  628. .max(1)
  629. .leading_zeros()
  630. }
  631. n => u32::from(n),
  632. }
  633. }
  634. #[repr(C)]
  635. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  636. pub(crate) struct PlacedFootprint {
  637. pub(crate) offset: u64,
  638. format: u32,
  639. width: u32,
  640. height: u32,
  641. depth: u32,
  642. row_pitch: u32,
  643. }
  644. impl PlacedFootprint {
  645. /// The bytes it spans in a buffer: every row pitched but the last.
  646. pub(crate) fn bytes(&self) -> Option<u64> {
  647. let (element, block) = element(self.format)?;
  648. let lines = u64::from(self.height).div_ceil(block) * u64::from(self.depth);
  649. let last = u64::from(self.width).div_ceil(block) * element;
  650. Some(u64::from(self.row_pitch) * lines.saturating_sub(1) + last)
  651. }
  652. /// For a read back through a host buffer: this footprint at offset 0
  653. /// with its rows pitched as the host wants them (multiples of 256
  654. /// bytes), then the bytes that buffer needs, the bytes of a row, the
  655. /// rows, and the title's own pitch.
  656. pub(crate) fn host_rows(&self) -> Option<(PlacedFootprint, [u64; 4])> {
  657. let (element, block) = element(self.format)?;
  658. let lines = (u64::from(self.height).div_ceil(block) * u64::from(self.depth)).max(1);
  659. let row = u64::from(self.width).div_ceil(block) * element;
  660. let pitch = row.max(1).next_multiple_of(256);
  661. let host = PlacedFootprint {
  662. offset: 0,
  663. row_pitch: u32::try_from(pitch).ok()?,
  664. ..*self
  665. };
  666. Some((host, [pitch * lines, row, lines, u64::from(self.row_pitch)]))
  667. }
  668. }
  669. const _: () = assert!(size_of::<PlacedFootprint>() == 32);
  670. const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint {
  671. offset: u64::MAX,
  672. format: 0,
  673. width: 0,
  674. height: 0,
  675. depth: 0,
  676. row_pitch: 0,
  677. };
  678. /// One subresource's upload footprint (offset 0), row count and unpadded row size.
  679. fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> {
  680. const PITCH: u64 = 256;
  681. if desc.dimension == BUFFER {
  682. let footprint = PlacedFootprint {
  683. offset: 0,
  684. format: 0,
  685. width: u32::try_from(desc.width).ok()?,
  686. height: 1,
  687. depth: 1,
  688. row_pitch: u32::try_from(desc.width.next_multiple_of(PITCH)).ok()?,
  689. };
  690. return (index == 0).then_some((footprint, 1, desc.width));
  691. }
  692. let mips = mip_count(desc);
  693. let slices = if desc.dimension == TEXTURE_3D {
  694. 1
  695. } else {
  696. u32::from(desc.depth_or_array_size).max(1)
  697. };
  698. let mip = index % mips;
  699. let plane = index / mips / slices;
  700. let depth_stencil = matches!(desc.format, 19..=22 | 44..=47);
  701. // Each plane contains all the mip levels and array slices. Depth and
  702. // stencil copies use separate formats and 512-byte row alignment.
  703. let (format, pitch_alignment) = match (depth_stencil, plane) {
  704. (true, 0) => (39, 512), // DXGI_FORMAT_R32_TYPELESS
  705. (true, 1) => (60, 512), // DXGI_FORMAT_R8_TYPELESS
  706. (false, 0) => (desc.format, PITCH),
  707. _ => return None,
  708. };
  709. let (element, block) = element(format)?;
  710. let width = (desc.width >> mip).max(1).next_multiple_of(block);
  711. let height = (u64::from(desc.height) >> mip)
  712. .max(1)
  713. .next_multiple_of(block);
  714. let depth = if desc.dimension == TEXTURE_3D {
  715. (u32::from(desc.depth_or_array_size) >> mip).max(1)
  716. } else {
  717. 1
  718. };
  719. let row_size = width / block * element;
  720. let footprint = PlacedFootprint {
  721. offset: 0,
  722. format,
  723. width: u32::try_from(width).ok()?,
  724. height: u32::try_from(height).ok()?,
  725. depth,
  726. row_pitch: u32::try_from(row_size.next_multiple_of(pitch_alignment)).ok()?,
  727. };
  728. Some((footprint, u32::try_from(height / block).ok()?, row_size))
  729. }
  730. /// Places subresources at 512-byte boundaries in an upload buffer.
  731. /// Row pitch is aligned to 512 bytes for depth/stencil planes and 256 bytes
  732. /// otherwise. Unknown sizes give the documented all-ones values.
  733. pub(crate) extern "system" fn copyable_footprints(
  734. _: This,
  735. desc: *const ResourceDesc,
  736. first: u32,
  737. count: u32,
  738. base: u64,
  739. layouts: *mut PlacedFootprint,
  740. rows: *mut u32,
  741. row_sizes: *mut u64,
  742. total: *mut u64,
  743. ) {
  744. const PLACEMENT: u64 = 512;
  745. // SAFETY: the title passes a description (null is tolerated).
  746. let desc = unsafe { desc.as_ref() };
  747. let mut end = base;
  748. let mut known = desc.is_some();
  749. for i in 0..count {
  750. let one = desc.and_then(|d| subresource(d, first + i));
  751. let (layout, row_count, row_size) = match one {
  752. Some((mut footprint, row_count, row_size)) => {
  753. footprint.offset = end.next_multiple_of(PLACEMENT);
  754. let pitch = u64::from(footprint.row_pitch);
  755. let lines = u64::from(row_count) * u64::from(footprint.depth);
  756. end = footprint.offset + pitch * lines.saturating_sub(1) + row_size;
  757. (footprint, row_count, row_size)
  758. }
  759. None => {
  760. known = false;
  761. (NO_FOOTPRINT, u32::MAX, u64::MAX)
  762. }
  763. };
  764. let i = i as usize;
  765. // SAFETY: each output is null or holds `count` entries.
  766. unsafe {
  767. if !layouts.is_null() {
  768. layouts.add(i).write(layout);
  769. }
  770. if !rows.is_null() {
  771. rows.add(i).write(row_count);
  772. }
  773. if !row_sizes.is_null() {
  774. row_sizes.add(i).write(row_size);
  775. }
  776. }
  777. }
  778. if !known {
  779. tracing::warn!(?desc, "no footprint for this resource");
  780. }
  781. if !total.is_null() {
  782. // SAFETY: checked non-null.
  783. unsafe { total.write(if known { end - base } else { u64::MAX }) };
  784. }
  785. }
  786. /// Device method: the footprint of resources placed one after another.
  787. /// Returns a 16-byte value, through a hidden first argument. Invalid input
  788. /// gives the documented size `u64::MAX`.
  789. pub(crate) extern "system" fn allocation_info(
  790. out: *mut AllocationInfo,
  791. _: This,
  792. _visible: u32,
  793. count: u32,
  794. descs: *const ResourceDesc,
  795. ) -> *mut AllocationInfo {
  796. let descs = if descs.is_null() {
  797. &[][..]
  798. } else {
  799. // SAFETY: the title passes `count` descriptions.
  800. unsafe { std::slice::from_raw_parts(descs, count as usize) }
  801. };
  802. // SAFETY: the caller passes room for the value.
  803. unsafe { out.write(place(descs.iter(), |_, _| ())) };
  804. out
  805. }
  806. /// The newer description: the plain one, then a sampler feedback mip
  807. /// region (width, height, depth).
  808. #[repr(C)]
  809. pub(crate) struct ResourceDesc1 {
  810. desc: ResourceDesc,
  811. mip_region: [u32; 3],
  812. }
  813. const _: () = assert!(size_of::<ResourceDesc1>() == 72);
  814. /// Where one resource goes in [`allocation_info2`]'s placement.
  815. #[repr(C)]
  816. pub(crate) struct AllocationInfo1 {
  817. offset: u64,
  818. alignment: u64,
  819. size: u64,
  820. }
  821. /// Device method 0x360 (`ID3D12Device8`): [`allocation_info`] for newer
  822. /// descriptions, also telling where each resource goes.
  823. pub(crate) extern "system" fn allocation_info2(
  824. out: *mut AllocationInfo,
  825. _: This,
  826. _visible: u32,
  827. count: u32,
  828. descs: *const ResourceDesc1,
  829. each: *mut AllocationInfo1,
  830. ) -> *mut AllocationInfo {
  831. let descs = if descs.is_null() {
  832. &[][..]
  833. } else {
  834. // SAFETY: the title passes `count` descriptions.
  835. unsafe { std::slice::from_raw_parts(descs, count as usize) }
  836. };
  837. let total = place(descs.iter().map(|d| &d.desc), |i, info| {
  838. if !each.is_null() {
  839. // SAFETY: the title passes room for `count` entries.
  840. unsafe { each.add(i).write(info) };
  841. }
  842. });
  843. // SAFETY: the caller passes room for the value.
  844. unsafe { out.write(total) };
  845. out
  846. }
  847. /// Resources placed one after another: the whole footprint, telling `each`
  848. /// where every resource goes. Unknown sizes give the documented `u64::MAX`.
  849. fn place<'a>(
  850. descs: impl Iterator<Item = &'a ResourceDesc>,
  851. mut each: impl FnMut(usize, AllocationInfo1),
  852. ) -> AllocationInfo {
  853. let mut total = AllocationInfo {
  854. size: 0,
  855. alignment: KIB_64,
  856. };
  857. for (i, desc) in descs.enumerate() {
  858. let Some(one) = footprint(desc) else {
  859. tracing::warn!(?desc, "no size for this resource");
  860. each(
  861. i,
  862. AllocationInfo1 {
  863. offset: u64::MAX,
  864. alignment: 0,
  865. size: u64::MAX,
  866. },
  867. );
  868. return AllocationInfo {
  869. size: u64::MAX,
  870. alignment: 0,
  871. };
  872. };
  873. tracing::debug!(?desc, ?one, "allocation info");
  874. let offset = total.size.next_multiple_of(one.alignment);
  875. each(
  876. i,
  877. AllocationInfo1 {
  878. offset,
  879. alignment: one.alignment,
  880. size: one.size,
  881. },
  882. );
  883. total.size = offset + one.size;
  884. total.alignment = total.alignment.max(one.alignment);
  885. }
  886. total
  887. }
  888. /// Zeroed host memory standing in for GPU memory.
  889. pub(crate) struct Memory {
  890. ptr: NonNull<u8>,
  891. layout: Layout,
  892. /// Set when the memory came from the title's allocator, with these
  893. /// allocation attributes (it goes back there).
  894. attributes: Option<u64>,
  895. }
  896. pub type AllocRoutine = extern "system" fn(usize, u64) -> *mut c_void;
  897. pub type FreeRoutine = extern "system" fn(*mut c_void, u64);
  898. static ALLOCATOR: std::sync::OnceLock<(AllocRoutine, FreeRoutine)> = std::sync::OnceLock::new();
  899. /// Committed resources get their memory from the title's general
  900. /// allocator, as on the console, where titles hook it to place graphics
  901. /// memory themselves (the title places its back buffers in a
  902. /// block of its own and checks they fill it). The runtime names it before
  903. /// the device exists.
  904. pub fn use_allocator(alloc: AllocRoutine, free: FreeRoutine) {
  905. let _ = ALLOCATOR.set((alloc, free));
  906. }
  907. /// Maps the physical pages behind one range of title memory at another,
  908. /// `(to, from, len)` (`from` 0 unmaps); false on failure.
  909. pub type PageMapper = fn(u64, u64, u64) -> bool;
  910. static PAGE_MAPPER: std::sync::OnceLock<PageMapper> = std::sync::OnceLock::new();
  911. /// The runtime's page mapper, for the queues' page-mapping copies (memory
  912. /// is the runtime's, as on the console).
  913. pub fn use_page_mapper(mapper: PageMapper) {
  914. let _ = PAGE_MAPPER.set(mapper);
  915. }
  916. /// As a [`PageMapper`], many at once: `(to, from, len)` each, in order.
  917. pub type ManyPageMapper = fn(&[(u64, u64, u64)]) -> bool;
  918. static MANY_PAGE_MAPPER: std::sync::OnceLock<ManyPageMapper> = std::sync::OnceLock::new();
  919. /// The runtime's mapper of many pages at once.
  920. pub fn use_many_page_mapper(mapper: ManyPageMapper) {
  921. let _ = MANY_PAGE_MAPPER.set(mapper);
  922. }
  923. pub(crate) fn many_page_mapper() -> Option<ManyPageMapper> {
  924. MANY_PAGE_MAPPER.get().copied()
  925. }
  926. pub(crate) fn page_mapper() -> Option<PageMapper> {
  927. PAGE_MAPPER.get().copied()
  928. }
  929. /// Allocation attributes for resource memory: allocator id, page size
  930. /// (bits 14-15: 2 MiB pages from 2 MiB up, else 64 KiB), alignment as log2
  931. /// (bits 24-28) and memory type (bits 29-32: write-combined for GPU-only
  932. /// heaps, cacheable for the CPU-visible ones).
  933. /// shortcut: the console runtime's own choice of page size and memory type
  934. /// is not known; this is the plausible one.
  935. fn resource_attributes(info: AllocationInfo, heap_kind: u32) -> u64 {
  936. const GRAPHICS_ALLOCATOR: u64 = 128 << 16;
  937. const DEFAULT_HEAP: u32 = 1;
  938. let pages: u64 = if info.size >= 2 << 20 { 2 } else { 1 };
  939. let memory: u64 = if heap_kind == DEFAULT_HEAP { 1 } else { 3 };
  940. let alignment = u64::from(info.alignment.max(1).trailing_zeros());
  941. GRAPHICS_ALLOCATOR | pages << 14 | alignment << 24 | memory << 29
  942. }
  943. impl Memory {
  944. /// A committed resource's memory: from the title's allocator if the
  945. /// runtime named one, else our own; zeroed either way.
  946. fn for_resource(info: AllocationInfo, heap_kind: u32) -> Result<Memory, HRESULT> {
  947. let Some(&(alloc, _)) = ALLOCATOR.get() else {
  948. return Memory::new(info);
  949. };
  950. let layout = Layout::from_size_align(info.size as usize, info.alignment as usize)
  951. .map_err(|_| E_INVALIDARG)?;
  952. let attributes = resource_attributes(info, heap_kind);
  953. let ptr =
  954. NonNull::new(alloc(layout.size(), attributes).cast::<u8>()).ok_or(E_OUTOFMEMORY)?;
  955. // SAFETY: the allocator handed out `size` bytes.
  956. unsafe { ptr.as_ptr().write_bytes(0, layout.size()) };
  957. Ok(Memory {
  958. ptr,
  959. layout,
  960. attributes: Some(attributes),
  961. })
  962. }
  963. /// `size` zeroed bytes aligned to `alignment` (a power of two).
  964. pub(crate) fn zeroed(size: u64, alignment: u64) -> Result<Memory, HRESULT> {
  965. Memory::new(AllocationInfo { size, alignment })
  966. }
  967. pub(crate) fn address(&self) -> u64 {
  968. self.ptr.as_ptr() as u64
  969. }
  970. fn new(info: AllocationInfo) -> Result<Memory, HRESULT> {
  971. let layout = usize::try_from(info.size)
  972. .ok()
  973. .zip(usize::try_from(info.alignment).ok())
  974. .filter(|&(size, _)| size > 0)
  975. .and_then(|(size, align)| Layout::from_size_align(size, align).ok())
  976. .ok_or(E_INVALIDARG)?;
  977. // SAFETY: the size is non-zero.
  978. let ptr = NonNull::new(unsafe { alloc_zeroed(layout) }).ok_or(E_OUTOFMEMORY)?;
  979. // The big ones are named in the log: the memory line counts our own
  980. // allocations by size, and these are the title's memory given out
  981. // of ours (a heap it made through the device, a descriptor heap).
  982. if info.size >= 32 << 20 {
  983. tracing::info!(mb = info.size >> 20, at = ?ptr, "memory for the title from our allocator (a heap or a descriptor heap)");
  984. }
  985. Ok(Memory {
  986. ptr,
  987. layout,
  988. attributes: None,
  989. })
  990. }
  991. }
  992. impl Drop for Memory {
  993. fn drop(&mut self) {
  994. match (self.attributes, ALLOCATOR.get()) {
  995. (Some(attributes), Some(&(_, free))) => free(self.ptr.as_ptr().cast(), attributes),
  996. // SAFETY: allocated in `new` with this layout.
  997. _ => unsafe { dealloc(self.ptr.as_ptr(), self.layout) },
  998. }
  999. }
  1000. }
  1001. #[repr(C)]
  1002. struct Heap {
  1003. object: Object,
  1004. desc: HeapDesc,
  1005. memory: Memory,
  1006. }
  1007. pub(crate) extern "system" fn create_heap(
  1008. _: This,
  1009. desc: *const HeapDesc,
  1010. iid: *const Iid,
  1011. out: *mut This,
  1012. ) -> HRESULT {
  1013. // SAFETY: the title passes a description (null is tolerated).
  1014. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  1015. return E_INVALIDARG;
  1016. };
  1017. tracing::debug!(
  1018. size = desc.size,
  1019. kind = desc.properties.kind,
  1020. flags = format_args!("{:#x}", desc.flags),
  1021. "heap"
  1022. );
  1023. if desc.alignment != 0 && !desc.alignment.is_power_of_two() {
  1024. return E_INVALIDARG;
  1025. }
  1026. let info = AllocationInfo {
  1027. size: desc.size,
  1028. alignment: desc.alignment.max(KIB_64),
  1029. };
  1030. let memory = match Memory::new(info) {
  1031. Ok(memory) => memory,
  1032. Err(hr) => return hr,
  1033. };
  1034. let heap = Box::new(Heap {
  1035. object: Object::new(&HEAP_FUNCTIONS),
  1036. desc,
  1037. memory,
  1038. });
  1039. object::hand_out(HEAP, heap, iid, &HEAP_IIDS, out)
  1040. }
  1041. extern "system" fn heap_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  1042. object::answer(HEAP, iid, object::is(iid, &HEAP_IIDS).then_some(this), out)
  1043. }
  1044. extern "system" fn heap_release(this: This) -> u32 {
  1045. object::release_boxed::<Heap>(this)
  1046. }
  1047. extern "system" fn heap_desc(this: This, out: *mut HeapDesc) {
  1048. if !out.is_null() {
  1049. // SAFETY: `this` is a heap; the title passes room for a description.
  1050. unsafe { out.write((*this.cast::<Heap>()).desc) };
  1051. }
  1052. }
  1053. /// A resource's memory: its own, or a range of a heap it holds a reference
  1054. /// to.
  1055. enum Backing {
  1056. Committed(Memory),
  1057. Placed {
  1058. heap: This,
  1059. offset: u64,
  1060. },
  1061. /// Memory the title mapped itself, at this address.
  1062. Address(*mut u8),
  1063. }
  1064. impl Drop for Backing {
  1065. fn drop(&mut self) {
  1066. if let Backing::Placed { heap, .. } = *self {
  1067. heap_release(heap);
  1068. }
  1069. }
  1070. }
  1071. #[repr(C)]
  1072. struct Resource {
  1073. object: Object,
  1074. desc: ResourceDesc,
  1075. heap: HeapProperties,
  1076. heap_flags: u32,
  1077. backing: Backing,
  1078. /// Textures also live on the host GPU (decision 0007); buffers do not
  1079. /// yet. With, for a depth texture the title also writes as unordered
  1080. /// access, the colour texture shaders write instead ([`Twin`]).
  1081. #[cfg(windows)]
  1082. host: Hosted,
  1083. }
  1084. /// A title texture's host copy and the state it is in. The title's barriers
  1085. /// name console states (looser than the host's), so we transition from this
  1086. /// one. Lists that use the texture hold it until they are reset: the title
  1087. /// may release a resource whose commands it recorded but not yet submitted
  1088. /// (console memory outlives the object; a host texture must outlive the
  1089. /// lists that name it).
  1090. #[cfg(windows)]
  1091. pub(crate) struct HostTexture {
  1092. pub(crate) texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
  1093. pub(crate) state: std::sync::atomic::AtomicU32,
  1094. /// The bytes the host gives it.
  1095. bytes: u64,
  1096. /// Whether its contents come from title memory ([`fills`]): counted in
  1097. /// [`KINDS`] while it lives.
  1098. filled: bool,
  1099. /// Made without memory of its own (`crate::tiles`): the tiles its
  1100. /// levels have been given. Its `bytes` are 0: what it holds of the card
  1101. /// is counted there.
  1102. pub(crate) tiled: Option<crate::tiles::Tiled>,
  1103. /// The title's level its level 0 is ([`held_only`]): larger levels have
  1104. /// no place in it.
  1105. pub(crate) base: u32,
  1106. /// Tells host copies apart that one texture had one after the other.
  1107. pub(crate) serial: u64,
  1108. /// Made in place of one with fewer levels: the slots that show that one
  1109. /// are made again once this one was filled whole.
  1110. pub(crate) grown: std::sync::atomic::AtomicBool,
  1111. /// What the last submitted upload put in it.
  1112. pub(crate) holds: std::sync::Arc<Holds>,
  1113. /// Who makes its first upload (`crate::texture::ahead`).
  1114. pub(crate) ahead: std::sync::atomic::AtomicU8,
  1115. /// The texture's flags (asked once: the runtime takes 100 ns to say, and
  1116. /// every texture of every draw is asked about).
  1117. flags: u32,
  1118. }
  1119. /// What a host copy was filled with last: the first level of it and the
  1120. /// hash of the title memory it was read from.
  1121. #[cfg(windows)]
  1122. pub(crate) type Holds = std::sync::Mutex<Option<(u32, crate::texture::Digest)>>;
  1123. /// [`HostTexture::serial`] of the last one made.
  1124. #[cfg(windows)]
  1125. static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1126. /// What a title texture has on the host: its host copy and, for a depth
  1127. /// texture shaders also write, the colour twin.
  1128. #[cfg(windows)]
  1129. type Made = (std::sync::Arc<HostTexture>, Option<std::sync::Arc<Twin>>);
  1130. /// A title texture's host side. The host copy is made when something first
  1131. /// uses the texture, not when the title creates it: the title
  1132. /// had created 3,871 textures (9.2 GB on the host) before its world's first
  1133. /// frame, of which a frame's lists name some hundreds (run 23), on a card
  1134. /// with 12 GB. A title texture is memory the title has either way; its host
  1135. /// copy is the card's.
  1136. #[cfg(windows)]
  1137. struct Hosted {
  1138. /// The host copy (and twin) once made. Taken out again only by
  1139. /// [`let_go_idle`] and when the title releases the resource.
  1140. made: std::sync::Mutex<Option<Made>>,
  1141. /// The state and clear value the title created the texture with.
  1142. state: u32,
  1143. clear: Option<[u32; 5]>,
  1144. /// When the host copy was last asked for (`crate::host::moment`),
  1145. /// written under `made`'s lock.
  1146. used: std::sync::atomic::AtomicU64,
  1147. /// The host refused to make it: not tried again.
  1148. refused: std::sync::atomic::AtomicBool,
  1149. /// Its host copy was let go as idle once.
  1150. gone: std::sync::atomic::AtomicBool,
  1151. /// A texture of [`PLACED_TEXTURES`].
  1152. placed: std::sync::atomic::AtomicBool,
  1153. /// The lowest level a view asked for since it had no host copy
  1154. /// ([`want_level`]; `u32::MAX`: none said).
  1155. wanted: std::sync::atomic::AtomicU32,
  1156. /// The next host copy takes the place of one with fewer levels.
  1157. grown: std::sync::atomic::AtomicBool,
  1158. }
  1159. /// Whether a texture the title places in memory is read, kept and uploaded
  1160. /// from the first level its views show on (`VICTORY_HELD_LEVELS=0`: whole,
  1161. /// as before). Such a title describes every level of a texture and views it
  1162. /// from the first one it holds; the memory of the larger ones is the next
  1163. /// texture's, or nothing. Of two recorded world frames the levels some slot
  1164. /// shows are 1.2 and 1.6 GB of the 6.3 and 6.7 GB of such host copies, and
  1165. /// most of what was found "changed" and uploaded again was other textures'
  1166. /// bytes.
  1167. #[cfg(windows)]
  1168. pub(crate) fn held_only() -> bool {
  1169. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1170. *ON.get_or_init(|| {
  1171. std::env::var_os("VICTORY_HELD_LEVELS").is_none_or(|v| v != "0") && !crate::tiles::wanted()
  1172. })
  1173. }
  1174. /// The first level a placed texture's view shows: of views of one 2D
  1175. /// texture (the others show whole textures). After victory-amd 4436f8f1.
  1176. pub(crate) fn first_mip(view: &[u32]) -> u32 {
  1177. const TEXTURE_2D_VIEW: u32 = 4;
  1178. match *view {
  1179. [_, TEXTURE_2D_VIEW, _, _, first, ..] => first.min(15),
  1180. _ => 0,
  1181. }
  1182. }
  1183. /// The level from which on a texture of layout `layout` is read for a view
  1184. /// that starts at `first`: the smallest levels share a block and are read
  1185. /// together; 0 where the larger ones lie between the smaller ones.
  1186. pub(crate) fn read_from(layout: &victory_formats::texture::Layout, first: u32) -> u32 {
  1187. if layout.slices != 1 || layout.mips.is_empty() {
  1188. return 0;
  1189. }
  1190. let first = first.min(layout.first_tail_mip).min(layout.mips.len() as u32 - 1);
  1191. if layout.bytes_from(first) < layout.size { first } else { 0 }
  1192. }
  1193. /// The level a host copy begins at for views that start at `first`: one the
  1194. /// host can have as a texture's level 0 ([`read_from`]; block-compressed
  1195. /// formats in whole blocks).
  1196. #[cfg(windows)]
  1197. fn base_level(desc: &ResourceDesc, first: u32) -> u32 {
  1198. const TEXTURE_2D: u32 = 3;
  1199. if first == 0
  1200. || !fills(desc)
  1201. || desc.dimension != TEXTURE_2D
  1202. || desc.depth_or_array_size != 1
  1203. || desc.mip_levels <= 1
  1204. || desc.sample_count > 1
  1205. {
  1206. return 0;
  1207. }
  1208. let Some(t) = texture_layout(desc).filter(|t| t.planes.len() == 1) else {
  1209. return 0;
  1210. };
  1211. let layout = &t.planes[0].layout;
  1212. if layout.desc.swizzle.xor() {
  1213. return 0;
  1214. }
  1215. let block = u64::from(layout.desc.block.max(1));
  1216. let mut base = read_from(layout, first).min(u32::from(desc.mip_levels) - 1);
  1217. let whole = |side: u64| side != 0 && side.is_multiple_of(block);
  1218. while base > 0 && !(whole(desc.width >> base) && whole(u64::from(desc.height) >> base)) {
  1219. base -= 1;
  1220. }
  1221. base
  1222. }
  1223. /// The bytes of title memory a placed texture with the resource description
  1224. /// `desc` is read from for a view that starts at level `first`; `None` as
  1225. /// [`placed_bytes`]. Remembered: asked for every slot that is looked at.
  1226. #[cfg(windows)]
  1227. pub(crate) fn placed_bytes_from(desc: &[u32; 14], first: u32) -> Option<u64> {
  1228. if first == 0 || !held_only() {
  1229. return placed_bytes(desc);
  1230. }
  1231. type Known = std::collections::HashMap<([u32; 14], u32), Option<u64>>;
  1232. thread_local! {
  1233. static KNOWN: std::cell::RefCell<Known> = std::cell::RefCell::default();
  1234. }
  1235. KNOWN.with(|known| {
  1236. *known.borrow_mut().entry((*desc, first)).or_insert_with(|| {
  1237. let whole = placed_bytes(desc)?;
  1238. // SAFETY: 56 bytes in the description's layout.
  1239. let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
  1240. let Some(t) = texture_layout(&d).filter(|t| t.planes.len() == 1) else {
  1241. return Some(whole);
  1242. };
  1243. let layout = &t.planes[0].layout;
  1244. Some(layout.bytes_from(read_from(layout, first)).min(whole))
  1245. })
  1246. })
  1247. }
  1248. /// Host copies replaced by ones with more levels, for as long as a thread
  1249. /// that asked for one may still be about to record its use
  1250. /// ([`host_resource`]): when, and the copy.
  1251. #[cfg(windows)]
  1252. static REPLACED: std::sync::Mutex<Vec<(u64, Made)>> = std::sync::Mutex::new(Vec::new());
  1253. /// Since the start: host copies made with a first level other than the
  1254. /// title's, and their bytes; host copies replaced by one with more levels;
  1255. /// bytes of title memory such copies' textures take whole.
  1256. #[cfg(windows)]
  1257. pub(crate) static HELD: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  1258. /// A view of the placed texture `this` that starts at level `first` is made
  1259. /// or brought up to date: a host copy without that level is replaced by one
  1260. /// with it (made and filled at the next use; the slots that show the old
  1261. /// one go on showing it until that is done).
  1262. #[cfg(windows)]
  1263. pub(crate) fn want_level(this: This, first: u32) {
  1264. use std::sync::atomic::Ordering::Relaxed;
  1265. if this.is_null() || !held_only() {
  1266. return;
  1267. }
  1268. let r = resource(this);
  1269. if r.desc.dimension == BUFFER || !r.host.placed.load(Relaxed) {
  1270. return;
  1271. }
  1272. let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1273. let Some((host, _)) = made.as_ref() else {
  1274. r.host.wanted.fetch_min(first, Relaxed);
  1275. return;
  1276. };
  1277. if host.base == 0 || host.base <= base_level(&r.desc, first) {
  1278. return;
  1279. }
  1280. r.host.wanted.store(first, Relaxed);
  1281. // Under the lock, as in `let_go_idle`.
  1282. crate::texture::unstage(this);
  1283. r.host.grown.store(true, Relaxed);
  1284. HELD[2].fetch_add(1, Relaxed);
  1285. if let Some(old) = made.take() {
  1286. REPLACED.lock().unwrap_or_else(|e| e.into_inner()).push((crate::host::moment(), old));
  1287. }
  1288. }
  1289. /// Counts for the memory line: host copies of textures the title fills
  1290. /// alive and their bytes; such copies let go as idle since the start and
  1291. /// their bytes; made again after that and their bytes; and host copies made
  1292. /// since the start.
  1293. #[cfg(windows)]
  1294. pub(crate) static KINDS: [std::sync::atomic::AtomicU64; 7] =
  1295. [const { std::sync::atomic::AtomicU64::new(0) }; 7];
  1296. /// Every title texture alive (not buffers), by address: for the sweep and
  1297. /// the memory line. A texture leaves the table before it is freed.
  1298. #[cfg(windows)]
  1299. static TEXTURES: std::sync::Mutex<std::collections::BTreeSet<usize>> =
  1300. std::sync::Mutex::new(std::collections::BTreeSet::new());
  1301. #[cfg(windows)]
  1302. fn textures() -> std::sync::MutexGuard<'static, std::collections::BTreeSet<usize>> {
  1303. TEXTURES.lock().unwrap_or_else(|e| e.into_inner())
  1304. }
  1305. /// The title textures the host renders to or writes (targets, depth,
  1306. /// unordered access), by the address of their memory: what a view the
  1307. /// title places in that memory in another format shows ([`alias_of`]). A
  1308. /// texture leaves the table before it is freed.
  1309. #[cfg(windows)]
  1310. static TARGETS_AT: std::sync::Mutex<std::collections::BTreeMap<u64, usize>> =
  1311. std::sync::Mutex::new(std::collections::BTreeMap::new());
  1312. /// For `this`, a texture made for a view the title placed in memory
  1313. /// ([`texture_at`]): the title texture the host writes that lies in the
  1314. /// same memory, if there is one of the same size, levels and layers with
  1315. /// texels of the same width. The console reads such a texture through the
  1316. /// view as it is
  1317. /// (the title packs light as R9G9B9E5 into R32_UINT textures
  1318. /// with compute shaders, which cannot write R9G9B9E5, and samples them
  1319. /// through R9G9B9E5 views placed at the textures' addresses: the sky, the
  1320. /// sky and light probes, the bounced light the lighting pass adds). On the
  1321. /// host the two are two textures and what the shaders wrote exists in one
  1322. /// of them only: the other was filled from title memory, which nothing
  1323. /// writes, so everything read through such a view was black.
  1324. /// Textures of several levels or layers count too (the screen probes'
  1325. /// light atlas has four levels, the camera's sky light cache six layers,
  1326. /// the cloud and sky tables are volumes): only textures of one level and
  1327. /// one layer were found at first, and the programs behind the others read
  1328. /// the title's unwritten memory - the sky light cache's second stage wrote
  1329. /// all zeros from a first stage that held light (run 88).
  1330. /// `VICTORY_ALIAS_COPY=0`: none is found, as before; `=1`: only textures
  1331. /// of one level and one layer, as at first.
  1332. #[cfg(windows)]
  1333. pub(crate) fn alias_of(this: This) -> Option<This> {
  1334. use std::sync::atomic::Ordering::Relaxed;
  1335. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1336. if this.is_null()
  1337. || !*ON.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "0"))
  1338. {
  1339. return None;
  1340. }
  1341. static WHOLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1342. let whole =
  1343. *WHOLE.get_or_init(|| std::env::var_os("VICTORY_ALIAS_COPY").is_none_or(|v| v != "1"));
  1344. let r = resource(this);
  1345. // A level count of 0 asks for a full chain: not counted here.
  1346. let one = |d: &ResourceDesc| {
  1347. d.dimension != BUFFER
  1348. && d.mip_levels >= 1
  1349. && d.depth_or_array_size >= 1
  1350. && (whole || (d.mip_levels == 1 && d.depth_or_array_size == 1))
  1351. && d.sample_count <= 1
  1352. };
  1353. if !r.host.placed.load(Relaxed) || !fills(&r.desc) || !one(&r.desc) {
  1354. return None;
  1355. }
  1356. // Under the table's lock: a texture leaves it before it is freed.
  1357. let targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner());
  1358. let other = *targets.get(&(r.data() as u64))? as This;
  1359. let o = resource(other);
  1360. const DEPTH: u32 = 0x2;
  1361. let same = one(&o.desc)
  1362. && o.desc.dimension == r.desc.dimension
  1363. && o.desc.width == r.desc.width
  1364. && o.desc.height == r.desc.height
  1365. && o.desc.mip_levels == r.desc.mip_levels
  1366. && o.desc.depth_or_array_size == r.desc.depth_or_array_size
  1367. && o.desc.flags & DEPTH == 0
  1368. && target_format(o.desc.format) == o.desc.format
  1369. && element(o.desc.format).is_some_and(|e| e.1 == 1 && Some(e) == element(r.desc.format));
  1370. if !same && r.desc.sample_count <= 1 {
  1371. // What shaders wrote there is on the card in the other texture; this
  1372. // one is filled from title memory, which they never reached. Each
  1373. // kind of pair is said once.
  1374. static SAID: std::sync::Mutex<std::collections::BTreeSet<[u32; 6]>> =
  1375. std::sync::Mutex::new(std::collections::BTreeSet::new());
  1376. let pair = [
  1377. r.desc.width as u32,
  1378. r.desc.height,
  1379. r.desc.format,
  1380. o.desc.width as u32,
  1381. o.desc.height,
  1382. o.desc.format,
  1383. ];
  1384. let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
  1385. if said.len() < 64 && said.insert(pair) {
  1386. tracing::warn!(
  1387. view = ?this,
  1388. texture = ?other,
  1389. "a placed texture lies where a texture the host writes does, and is not like it (width, height, format of each): {pair:?}, levels {} and {}, layers {} and {}",
  1390. r.desc.mip_levels, o.desc.mip_levels, r.desc.depth_or_array_size, o.desc.depth_or_array_size
  1391. );
  1392. }
  1393. }
  1394. same.then_some(other)
  1395. }
  1396. /// Whether host copies are made on first use. On by default;
  1397. /// `VICTORY_LAZY_TEXTURES=0` makes each when the title creates its texture,
  1398. /// as before.
  1399. #[cfg(windows)]
  1400. fn lazy() -> bool {
  1401. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1402. *ON.get_or_init(|| std::env::var_os("VICTORY_LAZY_TEXTURES").is_none_or(|v| v != "0"))
  1403. }
  1404. /// Whether a texture described by `desc` takes its contents from title
  1405. /// memory: one the host neither renders to nor writes (no target, depth or
  1406. /// unordered access flag). Its host copy can be made again from that
  1407. /// memory; any other texture's contents exist on the host alone.
  1408. #[cfg(windows)]
  1409. fn fills(desc: &ResourceDesc) -> bool {
  1410. const TARGET_DEPTH_UNORDERED: u32 = 0x7;
  1411. desc.dimension != BUFFER && desc.flags & TARGET_DEPTH_UNORDERED == 0
  1412. }
  1413. /// Whether the title fills texture `this` itself ([`fills`]).
  1414. #[cfg(windows)]
  1415. pub(crate) fn title_fills(this: This) -> bool {
  1416. !this.is_null() && fills(&resource(this).desc)
  1417. }
  1418. /// Whether `this` is a texture whose host copy is not made yet (and may
  1419. /// still be): a descriptor slot written with a view of it waits
  1420. /// (`crate::descriptor::make_waiting`).
  1421. #[cfg(windows)]
  1422. pub(crate) fn host_waits(this: This) -> bool {
  1423. if this.is_null() || !lazy() {
  1424. return false;
  1425. }
  1426. let r = resource(this);
  1427. r.desc.dimension != BUFFER
  1428. && !r.host.refused.load(std::sync::atomic::Ordering::Relaxed)
  1429. && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none()
  1430. }
  1431. /// The host side of title texture `this`: made now if it is not there and
  1432. /// `make` says so. `None` for buffers and for textures the host refuses.
  1433. #[cfg(windows)]
  1434. fn hosted(this: This, make: bool) -> Option<Made> {
  1435. use std::sync::atomic::Ordering::Relaxed;
  1436. let r = resource(this);
  1437. if r.desc.dimension == BUFFER {
  1438. return None;
  1439. }
  1440. let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1441. if made.is_none() {
  1442. if !make || r.host.refused.load(Relaxed) {
  1443. return None;
  1444. }
  1445. let clear = r
  1446. .host
  1447. .clear
  1448. .as_ref()
  1449. .map_or(std::ptr::null(), |c| std::ptr::from_ref(c).cast::<c_void>());
  1450. // Levels on demand (`crate::tiles`): a texture the title places in
  1451. // memory and fills, of a megabyte or more, that does not hold all
  1452. // its levels now, is made without memory and given it level by
  1453. // level. It does not hold them all if its memory is not all
  1454. // mapped, if the next texture starts inside its span, or if a
  1455. // view of it starts below level 0. Every other texture, and this
  1456. // one if the card will not have it so, is made as before.
  1457. const TEXTURE_2D: u32 = 3;
  1458. let mut tiled = None;
  1459. let mut texture = None;
  1460. let shape_fits = fills(&r.desc)
  1461. && r.desc.dimension == TEXTURE_2D
  1462. && r.desc.depth_or_array_size == 1
  1463. && r.desc.mip_levels > 1
  1464. && r.desc.sample_count <= 1;
  1465. if shape_fits && r.host.placed.load(Relaxed) && crate::tiles::wanted() {
  1466. let bytes = footprint(&r.desc).map_or(0, |f| f.size);
  1467. let start = r.data() as u64;
  1468. // What the upload can read: a console layout, no XOR mode
  1469. // (`crate::texture` `staging`).
  1470. let readable = texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor());
  1471. let partly = readable
  1472. && bytes >= crate::tiles::floor()
  1473. && (!crate::texture::committed(r.data().cast_const(), bytes as usize)
  1474. || crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some()
  1475. || crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0));
  1476. let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None };
  1477. let cut = reserved
  1478. .as_ref()
  1479. .zip(crate::host::host())
  1480. .and_then(|(t, host)| crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels)));
  1481. // (Both or neither: a reserved texture the card will not cut
  1482. // into tiles is dropped here, and the old kind is made below.)
  1483. if cut.is_some() {
  1484. tiled = cut;
  1485. texture = reserved;
  1486. }
  1487. }
  1488. // The levels views show ([`held_only`]), those of the slots shaders
  1489. // pick by index among them.
  1490. let mut base = 0;
  1491. if shape_fits && r.host.placed.load(Relaxed) && held_only() && alias_of(this).is_none() {
  1492. let wanted = r.host.wanted.load(Relaxed);
  1493. let viewed = crate::descriptor::host::first_viewed(r.data() as u64).unwrap_or(u32::MAX);
  1494. let first = wanted.min(viewed);
  1495. if first != u32::MAX {
  1496. base = base_level(&r.desc, first);
  1497. }
  1498. }
  1499. let texture = match texture {
  1500. Some(texture) => Some(texture),
  1501. None => host_texture(&r.desc.from_level(base), r.host.state, clear),
  1502. };
  1503. let Some(texture) = texture else {
  1504. r.host.refused.store(true, Relaxed);
  1505. return None;
  1506. };
  1507. let twin = twin_texture(&r.desc, &texture);
  1508. // One line per depth texture with unordered access: its address is
  1509. // the one target dumps and the captured frame's list of commands
  1510. // name.
  1511. if r.desc.flags & 6 == 6 {
  1512. tracing::info!(
  1513. resource = ?this,
  1514. desc = ?r.desc,
  1515. twin = twin.is_some(),
  1516. "depth texture with unordered access"
  1517. );
  1518. }
  1519. let state = crate::host::legal_state(&texture, crate::host::texture_state(r.host.state));
  1520. let mut host = match tiled {
  1521. Some(tiled) => HostTexture::new_tiled(texture, state, tiled),
  1522. None => HostTexture::new(texture, state),
  1523. };
  1524. host.base = base;
  1525. host.grown.store(r.host.grown.swap(false, Relaxed), Relaxed);
  1526. if base > 0 {
  1527. HELD[0].fetch_add(1, Relaxed);
  1528. HELD[1].fetch_add(host.bytes, Relaxed);
  1529. HELD[3].fetch_add(footprint(&r.desc).map_or(0, |f| f.size), Relaxed);
  1530. }
  1531. host.filled = fills(&r.desc);
  1532. if host.filled {
  1533. KINDS[0].fetch_add(1, Relaxed);
  1534. KINDS[1].fetch_add(host.bytes, Relaxed);
  1535. }
  1536. if r.host.gone.load(Relaxed) {
  1537. KINDS[4].fetch_add(1, Relaxed);
  1538. KINDS[5].fetch_add(host.bytes, Relaxed);
  1539. }
  1540. KINDS[6].fetch_add(1, Relaxed);
  1541. *made = Some((std::sync::Arc::new(host), twin));
  1542. // Slots the title wrote with views of it while it had no host copy
  1543. // are made before the next submission runs.
  1544. crate::descriptor::texture_made(this as usize);
  1545. }
  1546. let now = crate::host::moment();
  1547. if r.host.used.load(Relaxed) != now {
  1548. r.host.used.store(now, Relaxed);
  1549. }
  1550. made.clone()
  1551. }
  1552. /// The host copy of title texture `this` if it is made, without making it
  1553. /// (for diagnostics, which must not count as a use).
  1554. #[cfg(all(windows, feature = "diagnostics"))]
  1555. pub(crate) fn host_made<'a>(
  1556. this: This,
  1557. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  1558. if this.is_null() {
  1559. return None;
  1560. }
  1561. let (host, _) = hosted(this, false)?;
  1562. // SAFETY: as in `host_resource`.
  1563. Some(unsafe { &*std::ptr::from_ref(&host.texture) })
  1564. }
  1565. /// Unconditional host-texture floor for a given local VRAM budget (`None` when
  1566. /// the adapter does not report one): up to 2 GiB, capped at a quarter of the
  1567. /// reported budget so 4–6 GiB cards do not bypass the budget check early.
  1568. #[cfg(any(windows, test))]
  1569. fn texture_floor_bytes(vram_budget: Option<u64>) -> u64 {
  1570. const MAX_FLOOR: u64 = 2 << 30;
  1571. match vram_budget {
  1572. Some(budget) => MAX_FLOOR.min(budget / 4),
  1573. None => MAX_FLOOR,
  1574. }
  1575. }
  1576. /// Whether more host copies of textures the title fills may be made for
  1577. /// shaders that pick textures by index (`draw.rs` `heap_textures`): always
  1578. /// up to [`texture_floor_bytes`] bytes of them, beyond that while the card's
  1579. /// memory in use by this process is under nine tenths of the budget the system
  1580. /// gives it ([`room_percent`] says another share; `VICTORY_TEXTURE_BUDGET_MB`
  1581. /// sets a limit on those copies' bytes instead). Past the budget the system moves the card's memory into the PC's,
  1582. /// which ended runs 20 and 24.
  1583. #[cfg(windows)]
  1584. pub(crate) fn room(memory: Option<[u64; 4]>) -> bool {
  1585. use std::sync::atomic::Ordering::Relaxed;
  1586. const WITHOUT_BUDGET: u64 = 4 << 30;
  1587. static LIMIT: std::sync::OnceLock<Option<u64>> = std::sync::OnceLock::new();
  1588. let limit = *LIMIT.get_or_init(|| {
  1589. let mb = std::env::var("VICTORY_TEXTURE_BUDGET_MB").ok()?;
  1590. mb.trim().parse::<u64>().ok().map(|mb| mb << 20)
  1591. });
  1592. // (With the tiles of the copies made level by level, whose own bytes
  1593. // count as none: `crate::tiles`.)
  1594. let filled = KINDS[1].load(Relaxed) + crate::tiles::given_total();
  1595. if let Some(limit) = limit {
  1596. return filled < limit;
  1597. }
  1598. let floor = texture_floor_bytes(memory.map(|[budget, ..]| budget));
  1599. if filled < floor {
  1600. return true;
  1601. }
  1602. match memory {
  1603. // What is kept for card copies of title buffers not made yet
  1604. // (`crate::shadow::card_room_kept`) and for the render targets a
  1605. // world makes in its first frame ([`targets_room_kept`]) counts as
  1606. // used.
  1607. Some([budget, used, ..]) => {
  1608. used.saturating_sub(crate::pool::texture_room()) + crate::shadow::card_room_kept() + targets_room_kept()
  1609. < budget / 100 * room_percent()
  1610. }
  1611. None => filled < WITHOUT_BUDGET,
  1612. }
  1613. }
  1614. /// The bytes of the card's memory the texture queue leaves free for
  1615. /// render targets and other host copies the host itself writes that are
  1616. /// not made yet: `VICTORY_CARD_ROOM_FOR_TARGETS_MB` (3,072; 0: none, as
  1617. /// before) less what such copies hold now.
  1618. ///
  1619. /// Measured (runs 193, 197, 198): 652 MB of them before the world, 2,255
  1620. /// to 2,352 MB right after its first frame, 2,800 to 3,100 MB two minutes
  1621. /// on, none of them idle (run 198's census). They are made with no room
  1622. /// test, in the same frame as the card copies of title buffers (762 MB),
  1623. /// after the texture queue has filled the card to its line with textures
  1624. /// written while the world loaded (7.3 GB of them at the first world frame
  1625. /// of run 193, of which 2.3 GB were let go again within 13 seconds). The
  1626. /// card then stood at 99 to 100.5 % of its budget, buffer copies were
  1627. /// turned down for good (31 of 95 made: the frame 355 ms where 95 give
  1628. /// 238), and the queue was refused from the first world frame on. With
  1629. /// their room kept, the queue stops that much earlier while the world
  1630. /// loads and gets it back as the targets are made.
  1631. #[cfg(windows)]
  1632. pub(crate) fn targets_room_kept() -> u64 {
  1633. use std::sync::atomic::Ordering::Relaxed;
  1634. static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1635. let most = *MOST.get_or_init(|| {
  1636. std::env::var("VICTORY_CARD_ROOM_FOR_TARGETS_MB")
  1637. .ok()
  1638. .and_then(|v| v.trim().parse::<u64>().ok())
  1639. .map_or(3072 << 20, |mb| mb.min(8192) << 20)
  1640. });
  1641. // Every host texture's bytes less those of the copies the title fills.
  1642. let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed));
  1643. most.saturating_sub(targets)
  1644. }
  1645. /// [`room`] as it was at most a tenth of a second ago, for a question
  1646. /// asked of many textures a frame ([`room`] asks the system each time).
  1647. #[cfg(windows)]
  1648. pub(crate) fn room_lately() -> bool {
  1649. use std::sync::atomic::Ordering::Relaxed;
  1650. // The tenth of a second of the last asking, counted from 1, and its
  1651. // answer in the lowest bit.
  1652. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1653. let tenth = crate::host::now_ms() / 100 + 1;
  1654. let last = LAST.load(Relaxed);
  1655. if last >> 1 == tenth {
  1656. return last & 1 != 0;
  1657. }
  1658. let room = room(crate::host::host().and_then(|h| h.video_memory()));
  1659. LAST.store((tenth << 1) | u64::from(room), Relaxed);
  1660. room
  1661. }
  1662. /// The share of the card's budget, in percent, up to which host copies of
  1663. /// textures picked by index are made ([`room`]): 90 unless
  1664. /// `VICTORY_TEXTURE_ROOM_PERCENT` says another (50 to 97). At 90 about a
  1665. /// tenth of the budget, 1,020 MB of 10,200, stays unused while thousands of
  1666. /// textures wait (runs 170-174); the card copies of title buffers from
  1667. /// 1 MiB up take 449 MB more of the card than before (941 against 492),
  1668. /// and 94 gives the textures about that much back.
  1669. #[cfg(windows)]
  1670. fn room_percent() -> u64 {
  1671. static PERCENT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  1672. *PERCENT.get_or_init(|| {
  1673. std::env::var("VICTORY_TEXTURE_ROOM_PERCENT")
  1674. .ok()
  1675. .and_then(|v| v.trim().parse::<u64>().ok())
  1676. .map_or(90, |percent| percent.clamp(50, 97))
  1677. })
  1678. }
  1679. /// For the card accounting line ([`card_accounting`]): the title texture
  1680. /// made for a view of memory at `address` with the resource description
  1681. /// `desc`, if there is one ([`texture_at`] makes it; this does not).
  1682. #[cfg(windows)]
  1683. pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option<This> {
  1684. // Without the filler words and with them: whichever `texture_at` keeps.
  1685. let mut key = *desc;
  1686. key[1] = 0;
  1687. key[13] = 0;
  1688. let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
  1689. map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This)
  1690. }
  1691. /// For the card accounting line: whether title texture `this` has a host
  1692. /// copy now (2), had one that was let go and not made again (1), or never
  1693. /// had one (0); the bytes (its host copy's on the card, or without one
  1694. /// what its console layout takes in title memory); and where its title
  1695. /// memory is. `None` for buffers. Not a use of the texture.
  1696. #[cfg(windows)]
  1697. pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> {
  1698. use std::sync::atomic::Ordering::Relaxed;
  1699. if this.is_null() {
  1700. return None;
  1701. }
  1702. let r = resource(this);
  1703. if r.desc.dimension == BUFFER {
  1704. return None;
  1705. }
  1706. let memory = r.data() as u64;
  1707. let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1708. Some(match made.as_ref() {
  1709. Some((host, _)) => (2, host.bytes, memory),
  1710. None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory),
  1711. })
  1712. }
  1713. /// One line of where the card's memory is and what the queue of textures
  1714. /// picked by index would need (`VICTORY_CARD_ACCOUNTING=1`; `draw.rs`
  1715. /// `card_accounting` says when, and hands over the queue's side: `room`
  1716. /// as the pass found it, `due` its counts, `never` and `gone` the memory
  1717. /// of the due textures without a host copy). The line holds
  1718. /// - the host copies of textures the title fills that are alive: how
  1719. /// many, their bytes, and the bytes of the levels whose title memory is
  1720. /// not mapped (a host copy is made with every level of the description;
  1721. /// a texture streaming in has its small levels only). A copy's bytes
  1722. /// are shared out to its levels by their texels, so that part is an
  1723. /// estimate;
  1724. /// - the due slots: how many, and their textures by what they have on
  1725. /// the card (a host copy alive: no card memory needed; never one; one
  1726. /// that was let go), with the bytes the last two would need and how
  1727. /// much of their memory is mapped now;
  1728. /// - the host copies let go, made again and made since the line before.
  1729. ///
  1730. /// The textures are noted under the table's lock (their memory, their
  1731. /// description, their copy's bytes: about a millisecond for 18,000) and
  1732. /// the kernel is asked about their memory on a thread of its own, after
  1733. /// the lock is given back: one question for a texture that is all there
  1734. /// (up to 256 pages each; 18,000 textures of 5.5 GB are 1.4 million
  1735. /// pages, some 20,000 questions), one per level and array slice more for
  1736. /// one that is not. Not measured: a tenth to half a second is expected,
  1737. /// and the line says what it took. No line is begun while one is walking.
  1738. #[cfg(windows)]
  1739. pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) {
  1740. use std::sync::atomic::Ordering::Relaxed;
  1741. static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
  1742. // Host copies let go and their bytes, made again and their bytes, and
  1743. // made in all, at the line before.
  1744. static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
  1745. if WALKING.swap(true, Relaxed) {
  1746. return;
  1747. }
  1748. let began = std::time::Instant::now();
  1749. // (The last: made level by level, its bytes are those of its tiles.)
  1750. let mut copies: Vec<(usize, ResourceDesc, u64, bool)> = Vec::new();
  1751. // Textures the title fills without a host copy: never one, one let go.
  1752. let mut without = [0u64; 2];
  1753. {
  1754. let all = textures();
  1755. for &at in all.iter() {
  1756. // SAFETY: as in `let_go_idle`.
  1757. let r = unsafe { &*(at as *const Resource) };
  1758. if !fills(&r.desc) {
  1759. continue;
  1760. }
  1761. let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  1762. match made.as_ref() {
  1763. Some((host, _)) => copies.push(match &host.tiled {
  1764. Some(tiled) => (r.data() as usize, r.desc, tiled.given_bytes(), true),
  1765. None => (r.data() as usize, r.desc, host.bytes, false),
  1766. }),
  1767. None => without[usize::from(r.host.gone.load(Relaxed))] += 1,
  1768. }
  1769. }
  1770. }
  1771. let kinds = KINDS.each_ref().map(|k| k.load(Relaxed));
  1772. let mut since = [0u64; 5];
  1773. for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) {
  1774. *slot = now.saturating_sub(before.swap(now, Relaxed));
  1775. }
  1776. let video = crate::host::host().and_then(|h| h.video_memory());
  1777. let noted_us = began.elapsed().as_micros() as u64;
  1778. let walk = move || {
  1779. fn texels(m: &texture::Mip) -> u64 {
  1780. u64::from(m.width) * u64::from(m.height) * u64::from(m.depth)
  1781. }
  1782. let began = std::time::Instant::now();
  1783. // Copies; their bytes; the bytes of levels not mapped; copies with
  1784. // a level not mapped; with the largest level not mapped; with no
  1785. // level mapped; copies without a console layout (not asked).
  1786. let mut c = [0u64; 7];
  1787. // Of the copies: made level by level, and the bytes of their tiles.
  1788. let mut on_demand = [0u64; 2];
  1789. for &(memory, desc, bytes, by_level) in &copies {
  1790. c[0] += 1;
  1791. c[1] += bytes;
  1792. if by_level {
  1793. on_demand[0] += 1;
  1794. on_demand[1] += bytes;
  1795. continue;
  1796. }
  1797. let Some(layout) = texture_layout(&desc).map(|t| t.planes[0].layout.clone()) else {
  1798. c[6] += 1;
  1799. continue;
  1800. };
  1801. if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) {
  1802. continue;
  1803. }
  1804. c[3] += 1;
  1805. // Every slice holds the whole chain: the levels of the tail in
  1806. // its first block, the others after it from the smallest up
  1807. // (`victory_formats::texture::Layout`).
  1808. let mips = &layout.mips;
  1809. let tail = (layout.first_tail_mip as usize).min(mips.len());
  1810. let there = |from: u64, to: u64| {
  1811. (0..u64::from(layout.slices)).all(|slice| {
  1812. let at = memory as u64 + slice * layout.slice_size + from;
  1813. crate::texture::committed(at as *const u8, (to - from) as usize)
  1814. })
  1815. };
  1816. let all: u64 = mips.iter().map(texels).sum::<u64>().max(1);
  1817. let (mut missing, mut any) = (0u64, false);
  1818. for (level, m) in mips.iter().enumerate().take(tail) {
  1819. let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset };
  1820. if end <= m.offset {
  1821. continue;
  1822. }
  1823. if there(m.offset, end) {
  1824. any = true;
  1825. } else {
  1826. missing += texels(m);
  1827. c[4] += u64::from(level == 0);
  1828. }
  1829. }
  1830. if tail < mips.len() {
  1831. if there(0, layout.alignment.min(layout.slice_size).max(1)) {
  1832. any = true;
  1833. } else {
  1834. missing += mips[tail..].iter().map(texels).sum::<u64>();
  1835. }
  1836. }
  1837. c[2] += (u128::from(bytes) * u128::from(missing) / u128::from(all)) as u64;
  1838. c[5] += u64::from(!any);
  1839. }
  1840. // Of the due textures without a host copy: how many; the bytes of
  1841. // their memory; with all of it mapped, and those bytes; with part
  1842. // of it mapped, and the bytes that are; with none of it mapped.
  1843. let mapped = |list: &[(u64, u64)]| {
  1844. let mut n = [0u64; 7];
  1845. for &(at, len) in list {
  1846. n[0] += 1;
  1847. n[1] += len;
  1848. let there = crate::texture::mapped_bytes(at as *const u8, len as usize);
  1849. if len > 0 && there >= len {
  1850. n[2] += 1;
  1851. n[3] += len;
  1852. } else if there > 0 {
  1853. n[4] += 1;
  1854. n[5] += there;
  1855. } else {
  1856. n[6] += 1;
  1857. }
  1858. }
  1859. n
  1860. };
  1861. let (never, gone) = (mapped(&never), mapped(&gone));
  1862. let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]);
  1863. let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] =
  1864. [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]];
  1865. let [without_never, without_gone] = without;
  1866. let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20];
  1867. let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] =
  1868. [never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]];
  1869. let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] =
  1870. [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]];
  1871. let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]];
  1872. let walk_ms = began.elapsed().as_millis() as u64;
  1873. let [by_level_n, by_level_mb] = [on_demand[0], on_demand[1] >> 20];
  1874. tracing::info!(
  1875. "card accounting: room {room}, the card {used_mb} MB in use of a budget of {budget_mb} MB; host copies of textures the title \
  1876. fills: {copies_n} alive {copies_mb} MB, of which {unmapped_mb} MB are levels whose title memory is not mapped ({partly} copies \
  1877. with such a level, {largest} of them the largest level, {nothing} with no level mapped; {unknown} without a console layout, not \
  1878. asked); title textures without a host copy: {without_never} never had one, {without_gone} had one let go; due slots: \
  1879. {due_slots} ({due_uploaded} uploaded before, {due_other} of nothing the title fills), their textures: {alive_n} with a host \
  1880. copy alive ({alive_mb} MB, no card memory needed); {never_n} that never had one ({never_mb} MB of title memory: {never_whole} \
  1881. all mapped {never_whole_mb} MB, {never_part} in part {never_part_mb} MB mapped, {never_none} not mapped); {gone_n} whose host \
  1882. copy was let go ({gone_mb} MB: {gone_whole} all mapped {gone_whole_mb} MB, {gone_part} in part {gone_part_mb} MB mapped, \
  1883. {gone_none} not mapped); since the line before: {let_go} host copies let go {let_go_mb} MB, {again} made again {again_mb} MB, \
  1884. {made} made in all; noting took {noted_us} us on the frame's thread, the walk {walk_ms} ms on its own; of the host \
  1885. copies {by_level_n} are made level by level and hold {by_level_mb} MB of tiles (in the MB alive, not in the levels not mapped)"
  1886. );
  1887. WALKING.store(false, Relaxed);
  1888. };
  1889. if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() {
  1890. WALKING.store(false, Relaxed);
  1891. }
  1892. }
  1893. /// Lets go of the host copies of textures the title fills that nothing
  1894. /// names any more: placed textures were never released (one host texture
  1895. /// per address and description ever viewed: 18,639 of them, 2.5 GB, after
  1896. /// nine minutes of run 24), nor those of texture objects before the title
  1897. /// released them. A host copy goes when
  1898. /// - the title fills the texture ([`fills`]) and the host never copied
  1899. /// into it: its contents are in title memory;
  1900. /// - only the resource holds it: no list not yet reset names it (a list
  1901. /// holds the copies of the textures it uses, `HostList::transition`);
  1902. /// - only the host copy holds the host texture: no descriptor slot views
  1903. /// it (a slot keeps what it views, `HostHeap::kept`), so no shader can
  1904. /// read it through a slot made earlier, by a table or by an index;
  1905. /// - nothing asked for it for `IDLE_MS` and `IDLE_FRAMES` frames.
  1906. ///
  1907. /// The next use makes the host copy anew and uploads the title's memory
  1908. /// again (its staging state goes with it). The title resource stays: its
  1909. /// address is what views and lists name.
  1910. /// shortcut: [`host_resource`] hands out the host texture without holding
  1911. /// it; a thread that asked for it and has not yet recorded its use (which
  1912. /// makes the list or the slot hold it) is protected by that idle time alone.
  1913. /// Every caller uses it at once, within the title's call.
  1914. /// Called before a submission starts, by the thread that submits.
  1915. /// `VICTORY_TEXTURE_SWEEP=0` lets nothing go.
  1916. #[cfg(windows)]
  1917. pub(crate) fn let_go_idle() {
  1918. use std::sync::atomic::Ordering::Relaxed;
  1919. const IDLE_FRAMES: u64 = 4;
  1920. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1921. if !*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_none_or(|v| v != "0")) {
  1922. return;
  1923. }
  1924. // Copies replaced by ones with more levels, as any let go.
  1925. {
  1926. let mut replaced = REPLACED.lock().unwrap_or_else(|e| e.into_inner());
  1927. let (gone, keep): (Vec<_>, Vec<_>) =
  1928. replaced.drain(..).partition(|(at, _)| crate::host::long_ago(*at, 1000, IDLE_FRAMES));
  1929. *replaced = keep;
  1930. drop(replaced);
  1931. for (_, made) in gone {
  1932. crate::host::retire(made);
  1933. }
  1934. }
  1935. let memory = crate::host::host().and_then(|h| h.video_memory());
  1936. static KEEP: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1937. let keep = *KEEP
  1938. .get_or_init(|| !matches!(std::env::var("VICTORY_TEXTURE_KEEP").as_deref(), Ok("0") | Ok("1")));
  1939. let (idle_ms, most) = match memory {
  1940. Some([budget, used, ..]) if keep => {
  1941. let used = used.saturating_sub(crate::pool::texture_room())
  1942. + crate::shadow::card_room_kept()
  1943. + targets_room_kept();
  1944. crate::host::vram_keep(budget, used)
  1945. }
  1946. _ => (crate::host::vram_idle_ms(memory), u64::MAX),
  1947. };
  1948. // For the trail (`crate::host::trail`): how many went, their bytes,
  1949. // and the first one.
  1950. let (mut went, mut bytes, mut first) = (0u64, 0u64, None);
  1951. let all = textures();
  1952. // With a limit, the longest idle first.
  1953. let mut by_age: Vec<(u64, usize)> = Vec::new();
  1954. if most != u64::MAX {
  1955. for &at in all.iter() {
  1956. // SAFETY: as below.
  1957. let r = unsafe { &*(at as *const Resource) };
  1958. let used = r.host.used.load(Relaxed);
  1959. if used != 0 && fills(&r.desc) && crate::host::long_ago(used, idle_ms, IDLE_FRAMES) {
  1960. by_age.push((used & 0xffff_ffff, at));
  1961. }
  1962. }
  1963. by_age.sort_unstable();
  1964. }
  1965. // Without one, while textures are kept for minutes, a part of them at
  1966. // each look, the next one at the next: a play has over 100,000
  1967. // (`VICTORY_TEXTURE_SWEEP=whole`: all each time, as before).
  1968. const PART: usize = 8192;
  1969. static FROM: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
  1970. static WHOLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1971. let whole = *WHOLE.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_SWEEP").is_some_and(|v| v == "whole"));
  1972. let part = if most != u64::MAX {
  1973. 0
  1974. } else if whole || idle_ms < 60_000 {
  1975. usize::MAX
  1976. } else {
  1977. PART
  1978. };
  1979. let from = if part == PART { FROM.load(Relaxed) } else { 0 };
  1980. let mut looked = 0;
  1981. let began = std::time::Instant::now();
  1982. for at in all.range(from..).take(part).copied().chain(by_age.iter().map(|&(_, at)| at)) {
  1983. if bytes >= most {
  1984. break;
  1985. }
  1986. looked += 1;
  1987. if part == PART {
  1988. FROM.store(if looked == PART { at + 1 } else { 0 }, Relaxed);
  1989. }
  1990. // SAFETY: a texture leaves the table before it is freed, under the
  1991. // lock held here (`Drop for Resource`).
  1992. let r = unsafe { &*(at as *const Resource) };
  1993. // (Without its lock first: most were used lately or have none.)
  1994. let used = r.host.used.load(Relaxed);
  1995. if used == 0 || !fills(&r.desc) || !crate::host::long_ago(used, idle_ms, IDLE_FRAMES) || crate::texture::host_wrote(at) {
  1996. continue;
  1997. }
  1998. let gone = {
  1999. let mut made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  2000. let idle = made.as_ref().is_some_and(|(host, _)| {
  2001. crate::host::long_ago(r.host.used.load(Relaxed), idle_ms, IDLE_FRAMES)
  2002. && std::sync::Arc::strong_count(host) == 1
  2003. && crate::host::references(&host.texture) == 1
  2004. });
  2005. if idle {
  2006. // Under the lock: the next use must not find the staging
  2007. // state of the texture let go (it says "uploaded").
  2008. crate::texture::unstage(at as This);
  2009. r.host.wanted.store(u32::MAX, Relaxed);
  2010. made.take()
  2011. } else {
  2012. None
  2013. }
  2014. };
  2015. if let Some((host, _)) = gone {
  2016. r.host.gone.store(true, Relaxed);
  2017. KINDS[2].fetch_add(1, Relaxed);
  2018. KINDS[3].fetch_add(host.bytes, Relaxed);
  2019. went += 1;
  2020. bytes += host.bytes;
  2021. if first.is_none() {
  2022. first = Some(at);
  2023. }
  2024. crate::host::retire(host);
  2025. }
  2026. }
  2027. SWEPT_US[0].fetch_add(1, Relaxed);
  2028. SWEPT_US[1].fetch_add(began.elapsed().as_micros() as u64, Relaxed);
  2029. SWEPT_US[2].fetch_max(began.elapsed().as_micros() as u64, Relaxed);
  2030. if went > 0 {
  2031. crate::host::trail(|| {
  2032. format!(
  2033. "sweep: {went} host copies of textures the title fills let go ({} KiB), each held by its title texture alone (no list, no slot); the first: title texture {:#x}",
  2034. bytes >> 10,
  2035. first.unwrap_or(0)
  2036. )
  2037. });
  2038. }
  2039. }
  2040. /// Since the start: looks of [`let_go_idle`], their microseconds, and the
  2041. /// longest one's.
  2042. #[cfg(windows)]
  2043. pub(crate) static SWEPT_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
  2044. /// For the memory line: the host copies the sweep never lets go
  2045. /// ([`let_go_idle`] takes only copies of textures the title fills that the
  2046. /// host never copied into), by what would say they are dead weight. A
  2047. /// count and the bytes (twins included) of: the copies the host renders to
  2048. /// or writes; of them, those whose title memory is not mapped now (its
  2049. /// first page); those nothing has used for 30 seconds and 60 frames and
  2050. /// that no list and no slot holds; those that are both; the copies of
  2051. /// textures the title fills that the host copied into; and, of the first,
  2052. /// the placed ones. Render-target copies grew from 2,319 MB at the world's
  2053. /// first frame to 3,075 MB 150 s later in run 197 and never shrank, while
  2054. /// 26,517 copies of filled textures were let go to stay under the card's
  2055. /// line.
  2056. #[cfg(all(windows, feature = "diagnostics"))]
  2057. pub(crate) fn targets_census() -> [u64; 12] {
  2058. use std::sync::atomic::Ordering::Relaxed;
  2059. let mut c = [0u64; 12];
  2060. let all = textures();
  2061. for &at in all.iter() {
  2062. // SAFETY: as in `let_go_idle`.
  2063. let r = unsafe { &*(at as *const Resource) };
  2064. let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  2065. let Some((host, twin)) = made.as_ref() else {
  2066. continue;
  2067. };
  2068. let copied_into = host.filled && crate::texture::host_wrote(at);
  2069. if host.filled && !copied_into {
  2070. continue;
  2071. }
  2072. let bytes = host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes);
  2073. let mut add = |i: usize| {
  2074. c[i] += 1;
  2075. c[i + 1] += bytes;
  2076. };
  2077. if copied_into {
  2078. add(8);
  2079. continue;
  2080. }
  2081. add(0);
  2082. let placed = r.host.placed.load(Relaxed);
  2083. // Its first page: what is there of a texture starts there.
  2084. let unmapped = placed && !crate::texture::committed(r.data().cast_const(), 1);
  2085. let idle = crate::host::long_ago(r.host.used.load(Relaxed), 30_000, 60)
  2086. && std::sync::Arc::strong_count(host) == 1
  2087. && crate::host::references(&host.texture) == 1;
  2088. if unmapped {
  2089. add(2);
  2090. }
  2091. if idle {
  2092. add(4);
  2093. }
  2094. if unmapped && idle {
  2095. add(6);
  2096. }
  2097. if placed {
  2098. add(10);
  2099. }
  2100. }
  2101. c
  2102. }
  2103. /// For the memory line: title textures with a host copy the host renders
  2104. /// to or writes and those copies' bytes (twins included); title textures
  2105. /// without a host copy and the bytes of title memory they are; host copies
  2106. /// of textures the title fills and their bytes; of all title textures,
  2107. /// the placed ones with a host copy; the bytes of the twins alone (the
  2108. /// layer's own: the console has no second texture for a depth texture
  2109. /// shaders write); and, of the host copies of placed textures the title
  2110. /// fills, the bytes of those whose title memory is not mapped any more and
  2111. /// of those a descriptor slot still shows (the card holds a texture the
  2112. /// title has given up for as long as a slot shows it). The last two are
  2113. /// estimates from every 16th such texture: asking Windows about the memory
  2114. /// of all 16,000 takes too long.
  2115. #[cfg(all(windows, feature = "diagnostics"))]
  2116. pub(crate) fn census() -> [u64; 10] {
  2117. const EVERY: u64 = 16;
  2118. let mut count = [0u64; 10];
  2119. let mut placed_filled = 0u64;
  2120. let all = textures();
  2121. for &at in all.iter() {
  2122. // SAFETY: as in `let_go_idle`.
  2123. let r = unsafe { &*(at as *const Resource) };
  2124. let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner());
  2125. match made.as_ref() {
  2126. Some((host, twin)) => {
  2127. let kind = if host.filled { 4 } else { 0 };
  2128. count[kind] += 1;
  2129. count[kind + 1] += host.bytes + twin.as_ref().map_or(0, |t| t.colour.bytes);
  2130. count[7] += twin.as_ref().map_or(0, |t| t.colour.bytes);
  2131. let placed = r.host.placed.load(std::sync::atomic::Ordering::Relaxed);
  2132. if placed {
  2133. count[6] += 1;
  2134. }
  2135. if placed && host.filled {
  2136. placed_filled += 1;
  2137. // Its first page: a texture's smallest mips lie there,
  2138. // and are mapped first and unmapped last.
  2139. if placed_filled.is_multiple_of(EVERY) && !crate::texture::committed(r.data().cast_const(), 1) {
  2140. count[8] += host.bytes * EVERY;
  2141. if crate::host::references(&host.texture) > 1 {
  2142. count[9] += host.bytes * EVERY;
  2143. }
  2144. }
  2145. }
  2146. }
  2147. None => {
  2148. count[2] += 1;
  2149. count[3] += footprint(&r.desc).map_or(0, |f| f.size);
  2150. }
  2151. }
  2152. }
  2153. count
  2154. }
  2155. /// Host textures alive (the title's and the twins) and the bytes the host
  2156. /// gives them, for the memory line.
  2157. #[cfg(windows)]
  2158. pub(crate) static HOST_TEXTURES: [std::sync::atomic::AtomicU64; 2] =
  2159. [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  2160. /// The bytes the host allocates for `texture`.
  2161. #[cfg(windows)]
  2162. fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> u64 {
  2163. let Some(host) = crate::host::host() else {
  2164. return 0;
  2165. };
  2166. // SAFETY: plain queries on a live resource and device.
  2167. unsafe {
  2168. let desc = texture.GetDesc();
  2169. host.device.GetResourceAllocationInfo(0, &[desc]).SizeInBytes
  2170. }
  2171. }
  2172. #[cfg(windows)]
  2173. impl HostTexture {
  2174. pub(crate) fn flags(&self) -> u32 {
  2175. self.flags
  2176. }
  2177. fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture {
  2178. use std::sync::atomic::Ordering::Relaxed;
  2179. let bytes = host_bytes(&texture);
  2180. // SAFETY: a live texture.
  2181. let flags = unsafe { texture.GetDesc() }.Flags.0 as u32;
  2182. HOST_TEXTURES[0].fetch_add(1, Relaxed);
  2183. HOST_TEXTURES[1].fetch_add(bytes, Relaxed);
  2184. HostTexture {
  2185. texture,
  2186. state: std::sync::atomic::AtomicU32::new(state),
  2187. bytes,
  2188. filled: false,
  2189. tiled: None,
  2190. base: 0,
  2191. serial: SERIAL.fetch_add(1, Relaxed) + 1,
  2192. grown: Default::default(),
  2193. holds: Default::default(),
  2194. ahead: crate::texture::ahead::fresh(),
  2195. flags,
  2196. }
  2197. }
  2198. /// A texture made without memory of its own (`crate::tiles`): counted
  2199. /// as a host texture of no bytes.
  2200. fn new_tiled(
  2201. texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource,
  2202. state: u32,
  2203. tiled: crate::tiles::Tiled,
  2204. ) -> HostTexture {
  2205. HOST_TEXTURES[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2206. // SAFETY: a live texture.
  2207. let flags = unsafe { texture.GetDesc() }.Flags.0 as u32;
  2208. HostTexture {
  2209. texture,
  2210. state: std::sync::atomic::AtomicU32::new(state),
  2211. bytes: 0,
  2212. filled: false,
  2213. tiled: Some(tiled),
  2214. base: 0,
  2215. serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
  2216. grown: Default::default(),
  2217. holds: Default::default(),
  2218. ahead: crate::texture::ahead::fresh(),
  2219. flags,
  2220. }
  2221. }
  2222. }
  2223. #[cfg(windows)]
  2224. impl Drop for HostTexture {
  2225. fn drop(&mut self) {
  2226. use std::sync::atomic::Ordering::Relaxed;
  2227. HOST_TEXTURES[0].fetch_sub(1, Relaxed);
  2228. HOST_TEXTURES[1].fetch_sub(self.bytes, Relaxed);
  2229. if self.filled {
  2230. KINDS[0].fetch_sub(1, Relaxed);
  2231. KINDS[1].fetch_sub(self.bytes, Relaxed);
  2232. }
  2233. }
  2234. }
  2235. /// How many textures placed in title memory have a resource of ours
  2236. /// (never released), for the memory line.
  2237. #[cfg(all(windows, feature = "diagnostics"))]
  2238. pub(crate) fn placed_textures() -> u64 {
  2239. PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64
  2240. }
  2241. /// Moves the host texture to `wanted` (a host texture state); the host
  2242. /// resource and the state it leaves, if that is a change.
  2243. #[cfg(windows)]
  2244. pub(crate) fn host_transition(this: This, wanted: u32) -> Option<(*mut c_void, u32)> {
  2245. use windows::core::Interface;
  2246. let (host, _) = hosted(this, true)?;
  2247. let before = host
  2248. .state
  2249. .swap(wanted, std::sync::atomic::Ordering::Relaxed);
  2250. (before != wanted).then(|| (host.texture.as_raw(), before))
  2251. }
  2252. /// The host GPU's copy of a title resource, if it has one: made now if
  2253. /// this is the texture's first use ([`Hosted`]). Asking is a use; what must
  2254. /// not count as one asks `host_made`.
  2255. #[cfg(windows)]
  2256. pub(crate) fn host_resource<'a>(
  2257. this: This,
  2258. ) -> Option<&'a windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  2259. if this.is_null() {
  2260. return None;
  2261. }
  2262. let (host, _) = hosted(this, true)?;
  2263. // SAFETY: the resource holds the host copy until the title releases it
  2264. // (lists and slots that name the texture hold it past that), or until
  2265. // `let_go_idle` takes it: only from a texture the title fills, that no
  2266. // list and no slot holds and that nothing asked for in seconds (the
  2267. // asking just made is noted under the same lock).
  2268. Some(unsafe { &*std::ptr::from_ref(&host.texture) })
  2269. }
  2270. /// A title texture's host copy, shared, for a list to hold.
  2271. #[cfg(windows)]
  2272. pub(crate) fn host_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
  2273. if this.is_null() {
  2274. return None;
  2275. }
  2276. hosted(this, true).map(|made| made.0)
  2277. }
  2278. /// A title texture's host copy if it is made; not made here.
  2279. #[cfg(windows)]
  2280. pub(crate) fn made_copy(this: This) -> Option<std::sync::Arc<HostTexture>> {
  2281. if this.is_null() {
  2282. return None;
  2283. }
  2284. hosted(this, false).map(|made| made.0)
  2285. }
  2286. /// A host texture like the title's: same description, in GPU memory,
  2287. /// without the console's layout and flags.
  2288. #[cfg(windows)]
  2289. fn host_texture(
  2290. desc: &ResourceDesc,
  2291. state: u32,
  2292. clear: *const c_void,
  2293. ) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  2294. host_texture_as(desc, state, clear, false)
  2295. }
  2296. /// [`host_texture`]; `reserved`: without memory of its own, to be given
  2297. /// tiles level by level (`crate::tiles`).
  2298. #[cfg(windows)]
  2299. fn host_texture_as(
  2300. desc: &ResourceDesc,
  2301. state: u32,
  2302. clear: *const c_void,
  2303. reserved: bool,
  2304. ) -> Option<windows::Win32::Graphics::Direct3D12::ID3D12Resource> {
  2305. use windows::Win32::Graphics::Direct3D12::*;
  2306. const PC_FLAGS: u32 = 0xf; // render target, depth, UAV, no shader access
  2307. if desc.dimension == BUFFER {
  2308. return None;
  2309. }
  2310. let host = crate::host::host()?;
  2311. let mut d = *desc;
  2312. d.layout = 0;
  2313. d.alignment = 0;
  2314. d.flags &= PC_FLAGS;
  2315. // PC refuses depth targets that are also unordered-access (the console
  2316. // allows both; the title's shadow maps ask for it).
  2317. // The host copy loses the unordered access: shaders write a colour
  2318. // twin instead ([`Twin`]).
  2319. const DEPTH: u32 = 2;
  2320. const UNORDERED: u32 = 4;
  2321. if d.flags & DEPTH != 0 {
  2322. if d.flags & UNORDERED != 0 {
  2323. DEPTH_UNORDERED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2324. }
  2325. d.flags &= !UNORDERED;
  2326. }
  2327. d.format = pc_format(d.format);
  2328. const TARGET: u32 = 1;
  2329. if d.flags & (TARGET | UNORDERED) != 0 {
  2330. d.format = target_format(d.format);
  2331. }
  2332. const DENY_SHADER_RESOURCE: u32 = 8;
  2333. if d.flags & DENY_SHADER_RESOURCE == 0
  2334. && let Some(&(_, typeless)) = DEPTH_FORMATS.iter().find(|&&(f, _)| f == d.format)
  2335. {
  2336. d.format = typeless;
  2337. }
  2338. // The host has no sRGB unordered access: such textures are typeless,
  2339. // their unordered access views plain UNORM.
  2340. if d.flags & UNORDERED != 0 && SRGB.iter().any(|&(srgb, _)| srgb == d.format) {
  2341. d.format = family(d.format);
  2342. }
  2343. // The clear value names the format too: format, then color or depth
  2344. // and stencil (5 words).
  2345. let clear_value = (!clear.is_null()).then(|| {
  2346. // SAFETY: the title passes a whole clear value.
  2347. let mut value = unsafe { clear.cast::<[u32; 5]>().read_unaligned() };
  2348. value[0] = pc_format(value[0]);
  2349. if d.flags & (TARGET | UNORDERED) != 0 {
  2350. value[0] = target_format(value[0]);
  2351. }
  2352. value
  2353. });
  2354. let heap = D3D12_HEAP_PROPERTIES {
  2355. Type: D3D12_HEAP_TYPE_DEFAULT,
  2356. ..Default::default()
  2357. };
  2358. // A texture the title fills, whose every subresource is uploaded before
  2359. // anything reads it: cut from a block (what the piece held before shows
  2360. // in no texel).
  2361. if fills(desc)
  2362. && d.sample_count <= 1
  2363. && clear_value.is_none()
  2364. && texture_layout(desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor())
  2365. // SAFETY: the description has the host layout, as below.
  2366. && let Some(t) = unsafe {
  2367. crate::pool::texture(
  2368. &host.device,
  2369. (&raw const d).cast(),
  2370. D3D12_RESOURCE_STATES(crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32),
  2371. )
  2372. }
  2373. {
  2374. crate::host::name(&t, || {
  2375. format!("texture {}x{} f{} flags {:#x} (in a block)", d.width, d.height, d.format, d.flags)
  2376. });
  2377. return Some(t);
  2378. }
  2379. let mut texture: Option<ID3D12Resource> = None;
  2380. let made = if reserved {
  2381. // The card's own layout of 64 KiB tiles, which a reserved texture
  2382. // must have.
  2383. d.layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE.0 as u32;
  2384. // SAFETY: as below; a texture the title fills has no clear value.
  2385. unsafe {
  2386. host.device.CreateReservedResource(
  2387. (&raw const d).cast(),
  2388. D3D12_RESOURCE_STATES(
  2389. crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
  2390. ),
  2391. None,
  2392. &mut texture,
  2393. )
  2394. }
  2395. } else {
  2396. // SAFETY: the description has the host layout (checked size, same
  2397. // fields); the out pointer is ours.
  2398. unsafe {
  2399. host.device.CreateCommittedResource(
  2400. &heap,
  2401. crate::host::not_resident(),
  2402. (&raw const d).cast(),
  2403. D3D12_RESOURCE_STATES(
  2404. crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
  2405. ),
  2406. // The same layout: format, then color or depth and stencil.
  2407. clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()),
  2408. &mut texture,
  2409. )
  2410. }
  2411. };
  2412. if let Err(e) = &made {
  2413. tracing::warn!(error = %e, desc = ?d, reserved, "no host texture");
  2414. }
  2415. if !reserved
  2416. && made.is_ok()
  2417. && let Some(t) = &texture
  2418. && let Err(e) = crate::host::resident(&host.device, t).and_then(|()| crate::host::mapped(&host.device))
  2419. {
  2420. tracing::warn!(error = %e, desc = ?d, "a host texture is not resident");
  2421. texture = None;
  2422. }
  2423. if let Some(t) = &texture {
  2424. crate::host::name(t, || {
  2425. format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags)
  2426. });
  2427. }
  2428. texture
  2429. }
  2430. /// The host copy of title texture `this` if it is made and was made
  2431. /// without memory of its own (`crate::tiles`); it is not made here.
  2432. #[cfg(windows)]
  2433. pub(crate) fn host_tiled(this: This) -> Option<OnDemand> {
  2434. if this.is_null() || !crate::tiles::wanted() {
  2435. return None;
  2436. }
  2437. hosted(this, false).map(|(host, _)| host).filter(|host| host.tiled.is_some()).map(OnDemand)
  2438. }
  2439. /// The first level a view of title texture `this` may show, if its host
  2440. /// copy is made level by level and some level is held and has memory
  2441. /// (`crate::tiles::Tiled::first_shown`).
  2442. #[cfg(windows)]
  2443. pub(crate) fn first_shown(this: This) -> Option<u32> {
  2444. host_tiled(this)?.tiled()?.first_shown()
  2445. }
  2446. /// A host copy made without memory of its own (`crate::tiles`), as a
  2447. /// submission-time step of a list holds it.
  2448. #[cfg(windows)]
  2449. pub(crate) struct OnDemand(std::sync::Arc<HostTexture>);
  2450. // SAFETY: the host texture is named only in queue calls, which any thread
  2451. // may make; what it has been given is behind a lock of its own.
  2452. #[cfg(windows)]
  2453. unsafe impl Send for OnDemand {}
  2454. // SAFETY: as above.
  2455. #[cfg(windows)]
  2456. unsafe impl Sync for OnDemand {}
  2457. #[cfg(windows)]
  2458. impl OnDemand {
  2459. pub(crate) fn tiled(&self) -> Option<&crate::tiles::Tiled> {
  2460. self.0.tiled.as_ref()
  2461. }
  2462. /// [`crate::tiles::Tiled::uploaded`]; `memory`: where the texture's
  2463. /// title memory starts (its slots are made again if the first level
  2464. /// they may show changed).
  2465. /// Held levels get tiles only while the card has room ([`room`]).
  2466. /// Returns whether a level is still without its tiles: the caller
  2467. /// records the upload again later.
  2468. pub(crate) fn uploaded(&self, held: u32, memory: u64) -> bool {
  2469. let Some(tiled) = &self.0.tiled else {
  2470. return false;
  2471. };
  2472. let (changed, waiting) = tiled.uploaded(&self.0.texture, held, room(crate::host::host().and_then(|h| h.video_memory())));
  2473. if changed {
  2474. crate::descriptor::host::levels_changed(memory);
  2475. }
  2476. if waiting {
  2477. crate::tiles::STATS[9].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2478. }
  2479. waiting
  2480. }
  2481. /// [`crate::tiles::Tiled::card_wrote`]; `memory` as above.
  2482. pub(crate) fn card_wrote(&self, levels: u32, memory: u64) {
  2483. if let Some(tiled) = &self.0.tiled
  2484. && tiled.card_wrote(&self.0.texture, levels)
  2485. {
  2486. crate::descriptor::host::levels_changed(memory);
  2487. }
  2488. }
  2489. }
  2490. /// A texture's console memory and description; `None` for buffers.
  2491. pub(crate) fn texture_memory(this: This) -> Option<(*const u8, ResourceDesc)> {
  2492. if this.is_null() {
  2493. return None;
  2494. }
  2495. let r = resource(this);
  2496. (r.desc.dimension != BUFFER).then(|| (r.data().cast_const(), r.desc))
  2497. }
  2498. /// A buffer's host memory and size; `None` for textures.
  2499. pub(crate) fn buffer_bytes(this: This) -> Option<(*mut u8, u64)> {
  2500. if this.is_null() {
  2501. return None;
  2502. }
  2503. let r = resource(this);
  2504. (r.desc.dimension == BUFFER).then(|| (r.data(), r.desc.width))
  2505. }
  2506. impl Resource {
  2507. fn data(&self) -> *mut u8 {
  2508. match self.backing {
  2509. Backing::Committed(ref memory) => memory.ptr.as_ptr(),
  2510. // SAFETY: placement checked the range lies inside the heap.
  2511. Backing::Placed { heap, offset } => unsafe {
  2512. (*heap.cast::<Heap>())
  2513. .memory
  2514. .ptr
  2515. .as_ptr()
  2516. .add(offset as usize)
  2517. },
  2518. Backing::Address(at) => at,
  2519. }
  2520. }
  2521. }
  2522. fn resource<'a>(this: This) -> &'a Resource {
  2523. // SAFETY: called from resource methods only.
  2524. unsafe { &*this.cast::<Resource>() }
  2525. }
  2526. // The creation methods' own arguments, passed on.
  2527. #[allow(clippy::too_many_arguments)]
  2528. fn hand_out_resource(
  2529. desc: ResourceDesc,
  2530. heap: HeapProperties,
  2531. heap_flags: u32,
  2532. backing: Backing,
  2533. state: u32,
  2534. clear: *const c_void,
  2535. iid: *const Iid,
  2536. out: *mut This,
  2537. ) -> HRESULT {
  2538. #[cfg(not(windows))]
  2539. let _ = (state, clear);
  2540. let resource = Box::new(Resource {
  2541. object: Object::new(&RESOURCE_FUNCTIONS),
  2542. desc,
  2543. heap,
  2544. heap_flags,
  2545. backing,
  2546. #[cfg(windows)]
  2547. host: Hosted {
  2548. made: std::sync::Mutex::new(None),
  2549. state,
  2550. // SAFETY: the title passes a whole clear value (the format,
  2551. // then color or depth and stencil: 5 words) or null.
  2552. clear: (!clear.is_null()).then(|| unsafe { clear.cast::<[u32; 5]>().read_unaligned() }),
  2553. used: std::sync::atomic::AtomicU64::new(0),
  2554. refused: std::sync::atomic::AtomicBool::new(false),
  2555. gone: std::sync::atomic::AtomicBool::new(false),
  2556. placed: std::sync::atomic::AtomicBool::new(false),
  2557. wanted: std::sync::atomic::AtomicU32::new(u32::MAX),
  2558. grown: std::sync::atomic::AtomicBool::new(false),
  2559. },
  2560. });
  2561. // The host copy waits for the texture's first use ([`Hosted`]).
  2562. #[cfg(windows)]
  2563. if desc.dimension != BUFFER {
  2564. let at = std::ptr::from_ref::<Resource>(&resource) as usize;
  2565. textures().insert(at);
  2566. if !fills(&desc) {
  2567. TARGETS_AT
  2568. .lock()
  2569. .unwrap_or_else(|e| e.into_inner())
  2570. .insert(resource.data() as u64, at);
  2571. }
  2572. if !lazy() {
  2573. let _ = hosted(at as This, true);
  2574. }
  2575. }
  2576. #[cfg(windows)]
  2577. if desc.dimension == BUFFER {
  2578. let at = std::ptr::from_ref::<Resource>(&resource) as usize;
  2579. crate::shadow::register(at, resource.data() as u64, desc.width);
  2580. }
  2581. object::hand_out(RESOURCE, resource, iid, &RESOURCE_IIDS, out)
  2582. }
  2583. #[cfg(windows)]
  2584. impl Drop for Resource {
  2585. fn drop(&mut self) {
  2586. // Out of the table of textures first: the sweep looks at the ones
  2587. // in it, under its lock.
  2588. if self.desc.dimension != BUFFER {
  2589. textures().remove(&(std::ptr::from_ref::<Resource>(self) as usize));
  2590. if !fills(&self.desc) {
  2591. let mut targets = TARGETS_AT.lock().unwrap_or_else(|e| e.into_inner());
  2592. let at = self.data() as u64;
  2593. if targets.get(&at) == Some(&(std::ptr::from_ref::<Resource>(self) as usize)) {
  2594. targets.remove(&at);
  2595. }
  2596. }
  2597. }
  2598. let made = self
  2599. .host
  2600. .made
  2601. .get_mut()
  2602. .unwrap_or_else(|e| e.into_inner())
  2603. .take();
  2604. #[cfg(feature = "diagnostics")]
  2605. if made
  2606. .as_ref()
  2607. .is_some_and(|(h, _)| std::sync::Arc::strong_count(h) > 1)
  2608. {
  2609. // Before lists held their textures, this freed a texture that
  2610. // lists not yet run still named (a GPU page fault).
  2611. static OUTLIVED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  2612. let n = OUTLIVED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  2613. if n.is_power_of_two() {
  2614. tracing::info!(
  2615. n,
  2616. desc = ?self.desc,
  2617. "a title texture was released while a list not yet reset names its host copy"
  2618. );
  2619. }
  2620. }
  2621. // A running submission may still read the host copy (and a depth
  2622. // texture's colour twin).
  2623. if let Some((host, twin)) = made {
  2624. crate::host::retire(host);
  2625. if let Some(twin) = twin {
  2626. crate::host::retire(twin);
  2627. }
  2628. }
  2629. crate::texture::forget(std::ptr::from_ref::<Resource>(self) as usize);
  2630. crate::descriptor::forget(std::ptr::from_ref::<Resource>(self) as usize);
  2631. if self.desc.dimension == BUFFER {
  2632. crate::shadow::unregister(
  2633. std::ptr::from_ref::<Resource>(self) as usize,
  2634. self.data() as u64,
  2635. );
  2636. }
  2637. }
  2638. }
  2639. pub(crate) extern "system" fn create_committed(
  2640. _: This,
  2641. heap: *const HeapProperties,
  2642. heap_flags: u32,
  2643. desc: *const ResourceDesc,
  2644. state: u32,
  2645. clear: *const c_void,
  2646. iid: *const Iid,
  2647. out: *mut This,
  2648. ) -> HRESULT {
  2649. // SAFETY: the title passes both descriptions (null is tolerated).
  2650. let (Some(&heap), Some(&desc)) = (unsafe { (heap.as_ref(), desc.as_ref()) }) else {
  2651. return E_INVALIDARG;
  2652. };
  2653. let Some(info) = footprint(&desc) else {
  2654. tracing::warn!(?desc, "no size for this resource");
  2655. return E_INVALIDARG;
  2656. };
  2657. tracing::debug!(
  2658. dimension = desc.dimension,
  2659. size = info.size,
  2660. heap = heap.kind,
  2661. "committed resource"
  2662. );
  2663. let memory = match Memory::for_resource(info, heap.kind) {
  2664. Ok(memory) => memory,
  2665. Err(hr) => return hr,
  2666. };
  2667. hand_out_resource(
  2668. desc,
  2669. heap,
  2670. heap_flags,
  2671. Backing::Committed(memory),
  2672. state,
  2673. clear,
  2674. iid,
  2675. out,
  2676. )
  2677. }
  2678. /// Device method 0x3f8, inferred from the title's calls
  2679. /// (title+0x193e1b4: its back buffers, heap flag "allow display"): the
  2680. /// committed resource creation of the enhanced-barrier interfaces,
  2681. /// `(heap, heap flags, desc1, initial layout, clear value, protected
  2682. /// session, castable format count, castable formats, iid, out)`. The host
  2683. /// copy starts in the common state, as layouts are not tracked.
  2684. #[allow(clippy::too_many_arguments)] // the method's own arguments
  2685. pub(crate) extern "system" fn create_committed3(
  2686. this: This,
  2687. heap: *const HeapProperties,
  2688. heap_flags: u32,
  2689. desc: *const ResourceDesc,
  2690. _layout: u32,
  2691. clear: *const c_void,
  2692. _protected: This,
  2693. _castable_count: u32,
  2694. _castable: *const u32,
  2695. iid: *const Iid,
  2696. out: *mut This,
  2697. ) -> HRESULT {
  2698. const COMMON: u32 = 0;
  2699. create_committed(this, heap, heap_flags, desc, COMMON, clear, iid, out)
  2700. }
  2701. /// Registered page pools (64 KiB pages the title maps into tiled
  2702. /// resources by page index): first address and page count; a handle is an
  2703. /// index plus one, a removed pool leaves `None`.
  2704. static PAGE_POOLS: std::sync::Mutex<Vec<Option<(u64, u32)>>> = std::sync::Mutex::new(Vec::new());
  2705. fn page_pools() -> std::sync::MutexGuard<'static, Vec<Option<(u64, u32)>>> {
  2706. PAGE_POOLS.lock().unwrap_or_else(|e| e.into_inner())
  2707. }
  2708. /// Device method 0x250: `(address, page count, handle out)`.
  2709. pub(crate) extern "system" fn register_page_pool(
  2710. _: This,
  2711. address: u64,
  2712. pages: u32,
  2713. out: *mut usize,
  2714. ) -> HRESULT {
  2715. if out.is_null() || pages == 0 || !address.is_multiple_of(KIB_64) {
  2716. return E_INVALIDARG;
  2717. }
  2718. tracing::debug!(address = format_args!("{address:#x}"), pages, "page pool");
  2719. let mut pools = page_pools();
  2720. pools.push(Some((address, pages)));
  2721. // SAFETY: checked non-null; the title passes room for a handle.
  2722. unsafe { out.write(pools.len()) };
  2723. S_OK
  2724. }
  2725. /// Device method 0x258.
  2726. pub(crate) extern "system" fn unregister_page_pool(_: This, handle: usize) -> HRESULT {
  2727. match page_pools().get_mut(handle.wrapping_sub(1)) {
  2728. Some(pool @ Some(_)) => {
  2729. *pool = None;
  2730. S_OK
  2731. }
  2732. _ => E_INVALIDARG,
  2733. }
  2734. }
  2735. /// Device method 0x428, one of the `ID3D12Device9` to `ID3D12Device11`
  2736. /// additions. From the title's call: a resource at a virtual
  2737. /// address the title mapped itself, `(address, desc1, initial barrier
  2738. /// layout, clear value, iid, out)`, as `CreatePlacedResourceX` with
  2739. /// enhanced barriers. GPU addresses are CPU addresses, so the resource is
  2740. /// a view of that memory. `D3D12_RESOURCE_DESC1` starts like the plain
  2741. /// description; its sampler feedback region is not needed.
  2742. pub(crate) extern "system" fn create_at_address(
  2743. _: This,
  2744. address: u64,
  2745. desc: *const ResourceDesc,
  2746. layout: u32,
  2747. clear: *const c_void,
  2748. iid: *const Iid,
  2749. out: *mut This,
  2750. ) -> HRESULT {
  2751. // SAFETY: the title passes a description (null is tolerated).
  2752. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  2753. return E_INVALIDARG;
  2754. };
  2755. if address == 0 {
  2756. return E_INVALIDARG;
  2757. }
  2758. tracing::debug!(
  2759. address = format_args!("{address:#x}"),
  2760. dimension = desc.dimension,
  2761. width = desc.width,
  2762. layout,
  2763. "resource at an address"
  2764. );
  2765. const COMMON: u32 = 0;
  2766. const DEFAULT: HeapProperties = HeapProperties {
  2767. kind: 1,
  2768. cpu_pages: 0,
  2769. pool: 0,
  2770. creation_nodes: 1,
  2771. visible_nodes: 1,
  2772. };
  2773. hand_out_resource(
  2774. desc,
  2775. DEFAULT,
  2776. 0,
  2777. Backing::Address(address as *mut u8),
  2778. COMMON,
  2779. clear,
  2780. iid,
  2781. out,
  2782. )
  2783. }
  2784. /// Textures the title placed in its own memory and views without a
  2785. /// resource object (device 0x230, the title's streamed and
  2786. /// interface textures), by address and description: a resource at that
  2787. /// address, made the first time a draw reads one.
  2788. /// The resource is kept for the run (views and lists name its address);
  2789. /// its host texture is let go when nothing names it any more
  2790. /// ([`let_go_idle`]) and made again on the next use.
  2791. #[cfg(windows)]
  2792. static PLACED_TEXTURES: std::sync::Mutex<std::collections::BTreeMap<(u64, [u32; 14]), usize>> =
  2793. std::sync::Mutex::new(std::collections::BTreeMap::new());
  2794. /// The placed textures asked for with filler words set, as asked
  2795. /// (address and description): for [`PLACED_TWINS`].
  2796. #[cfg(windows)]
  2797. static PLACED_RAW: std::sync::Mutex<std::collections::BTreeSet<(u64, [u32; 14])>> =
  2798. std::sync::Mutex::new(std::collections::BTreeSet::new());
  2799. /// Placed textures asked for a second time with other filler words in
  2800. /// their description: each was a second resource and host copy before the
  2801. /// filler was left out of the key ([`texture_at`]).
  2802. #[cfg(windows)]
  2803. static PLACED_TWINS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  2804. /// See [`PLACED_TWINS`].
  2805. #[cfg(windows)]
  2806. pub(crate) fn placed_filler_twins() -> u64 {
  2807. PLACED_TWINS.load(std::sync::atomic::Ordering::Relaxed)
  2808. }
  2809. /// The bytes of title memory a texture with the resource description
  2810. /// `desc` (as words) takes where the title placed it; `None` for a buffer
  2811. /// and for a description without a size.
  2812. #[cfg(windows)]
  2813. pub(crate) fn placed_bytes(desc: &[u32; 14]) -> Option<u64> {
  2814. // SAFETY: 56 bytes in the description's layout.
  2815. let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
  2816. if d.dimension == BUFFER {
  2817. return None;
  2818. }
  2819. footprint(&d).map(|f| f.size)
  2820. }
  2821. /// The resource [`texture_at`] made for a texture placed at `address` with
  2822. /// the description `desc`, if it has made one: never made here (for the
  2823. /// frame listing, which must not count as a use).
  2824. #[cfg(all(windows, feature = "diagnostics"))]
  2825. pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> {
  2826. let mut key = *desc;
  2827. key[1] = 0;
  2828. key[13] = 0;
  2829. let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
  2830. let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?;
  2831. Some(*found as This)
  2832. }
  2833. /// From which level on the title texture's host copy was filled, and from
  2834. /// which bytes (diagnostics).
  2835. #[cfg(all(windows, feature = "diagnostics"))]
  2836. pub(crate) fn texture_held(resource: This) -> Option<(u32, crate::texture::Digest)> {
  2837. *made_copy(resource)?.holds.lock().unwrap_or_else(|e| e.into_inner())
  2838. }
  2839. /// The resource for a texture placed at `address` with the resource
  2840. /// description `desc` (as words), made on first use.
  2841. #[cfg(windows)]
  2842. pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option<This> {
  2843. // Words 1 and 13 of the description are the filler of its layout
  2844. // (after the dimension, and at the end): the title leaves there what
  2845. // its stack held, and two views of one texture that differed only in
  2846. // them each got a resource and a host copy of their own, on a card
  2847. // that fills at world entry. They are not part of what a texture is.
  2848. // `VICTORY_PLACED_FILLER=1`: kept in the key, as before.
  2849. static KEPT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  2850. let raw = *desc;
  2851. let mut key = *desc;
  2852. if !*KEPT.get_or_init(|| std::env::var_os("VICTORY_PLACED_FILLER").is_some_and(|v| v == "1")) {
  2853. key[1] = 0;
  2854. key[13] = 0;
  2855. }
  2856. let desc = &key;
  2857. let mut map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner());
  2858. // How many resources the filler alone would have added (a count for
  2859. // the log: `placed_filler_twins`).
  2860. if raw != key {
  2861. let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner());
  2862. if seen.insert((address, raw)) {
  2863. let others = seen.range((address, [0; 14])..=(address, [u32::MAX; 14])).filter(|(_, r)| {
  2864. let mut blank = *r;
  2865. blank[1] = 0;
  2866. blank[13] = 0;
  2867. blank == key
  2868. });
  2869. if others.count() > 1 {
  2870. PLACED_TWINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  2871. }
  2872. }
  2873. }
  2874. if let Some(&r) = map.get(&(address, *desc)) {
  2875. return Some(r as This);
  2876. }
  2877. // SAFETY: 56 bytes in the description's layout.
  2878. let d = unsafe { desc.as_ptr().cast::<ResourceDesc>().read_unaligned() };
  2879. if d.dimension == BUFFER {
  2880. return None;
  2881. }
  2882. let mut out = std::ptr::null();
  2883. let made = create_at_address(
  2884. std::ptr::null(),
  2885. address,
  2886. &d,
  2887. 0,
  2888. std::ptr::null(),
  2889. &RESOURCE_IIDS[0],
  2890. &mut out,
  2891. );
  2892. if made != S_OK {
  2893. return None;
  2894. }
  2895. map.insert((address, *desc), out as usize);
  2896. crate::texture::placed_in_host_written(address, desc);
  2897. resource(out)
  2898. .host
  2899. .placed
  2900. .store(true, std::sync::atomic::Ordering::Relaxed);
  2901. Some(out)
  2902. }
  2903. pub(crate) extern "system" fn create_placed(
  2904. _: This,
  2905. heap: This,
  2906. offset: u64,
  2907. desc: *const ResourceDesc,
  2908. state: u32,
  2909. clear: *const c_void,
  2910. iid: *const Iid,
  2911. out: *mut This,
  2912. ) -> HRESULT {
  2913. // SAFETY: the title passes a description (null is tolerated).
  2914. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  2915. return E_INVALIDARG;
  2916. };
  2917. if heap.is_null() {
  2918. return E_INVALIDARG;
  2919. }
  2920. // SAFETY: the title passes one of our heaps.
  2921. let h = unsafe { &*heap.cast::<Heap>() };
  2922. let fits = footprint(&desc).is_some_and(|info| {
  2923. offset.is_multiple_of(info.alignment)
  2924. && offset
  2925. .checked_add(info.size)
  2926. .is_some_and(|end| end <= h.desc.size)
  2927. });
  2928. if !fits {
  2929. tracing::warn!(
  2930. ?desc,
  2931. offset,
  2932. heap = h.desc.size,
  2933. "placed resource does not fit"
  2934. );
  2935. return E_INVALIDARG;
  2936. }
  2937. object::add_ref(heap);
  2938. let backing = Backing::Placed { heap, offset };
  2939. hand_out_resource(
  2940. desc,
  2941. h.desc.properties,
  2942. h.desc.flags,
  2943. backing,
  2944. state,
  2945. clear,
  2946. iid,
  2947. out,
  2948. )
  2949. }
  2950. extern "system" fn resource_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  2951. object::answer(
  2952. RESOURCE,
  2953. iid,
  2954. object::is(iid, &RESOURCE_IIDS).then_some(this),
  2955. out,
  2956. )
  2957. }
  2958. extern "system" fn resource_release(this: This) -> u32 {
  2959. object::release_boxed::<Resource>(this)
  2960. }
  2961. /// Memory is always mapped (subresources are not told apart yet); a null
  2962. /// `out` only asks for residency.
  2963. extern "system" fn map(this: This, _sub: u32, _read: *const c_void, out: *mut *mut u8) -> HRESULT {
  2964. if !out.is_null() {
  2965. // SAFETY: checked non-null; the title passes room for a pointer.
  2966. unsafe { out.write(resource(this).data()) };
  2967. }
  2968. S_OK
  2969. }
  2970. extern "system" fn unmap(_: This, _sub: u32, _written: *const c_void) {}
  2971. extern "system" fn resource_desc(this: This, out: *mut ResourceDesc) {
  2972. if !out.is_null() {
  2973. // SAFETY: checked non-null; the title passes room for a description.
  2974. unsafe { out.write(resource(this).desc) };
  2975. }
  2976. }
  2977. /// Device method `GetCustomHeapProperties`, returning its struct through a
  2978. /// hidden first argument: what a standard heap type is as a custom heap.
  2979. /// Memory is unified and cache-coherent (as the architecture query says),
  2980. /// so every type is in pool L0, default heaps are not CPU-visible and the
  2981. /// others are write-back.
  2982. pub(crate) extern "system" fn custom_heap_properties(
  2983. out: *mut HeapProperties,
  2984. _: This,
  2985. nodes: u32,
  2986. kind: u32,
  2987. ) -> *mut HeapProperties {
  2988. const CUSTOM: u32 = 4;
  2989. const NOT_AVAILABLE: u32 = 1;
  2990. const WRITE_BACK: u32 = 3;
  2991. const L0: u32 = 1;
  2992. let nodes = nodes.max(1);
  2993. let cpu_pages = match kind {
  2994. 1 => NOT_AVAILABLE,
  2995. 2 | 3 => WRITE_BACK,
  2996. _ => 0,
  2997. };
  2998. let properties = HeapProperties {
  2999. kind: CUSTOM,
  3000. cpu_pages,
  3001. pool: if cpu_pages == 0 { 0 } else { L0 },
  3002. creation_nodes: nodes,
  3003. visible_nodes: nodes,
  3004. };
  3005. // SAFETY: the title passes room for the result (null is tolerated).
  3006. if let Some(out) = unsafe { out.as_mut() } {
  3007. *out = properties;
  3008. }
  3009. out
  3010. }
  3011. extern "system" fn gpu_address(this: This) -> u64 {
  3012. let r = resource(this);
  3013. let at = r.data() as u64;
  3014. // The console's GPU addresses fit in 40 bits; its ray-tracing builder
  3015. // refuses others (diagnostics: which memory breaks that).
  3016. #[cfg(feature = "diagnostics")]
  3017. if at >> 40 != 0 {
  3018. static ONCE: [std::sync::Once; 2] = [std::sync::Once::new(), std::sync::Once::new()];
  3019. let backing = match r.backing {
  3020. Backing::Committed(ref m) => format!("committed, attributes {:?}", m.attributes),
  3021. Backing::Placed { offset, .. } => format!("placed in a heap at {offset:#x}"),
  3022. Backing::Address(_) => "at a title address".into(),
  3023. };
  3024. ONCE[usize::from(r.desc.dimension == BUFFER)].call_once(|| {
  3025. tracing::warn!(address = format_args!("{at:#x}"), backing, desc = ?r.desc, "a GPU address above 40 bits")
  3026. });
  3027. }
  3028. at
  3029. }
  3030. extern "system" fn heap_properties(
  3031. this: This,
  3032. properties: *mut HeapProperties,
  3033. flags: *mut u32,
  3034. ) -> HRESULT {
  3035. let r = resource(this);
  3036. // SAFETY: either pointer may be null; otherwise the title passes room.
  3037. unsafe {
  3038. if let Some(p) = properties.as_mut() {
  3039. *p = r.heap;
  3040. }
  3041. if let Some(f) = flags.as_mut() {
  3042. *f = r.heap_flags;
  3043. }
  3044. }
  3045. S_OK
  3046. }
  3047. /// IUnknown 3, object 4, device child 1, heap 1.
  3048. static HEAP_FUNCTIONS: Table<24> = {
  3049. let mut f = object::d3d12_object(object::missing_table::<HEAP, 24>());
  3050. f[0] = heap_query as *const ();
  3051. f[2] = heap_release as *const ();
  3052. f[7] = object::parent_device as *const (); // 0x38
  3053. f[8] = heap_desc as *const (); // 0x40
  3054. Table(f)
  3055. };
  3056. /// IUnknown 3, object 4, device child 1, resource 10 (7 as on PC, then 3
  3057. /// console ones).
  3058. static RESOURCE_FUNCTIONS: Table<32> = {
  3059. let mut f = object::d3d12_object(object::missing_table::<RESOURCE, 32>());
  3060. f[0] = resource_query as *const ();
  3061. f[2] = resource_release as *const ();
  3062. f[7] = object::parent_device as *const (); // 0x38
  3063. f[8] = map as *const (); // 0x40
  3064. f[9] = unmap as *const (); // 0x48
  3065. f[10] = resource_desc as *const (); // 0x50
  3066. f[11] = gpu_address as *const (); // 0x58
  3067. f[14] = heap_properties as *const (); // 0x70
  3068. Table(f)
  3069. };
  3070. #[cfg(test)]
  3071. pub(crate) fn test_buffer(width: u64) -> This {
  3072. let heap = HeapProperties {
  3073. kind: 1,
  3074. cpu_pages: 0,
  3075. pool: 0,
  3076. creation_nodes: 0,
  3077. visible_nodes: 0,
  3078. };
  3079. let desc = ResourceDesc {
  3080. dimension: BUFFER,
  3081. alignment: 0,
  3082. width,
  3083. height: 1,
  3084. depth_or_array_size: 1,
  3085. mip_levels: 1,
  3086. format: 0,
  3087. sample_count: 1,
  3088. sample_quality: 0,
  3089. layout: 1,
  3090. flags: 0,
  3091. };
  3092. let mut out = std::ptr::null();
  3093. let hr = create_committed(
  3094. std::ptr::null(),
  3095. &heap,
  3096. 0,
  3097. &desc,
  3098. 0,
  3099. std::ptr::null(),
  3100. &RESOURCE_IIDS[0],
  3101. &mut out,
  3102. );
  3103. assert_eq!(hr, S_OK);
  3104. out
  3105. }
  3106. #[cfg(test)]
  3107. mod tests {
  3108. use super::*;
  3109. use crate::object::slot;
  3110. #[test]
  3111. fn a8_unorm_is_not_in_the_r8_typeless_family() {
  3112. // DXGI_FORMAT values: 60 R8_TYPELESS, 61 R8_UNORM, 62 R8_UINT,
  3113. // 63 R8_SNORM, 64 R8_SINT, 65 A8_UNORM. The R8 typeless family is
  3114. // 60..=64; A8_UNORM has no typeless family and cannot be cast to R8,
  3115. // so it must stand alone rather than fold into R8_TYPELESS.
  3116. assert_eq!(family(60), 60);
  3117. for f in 61..=64 {
  3118. assert_eq!(family(f), 60);
  3119. }
  3120. assert_eq!(family(65), 65);
  3121. // Boundaries: 59 belongs to the preceding family, 66 is unmapped.
  3122. assert_eq!(family(59), 53);
  3123. assert_eq!(family(66), 66);
  3124. }
  3125. type Release = extern "system" fn(This) -> u32;
  3126. type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT;
  3127. type Address = extern "system" fn(This) -> u64;
  3128. const PROPERTIES: HeapProperties = HeapProperties {
  3129. kind: 1,
  3130. cpu_pages: 0,
  3131. pool: 0,
  3132. creation_nodes: 0,
  3133. visible_nodes: 0,
  3134. };
  3135. fn buffer(width: u64) -> ResourceDesc {
  3136. ResourceDesc {
  3137. dimension: BUFFER,
  3138. alignment: 0,
  3139. width,
  3140. height: 1,
  3141. depth_or_array_size: 1,
  3142. mip_levels: 1,
  3143. format: 0,
  3144. sample_count: 1,
  3145. sample_quality: 0,
  3146. layout: 1,
  3147. flags: 0,
  3148. }
  3149. }
  3150. fn texture(width: u64, height: u32, format: u32, mips: u16) -> ResourceDesc {
  3151. ResourceDesc {
  3152. dimension: 3,
  3153. width,
  3154. height,
  3155. format,
  3156. mip_levels: mips,
  3157. layout: 0,
  3158. ..buffer(0)
  3159. }
  3160. }
  3161. fn heap(size: u64) -> This {
  3162. let desc = HeapDesc {
  3163. size,
  3164. properties: PROPERTIES,
  3165. alignment: 0,
  3166. flags: 0,
  3167. };
  3168. let mut heap = std::ptr::null();
  3169. assert_eq!(
  3170. create_heap(std::ptr::null(), &desc, &HEAP_IIDS[0], &mut heap),
  3171. S_OK
  3172. );
  3173. heap
  3174. }
  3175. #[test]
  3176. fn heaps_are_zeroed_aligned_memory() {
  3177. let heap = heap(1 << 20);
  3178. // SAFETY: a heap we just made.
  3179. let memory = unsafe { &(*heap.cast::<Heap>()).memory };
  3180. assert_eq!(memory.ptr.as_ptr() as u64 % KIB_64, 0);
  3181. let mut back = std::mem::MaybeUninit::<HeapDesc>::uninit();
  3182. slot::<extern "system" fn(This, *mut HeapDesc)>(heap, 0x40)(heap, back.as_mut_ptr());
  3183. // SAFETY: written above.
  3184. assert_eq!(unsafe { back.assume_init() }.size, 1 << 20);
  3185. assert_eq!(slot::<Release>(heap, 0x10)(heap), 0);
  3186. let bad = HeapDesc {
  3187. size: 1 << 20,
  3188. properties: PROPERTIES,
  3189. alignment: 3,
  3190. flags: 0,
  3191. };
  3192. let mut out = std::ptr::null();
  3193. assert_eq!(
  3194. create_heap(std::ptr::null(), &bad, &HEAP_IIDS[0], &mut out),
  3195. E_INVALIDARG
  3196. );
  3197. }
  3198. #[test]
  3199. fn device_setup_heap_properties_and_resources_at_addresses() {
  3200. let device = crate::device::device();
  3201. // GetCustomHeapProperties (0xd0): the struct comes back through the
  3202. // hidden first argument, which is also returned.
  3203. type Custom =
  3204. extern "system" fn(*mut HeapProperties, This, u32, u32) -> *mut HeapProperties;
  3205. let mut p = PROPERTIES;
  3206. let back = slot::<Custom>(device, 0xd0)(&mut p, device, 1, 2);
  3207. assert_eq!(back, &raw mut p);
  3208. assert_eq!(
  3209. (
  3210. p.kind,
  3211. p.cpu_pages,
  3212. p.pool,
  3213. p.creation_nodes,
  3214. p.visible_nodes
  3215. ),
  3216. (4, 3, 1, 1, 1),
  3217. "upload: custom, write-back, L0"
  3218. );
  3219. slot::<Custom>(device, 0xd0)(&mut p, device, 1, 1);
  3220. assert_eq!(p.cpu_pages, 1, "default: not CPU-visible");
  3221. // 0x428: a buffer over memory the title owns, as the title asks.
  3222. type At = extern "system" fn(
  3223. This,
  3224. u64,
  3225. *const ResourceDesc,
  3226. u32,
  3227. *const c_void,
  3228. *const Iid,
  3229. *mut This,
  3230. ) -> HRESULT;
  3231. let memory = vec![0u8; 0x1_0000];
  3232. let address = memory.as_ptr() as u64;
  3233. let mut r = std::ptr::null();
  3234. let create = slot::<At>(device, 0x428);
  3235. let desc = buffer(0x1_0000);
  3236. let null = std::ptr::null();
  3237. assert_eq!(
  3238. create(
  3239. device,
  3240. address,
  3241. &desc,
  3242. u32::MAX,
  3243. null,
  3244. &RESOURCE_IIDS[0],
  3245. &mut r
  3246. ),
  3247. 0
  3248. );
  3249. assert_eq!(slot::<Address>(r, 0x58)(r), address);
  3250. assert_eq!(slot::<Release>(r, 0x10)(r), 0);
  3251. // The title's memory is still there after the release.
  3252. assert_eq!(memory[0xffff], 0);
  3253. assert_ne!(
  3254. create(device, 0, &desc, u32::MAX, null, &RESOURCE_IIDS[0], &mut r),
  3255. 0
  3256. );
  3257. }
  3258. #[test]
  3259. fn sizes_cover_every_mip() {
  3260. let size = |d: &ResourceDesc| footprint(d).map(|i| i.size);
  3261. assert_eq!(size(&buffer(256)), Some(KIB_64));
  3262. // Textures take their console layout and its alignment (4 KiB
  3263. // standard swizzle when the description leaves it to the library):
  3264. // 512x512 BC7 with 10 mips is 0x56000 bytes, 4 KiB aligned, as on
  3265. // the console.
  3266. let layout = |d: &ResourceDesc| texture_layout(d).unwrap().size;
  3267. let rgba = texture(256, 256, 28, 0);
  3268. assert_eq!(size(&rgba), Some(layout(&rgba).next_multiple_of(4096)));
  3269. let bc7 = footprint(&texture(512, 512, 98, 10));
  3270. let console = AllocationInfo {
  3271. size: 0x56000,
  3272. alignment: 0x1000,
  3273. };
  3274. assert_eq!(bc7, Some(console));
  3275. assert!(layout(&rgba) >= 4 * (256 * 256 * 4) / 3, "every mip");
  3276. // BC1 is 8 bytes per 4x4 block: 1024x1024, one mip = 512 KiB.
  3277. assert_eq!(size(&texture(1024, 1024, 71, 1)), Some(512 << 10));
  3278. assert_eq!(size(&texture(16, 16, 66, 1)), None, "1-bit format");
  3279. // Linear layout (1) and an explicit mode (64 KiB display, 0x10a).
  3280. let linear = ResourceDesc {
  3281. layout: 1,
  3282. ..texture(100, 60, 28, 1)
  3283. };
  3284. assert_eq!(
  3285. texture_layout(&linear).unwrap().planes[0]
  3286. .layout
  3287. .desc
  3288. .swizzle
  3289. .0,
  3290. 0
  3291. );
  3292. let display = ResourceDesc {
  3293. layout: 0x10a,
  3294. ..texture(100, 60, 28, 1)
  3295. };
  3296. assert_eq!(
  3297. texture_layout(&display).unwrap().planes[0]
  3298. .layout
  3299. .desc
  3300. .swizzle
  3301. .0,
  3302. 10
  3303. );
  3304. let mut info = AllocationInfo {
  3305. size: 0,
  3306. alignment: 0,
  3307. };
  3308. let descs = [buffer(100), texture(256, 256, 28, 0)];
  3309. allocation_info(&mut info, std::ptr::null(), 0, 2, descs.as_ptr());
  3310. assert_eq!(
  3311. info,
  3312. AllocationInfo {
  3313. size: KIB_64 + size(&descs[1]).unwrap(),
  3314. alignment: KIB_64
  3315. }
  3316. );
  3317. allocation_info(&mut info, std::ptr::null(), 0, 1, &texture(1, 1, 999, 1));
  3318. assert_eq!(info.size, u64::MAX);
  3319. }
  3320. #[test]
  3321. fn upload_footprints_follow_the_pc_rules() {
  3322. let null = std::ptr::null();
  3323. let mut layouts = [NO_FOOTPRINT; 2];
  3324. let (mut rows, mut sizes, mut total) = ([0; 2], [0; 2], 0);
  3325. let mut footprints = |desc: &ResourceDesc, first, count| {
  3326. let (l, r, s) = (layouts.as_mut_ptr(), rows.as_mut_ptr(), sizes.as_mut_ptr());
  3327. copyable_footprints(null, desc, first, count, 0, l, r, s, &mut total);
  3328. (layouts, rows, sizes, total)
  3329. };
  3330. // 100x60 RGBA8, 2 mips: 400-byte rows pitched to 512.
  3331. let (l, r, s, t) = footprints(&texture(100, 60, 28, 2), 0, 2);
  3332. assert_eq!((l[0].row_pitch, r[0], s[0]), (512, 60, 400));
  3333. // Mip 1 (50x30, 200-byte rows) starts after 59 pitched rows and one
  3334. // packed row, rounded up to 512.
  3335. assert_eq!(l[1].offset, (512 * 59 + 400u64).next_multiple_of(512));
  3336. assert_eq!((l[1].width, l[1].height, r[1]), (50, 30, 30));
  3337. assert_eq!(t, l[1].offset + 256 * 29 + 200);
  3338. // BC1: rows of 4x4 blocks, 8 bytes each.
  3339. let (_, r, s, _) = footprints(&texture(64, 64, 71, 1), 0, 1);
  3340. assert_eq!((r[0], s[0]), (16, 128));
  3341. let (_, _, _, t) = footprints(&texture(64, 64, 71, 1), 1, 1);
  3342. assert_eq!(t, u64::MAX, "no second subresource");
  3343. }
  3344. #[test]
  3345. fn depth_stencil_footprints_follow_the_pc_plane_order() {
  3346. // Native D3D12 reports the same layout for both depth/stencil families
  3347. // and their view formats. Mips vary fastest, then array slices, then planes.
  3348. let expected = [
  3349. (512, 39, 16, 8),
  3350. (4_608, 39, 8, 4),
  3351. (6_656, 39, 16, 8),
  3352. (10_752, 39, 8, 4),
  3353. (12_800, 60, 16, 8),
  3354. (16_896, 60, 8, 4),
  3355. (18_944, 60, 16, 8),
  3356. (23_040, 60, 8, 4),
  3357. ];
  3358. for format in (19..=22).chain(44..=47) {
  3359. let desc = ResourceDesc {
  3360. depth_or_array_size: 2,
  3361. ..texture(16, 8, format, 2)
  3362. };
  3363. let mut layouts = [NO_FOOTPRINT; 8];
  3364. let (mut rows, mut sizes, mut total) = ([0; 8], [0; 8], 0);
  3365. copyable_footprints(
  3366. std::ptr::null(),
  3367. &desc,
  3368. 0,
  3369. 8,
  3370. 512,
  3371. layouts.as_mut_ptr(),
  3372. rows.as_mut_ptr(),
  3373. sizes.as_mut_ptr(),
  3374. &mut total,
  3375. );
  3376. assert_eq!(
  3377. layouts.map(|l| (l.offset, l.format, l.width, l.height)),
  3378. expected,
  3379. "format {format}"
  3380. );
  3381. assert!(
  3382. layouts.iter().all(|l| l.depth == 1 && l.row_pitch == 512),
  3383. "format {format}"
  3384. );
  3385. assert_eq!(rows, [8, 4, 8, 4, 8, 4, 8, 4], "format {format}");
  3386. assert_eq!(sizes, [64, 32, 64, 32, 16, 8, 16, 8], "format {format}");
  3387. assert_eq!(total, 24_072, "format {format}");
  3388. assert!(subresource(&desc, 8).is_none(), "format {format}");
  3389. }
  3390. }
  3391. /// A 4x4 texture filled from a title buffer through our list and queue,
  3392. /// then read back from the host GPU.
  3393. #[cfg(windows)]
  3394. #[test]
  3395. fn buffer_data_reaches_the_host_texture() {
  3396. use windows::Win32::Graphics::Direct3D12::*;
  3397. let Some(host) = crate::host::host() else {
  3398. return; // no host GPU here
  3399. };
  3400. let null = std::ptr::null();
  3401. let iid = &RESOURCE_IIDS[0];
  3402. const COPY_DEST: u32 = 0x400;
  3403. let (mut image, mut source) = (null, null);
  3404. let rgba = texture(4, 4, 28, 1);
  3405. assert_eq!(
  3406. create_committed(
  3407. null,
  3408. &PROPERTIES,
  3409. 0,
  3410. &rgba,
  3411. COPY_DEST,
  3412. null.cast(),
  3413. iid,
  3414. &mut image
  3415. ),
  3416. S_OK
  3417. );
  3418. assert_eq!(
  3419. create_committed(
  3420. null,
  3421. &PROPERTIES,
  3422. 0,
  3423. &buffer(1024),
  3424. 0,
  3425. null.cast(),
  3426. iid,
  3427. &mut source
  3428. ),
  3429. S_OK
  3430. );
  3431. let (data, _) = buffer_bytes(source).unwrap();
  3432. // SAFETY: the buffer holds 1024 bytes.
  3433. let bytes = unsafe { std::slice::from_raw_parts_mut(data, 1024) };
  3434. for (i, b) in bytes.iter_mut().enumerate() {
  3435. *b = (i % 251) as u8;
  3436. }
  3437. let queue_iid = guid(
  3438. 0x0ec870a6,
  3439. 0x5d7e,
  3440. 0x4c22,
  3441. [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed],
  3442. );
  3443. let allocator_iid = guid(
  3444. 0x6102dee4,
  3445. 0xaf59,
  3446. 0x4b09,
  3447. [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
  3448. );
  3449. let list_iid = guid(
  3450. 0x5b160d0f,
  3451. 0xac1b,
  3452. 0x4185,
  3453. [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
  3454. );
  3455. let (mut queue, mut allocator, mut list) = (null, null, null);
  3456. let queue_desc = [0u32; 4];
  3457. assert_eq!(
  3458. crate::queue::create(null, queue_desc.as_ptr().cast(), &queue_iid, &mut queue),
  3459. S_OK
  3460. );
  3461. assert_eq!(
  3462. crate::list::create_allocator(null, 0, &allocator_iid, &mut allocator),
  3463. S_OK
  3464. );
  3465. assert_eq!(
  3466. crate::list::create_list(null, 0, 0, allocator, null, &list_iid, &mut list),
  3467. S_OK
  3468. );
  3469. #[repr(C)]
  3470. struct Location {
  3471. resource: This,
  3472. kind: u32,
  3473. footprint: PlacedFootprint,
  3474. }
  3475. let rows = PlacedFootprint {
  3476. offset: 0,
  3477. format: 28,
  3478. width: 4,
  3479. height: 4,
  3480. depth: 1,
  3481. row_pitch: 256,
  3482. };
  3483. let to = Location {
  3484. resource: image,
  3485. kind: 0,
  3486. footprint: PlacedFootprint { offset: 0, ..rows },
  3487. };
  3488. let from = Location {
  3489. resource: source,
  3490. kind: 1,
  3491. footprint: rows,
  3492. };
  3493. type Copy =
  3494. extern "system" fn(This, *const Location, u32, u32, u32, *const Location, *const u8);
  3495. slot::<Copy>(list, 0x80)(list, &to, 0, 0, 0, &from, null.cast());
  3496. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list);
  3497. slot::<extern "system" fn(This, u32, *const This)>(queue, 0x50)(queue, 1, &list);
  3498. // Read the host texture back into a readback buffer.
  3499. let readback_heap = D3D12_HEAP_PROPERTIES {
  3500. Type: D3D12_HEAP_TYPE_READBACK,
  3501. ..Default::default()
  3502. };
  3503. let readback_desc = D3D12_RESOURCE_DESC {
  3504. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  3505. Width: 1024,
  3506. Height: 1,
  3507. DepthOrArraySize: 1,
  3508. MipLevels: 1,
  3509. SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC {
  3510. Count: 1,
  3511. Quality: 0,
  3512. },
  3513. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  3514. ..Default::default()
  3515. };
  3516. let mut readback: Option<ID3D12Resource> = None;
  3517. // SAFETY: plain creation of a readback buffer.
  3518. unsafe {
  3519. host.device
  3520. .CreateCommittedResource(
  3521. &readback_heap,
  3522. D3D12_HEAP_FLAG_NONE,
  3523. &readback_desc,
  3524. D3D12_RESOURCE_STATE_COPY_DEST,
  3525. None,
  3526. &mut readback,
  3527. )
  3528. .unwrap();
  3529. }
  3530. let readback = readback.unwrap();
  3531. let host_image = host_resource(image).unwrap();
  3532. let back = host.new_list().unwrap();
  3533. let (_, before) = host_transition(image, 0x800).unwrap();
  3534. // The upload list holds the texture until it is reset.
  3535. assert!(std::sync::Arc::strong_count(&host_copy(image).unwrap()) > 2);
  3536. use windows::core::Interface;
  3537. let out_to = Location {
  3538. resource: readback.as_raw().cast_const().cast(),
  3539. kind: 1,
  3540. footprint: rows,
  3541. };
  3542. let out_from = Location {
  3543. resource: host_image.as_raw().cast_const().cast(),
  3544. kind: 0,
  3545. footprint: to.footprint,
  3546. };
  3547. // SAFETY: an open list, live resources, locations in the host layout.
  3548. unsafe {
  3549. back.list.ResourceBarrier(&[crate::host::transition(
  3550. host_image,
  3551. D3D12_RESOURCE_STATES(before as i32),
  3552. D3D12_RESOURCE_STATE_COPY_SOURCE,
  3553. )]);
  3554. back.list.CopyTextureRegion(
  3555. (&raw const out_to).cast(),
  3556. 0,
  3557. 0,
  3558. 0,
  3559. (&raw const out_from).cast(),
  3560. None,
  3561. );
  3562. }
  3563. back.close();
  3564. host.execute(&[&back]);
  3565. let mut mapped = std::ptr::null_mut();
  3566. // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes.
  3567. let read = unsafe {
  3568. readback
  3569. .Map(
  3570. 0,
  3571. Some(&D3D12_RANGE {
  3572. Begin: 0,
  3573. End: 1024,
  3574. }),
  3575. Some(&mut mapped),
  3576. )
  3577. .unwrap();
  3578. std::slice::from_raw_parts(mapped.cast::<u8>(), 1024)
  3579. };
  3580. for row in 0..4 {
  3581. let at = row * 256;
  3582. assert_eq!(read[at..at + 16], bytes[at..at + 16], "row {row}");
  3583. }
  3584. }
  3585. /// A 16-bit depth texture the title also asks unordered access for gets
  3586. /// a colour twin, and the host copies one into the other, both ways: a
  3587. /// pattern put into the twin is copied to the depth texture, the twin
  3588. /// is overwritten with zeros, and the pattern comes back from the depth
  3589. /// texture. A copy the host does not allow ends the test (with the
  3590. /// debug layer's message under `VICTORY_D3D12_DEBUG=1` in a diagnostics
  3591. /// build).
  3592. #[cfg(windows)]
  3593. #[test]
  3594. fn a_depth_texture_and_its_twin_copy_into_each_other() {
  3595. use windows::Win32::Graphics::Direct3D12::*;
  3596. use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC};
  3597. let Some(host) = crate::host::host() else {
  3598. return; // no host GPU here
  3599. };
  3600. let null = std::ptr::null();
  3601. const DEPTH_WRITE: u32 = 0x10;
  3602. let desc = ResourceDesc {
  3603. flags: 6,
  3604. ..texture(4, 4, 55, 1)
  3605. };
  3606. let mut depth = null;
  3607. assert_eq!(
  3608. create_committed(
  3609. null,
  3610. &PROPERTIES,
  3611. 0,
  3612. &desc,
  3613. DEPTH_WRITE,
  3614. null.cast(),
  3615. &RESOURCE_IIDS[0],
  3616. &mut depth
  3617. ),
  3618. S_OK
  3619. );
  3620. let host_depth = host_resource(depth).unwrap();
  3621. let Some(twin) = twin_resource(depth) else {
  3622. return; // twins are turned off
  3623. };
  3624. // SAFETY: live resources.
  3625. let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) };
  3626. // Both R16 typeless: one a depth texture, one with unordered access.
  3627. assert_eq!((d.Format.0, d.Flags.0), (53, 2));
  3628. assert_eq!((t.Format.0, t.Flags.0), (53, 4));
  3629. // Four rows of four 16-bit texels, 256 bytes apart as copies place
  3630. // them: the pattern, then as many zeros.
  3631. let mut pattern = vec![0u8; 1024];
  3632. for row in 0..4 {
  3633. for b in 0..8 {
  3634. pattern[row * 256 + b] = (1 + row * 8 + b) as u8;
  3635. }
  3636. }
  3637. let (upload, data) = host.upload_buffer(2048).unwrap();
  3638. // SAFETY: the buffer's mapping, 2048 bytes.
  3639. unsafe {
  3640. std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024);
  3641. std::ptr::write_bytes(data.add(1024), 0, 1024);
  3642. }
  3643. let readback_heap = D3D12_HEAP_PROPERTIES {
  3644. Type: D3D12_HEAP_TYPE_READBACK,
  3645. ..Default::default()
  3646. };
  3647. let readback_desc = D3D12_RESOURCE_DESC {
  3648. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  3649. Width: 1024,
  3650. Height: 1,
  3651. DepthOrArraySize: 1,
  3652. MipLevels: 1,
  3653. SampleDesc: DXGI_SAMPLE_DESC {
  3654. Count: 1,
  3655. Quality: 0,
  3656. },
  3657. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  3658. ..Default::default()
  3659. };
  3660. let mut readback: Option<ID3D12Resource> = None;
  3661. // SAFETY: plain creation of a readback buffer.
  3662. unsafe {
  3663. host.device
  3664. .CreateCommittedResource(
  3665. &readback_heap,
  3666. D3D12_HEAP_FLAG_NONE,
  3667. &readback_desc,
  3668. D3D12_RESOURCE_STATE_COPY_DEST,
  3669. None,
  3670. &mut readback,
  3671. )
  3672. .unwrap();
  3673. }
  3674. let readback = readback.unwrap();
  3675. // A texture's one subresource; the four rows of a buffer at `offset`.
  3676. let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION {
  3677. // SAFETY: a borrowed pointer the location never releases.
  3678. pResource: unsafe { std::mem::transmute_copy(texture) },
  3679. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  3680. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  3681. SubresourceIndex: 0,
  3682. },
  3683. };
  3684. let rows = |buffer: &ID3D12Resource, offset: u64| D3D12_TEXTURE_COPY_LOCATION {
  3685. // SAFETY: as above.
  3686. pResource: unsafe { std::mem::transmute_copy(buffer) },
  3687. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  3688. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  3689. PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  3690. Offset: offset,
  3691. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  3692. Format: DXGI_FORMAT(53),
  3693. Width: 4,
  3694. Height: 4,
  3695. Depth: 1,
  3696. RowPitch: 256,
  3697. },
  3698. },
  3699. },
  3700. };
  3701. let (written, tested, source, dest) = (
  3702. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  3703. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  3704. D3D12_RESOURCE_STATE_COPY_SOURCE,
  3705. D3D12_RESOURCE_STATE_COPY_DEST,
  3706. );
  3707. let moved = crate::host::transition;
  3708. let list = host.new_list().unwrap();
  3709. // SAFETY: an open list and live resources; the two textures are one
  3710. // size in one format family.
  3711. unsafe {
  3712. let l = &list.list;
  3713. // The pattern into the twin, the twin into the depth texture.
  3714. l.ResourceBarrier(&[moved(twin, written, dest), moved(host_depth, tested, dest)]);
  3715. l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 0), None);
  3716. l.ResourceBarrier(&[moved(twin, dest, source)]);
  3717. l.CopyResource(host_depth, twin);
  3718. // Zeros over the twin, then the depth texture back into it.
  3719. l.ResourceBarrier(&[moved(twin, source, dest)]);
  3720. l.CopyTextureRegion(&whole(twin), 0, 0, 0, &rows(&upload, 1024), None);
  3721. l.ResourceBarrier(&[moved(host_depth, dest, source)]);
  3722. l.CopyResource(twin, host_depth);
  3723. // The twin read back; both textures to the states they had.
  3724. l.ResourceBarrier(&[moved(twin, dest, source)]);
  3725. l.CopyTextureRegion(&rows(&readback, 0), 0, 0, 0, &whole(twin), None);
  3726. l.ResourceBarrier(&[
  3727. moved(twin, source, written),
  3728. moved(host_depth, source, tested),
  3729. ]);
  3730. }
  3731. list.close();
  3732. host.execute(&[&list]);
  3733. let mut mapped = std::ptr::null_mut();
  3734. // SAFETY: the copies finished (execute waits); the buffer is 1024 bytes.
  3735. let read = unsafe {
  3736. readback
  3737. .Map(
  3738. 0,
  3739. Some(&D3D12_RANGE {
  3740. Begin: 0,
  3741. End: 1024,
  3742. }),
  3743. Some(&mut mapped),
  3744. )
  3745. .unwrap();
  3746. std::slice::from_raw_parts(mapped.cast::<u8>(), 1024)
  3747. };
  3748. for row in 0..4 {
  3749. let at = row * 256;
  3750. assert_eq!(read[at..at + 8], pattern[at..at + 8], "row {row}");
  3751. }
  3752. }
  3753. /// A depth texture with a stencil plane that the title also asks
  3754. /// unordered access for gets a twin of the stencil plane, and what
  3755. /// shaders write there is in the stencil plane once the list is closed:
  3756. /// a pattern put into the twin is read back from the plane.
  3757. #[cfg(windows)]
  3758. #[test]
  3759. fn a_stencil_planes_twin_reaches_the_plane() {
  3760. use std::sync::atomic::Ordering::Relaxed;
  3761. use windows::Win32::Graphics::Direct3D12::*;
  3762. use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC};
  3763. let Some(host) = crate::host::host() else {
  3764. return; // no host GPU here
  3765. };
  3766. let null = std::ptr::null();
  3767. const DEPTH_WRITE: u32 = 0x10;
  3768. let desc = ResourceDesc {
  3769. flags: 6,
  3770. ..texture(4, 4, 45, 1)
  3771. };
  3772. let mut depth = null;
  3773. assert_eq!(
  3774. create_committed(
  3775. null,
  3776. &PROPERTIES,
  3777. 0,
  3778. &desc,
  3779. DEPTH_WRITE,
  3780. null.cast(),
  3781. &RESOURCE_IIDS[0],
  3782. &mut depth
  3783. ),
  3784. S_OK
  3785. );
  3786. let host_depth = host_resource(depth).unwrap();
  3787. let Some(twin) = twin_resource(depth) else {
  3788. return; // twins are turned off
  3789. };
  3790. // SAFETY: live resources.
  3791. let (d, t) = unsafe { (host_depth.GetDesc(), twin.GetDesc()) };
  3792. // R24G8 typeless with depth, R8 typeless with unordered access.
  3793. assert_eq!((d.Format.0, d.Flags.0), (44, 2));
  3794. assert_eq!((t.Format.0, t.Flags.0), (60, 4));
  3795. // Four rows of four texels, 256 bytes apart as copies place them.
  3796. let mut pattern = vec![0u8; 1024];
  3797. for row in 0..4 {
  3798. for b in 0..4 {
  3799. pattern[row * 256 + b] = (1 + row * 4 + b) as u8;
  3800. }
  3801. }
  3802. let (upload, data) = host.upload_buffer(1024).unwrap();
  3803. // SAFETY: the buffer's mapping, 1024 bytes.
  3804. unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) };
  3805. let readback_heap = D3D12_HEAP_PROPERTIES {
  3806. Type: D3D12_HEAP_TYPE_READBACK,
  3807. ..Default::default()
  3808. };
  3809. let readback_desc = D3D12_RESOURCE_DESC {
  3810. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  3811. // Room for the rows as the host places them (512 bytes apart
  3812. // for the stencil plane on NVIDIA, not 256).
  3813. Width: 4096,
  3814. Height: 1,
  3815. DepthOrArraySize: 1,
  3816. MipLevels: 1,
  3817. SampleDesc: DXGI_SAMPLE_DESC {
  3818. Count: 1,
  3819. Quality: 0,
  3820. },
  3821. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  3822. ..Default::default()
  3823. };
  3824. let mut readback: Option<ID3D12Resource> = None;
  3825. // SAFETY: plain creation of a readback buffer.
  3826. unsafe {
  3827. host.device
  3828. .CreateCommittedResource(
  3829. &readback_heap,
  3830. D3D12_HEAP_FLAG_NONE,
  3831. &readback_desc,
  3832. D3D12_RESOURCE_STATE_COPY_DEST,
  3833. None,
  3834. &mut readback,
  3835. )
  3836. .unwrap();
  3837. }
  3838. let readback = readback.unwrap();
  3839. // How the host lays the stencil plane (subresource 1) out in a buffer.
  3840. let mut plane = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  3841. // SAFETY: a plain query writing one footprint.
  3842. unsafe {
  3843. host.device
  3844. .GetCopyableFootprints(&d, 1, 1, 0, Some(&mut plane), None, None, None);
  3845. }
  3846. let pattern_rows = D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  3847. Offset: 0,
  3848. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  3849. Format: DXGI_FORMAT(60),
  3850. Width: 4,
  3851. Height: 4,
  3852. Depth: 1,
  3853. RowPitch: 256,
  3854. },
  3855. };
  3856. // A subresource of a texture; rows of a buffer.
  3857. let whole = |texture: &ID3D12Resource, index: u32| D3D12_TEXTURE_COPY_LOCATION {
  3858. // SAFETY: a borrowed pointer the location never releases.
  3859. pResource: unsafe { std::mem::transmute_copy(texture) },
  3860. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  3861. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  3862. SubresourceIndex: index,
  3863. },
  3864. };
  3865. let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| {
  3866. D3D12_TEXTURE_COPY_LOCATION {
  3867. // SAFETY: as above.
  3868. pResource: unsafe { std::mem::transmute_copy(buffer) },
  3869. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  3870. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  3871. PlacedFootprint: placed,
  3872. },
  3873. }
  3874. };
  3875. let (written, source, dest) = (
  3876. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  3877. D3D12_RESOURCE_STATE_COPY_SOURCE,
  3878. D3D12_RESOURCE_STATE_COPY_DEST,
  3879. );
  3880. let moved = crate::host::transition;
  3881. // The pattern into the twin, where a shader would write it.
  3882. let fill = host.new_list().unwrap();
  3883. // SAFETY: an open list and live resources.
  3884. unsafe {
  3885. let l = &fill.list;
  3886. l.ResourceBarrier(&[moved(twin, written, dest)]);
  3887. l.CopyTextureRegion(&whole(twin, 0), 0, 0, 0, &rows(&upload, pattern_rows), None);
  3888. l.ResourceBarrier(&[moved(twin, dest, written)]);
  3889. }
  3890. fill.close();
  3891. host.execute(&[&fill]);
  3892. // A list in which a shader writes the twin: closing it copies the
  3893. // twin into the stencil plane.
  3894. let list = host.new_list().unwrap();
  3895. assert!(list.twin_use(depth, true, true));
  3896. list.twins_written();
  3897. list.close();
  3898. host.execute(&[&list]);
  3899. // The stencil plane read back from the state the list left it in.
  3900. let state = host_copy(depth).unwrap().state.load(Relaxed);
  3901. let state = D3D12_RESOURCE_STATES(state as i32);
  3902. let back = host.new_list().unwrap();
  3903. // SAFETY: an open list and live resources; a whole subresource.
  3904. unsafe {
  3905. let l = &back.list;
  3906. l.ResourceBarrier(&[moved(host_depth, state, source)]);
  3907. let (to, from) = (rows(&readback, plane), whole(host_depth, 1));
  3908. l.CopyTextureRegion(&to, 0, 0, 0, &from, None);
  3909. l.ResourceBarrier(&[moved(host_depth, source, state)]);
  3910. }
  3911. back.close();
  3912. host.execute(&[&back]);
  3913. let mut mapped = std::ptr::null_mut();
  3914. // SAFETY: the copies finished (execute waits); the buffer is 4096 bytes.
  3915. let read = unsafe {
  3916. readback
  3917. .Map(
  3918. 0,
  3919. Some(&D3D12_RANGE {
  3920. Begin: 0,
  3921. End: 4096,
  3922. }),
  3923. Some(&mut mapped),
  3924. )
  3925. .unwrap();
  3926. std::slice::from_raw_parts(mapped.cast::<u8>(), 4096)
  3927. };
  3928. let pitch = plane.Footprint.RowPitch as usize;
  3929. for row in 0..4 {
  3930. let (at, from) = (row * pitch, row * 256);
  3931. assert_eq!(read[at..at + 4], pattern[from..from + 4], "row {row}");
  3932. }
  3933. }
  3934. /// The depth plane of a depth-stencil texture is drawn from the plane's
  3935. /// twin when the list that wrote the twin closes: class numbers are put
  3936. /// into the twin of a texture in the console's 16-bit depth-stencil
  3937. /// format, and draws with the depth test "equal" at the depth the
  3938. /// title's lighting computes for a class (the number times the float
  3939. /// nearest 1/65535) then cover the texels of that class and no other.
  3940. #[cfg(windows)]
  3941. #[test]
  3942. fn a_depth_planes_twin_is_drawn_into_the_plane() {
  3943. use std::sync::atomic::Ordering::Relaxed;
  3944. use windows::Win32::Foundation::RECT;
  3945. use windows::Win32::Graphics::Direct3D::D3D_PRIMITIVE_TOPOLOGY;
  3946. use windows::Win32::Graphics::Direct3D12::*;
  3947. use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_SAMPLE_DESC};
  3948. use windows::core::s;
  3949. let Some(host) = crate::host::host() else {
  3950. return; // no host GPU here
  3951. };
  3952. let null = std::ptr::null();
  3953. const DEPTH_WRITE: u32 = 0x10;
  3954. let desc = ResourceDesc {
  3955. flags: 6,
  3956. ..texture(4, 4, 118, 1)
  3957. };
  3958. let mut depth = null;
  3959. assert_eq!(
  3960. create_committed(
  3961. null,
  3962. &PROPERTIES,
  3963. 0,
  3964. &desc,
  3965. DEPTH_WRITE,
  3966. null.cast(),
  3967. &RESOURCE_IIDS[0],
  3968. &mut depth
  3969. ),
  3970. S_OK
  3971. );
  3972. let host_depth = host_resource(depth).unwrap();
  3973. let Some(plane) = twin_plane_resource(depth) else {
  3974. return; // these twins are turned off
  3975. };
  3976. // SAFETY: live resources.
  3977. let (d, t) = unsafe { (host_depth.GetDesc(), plane.GetDesc()) };
  3978. // R24G8 typeless with depth, R16 typeless with unordered access.
  3979. assert_eq!((d.Format.0, d.Flags.0), (44, 2));
  3980. assert_eq!((t.Format.0, t.Flags.0), (53, 4));
  3981. // Four rows of four class numbers (16 bits each), 256 bytes apart
  3982. // as copies place them. 128 and 129 are the classes whose 24-bit
  3983. // depth lies nearest a half step.
  3984. const CLASSES: [u16; 16] = [
  3985. 8, 65, 128, 129, 65, 8, 129, 128, 0, 255, 65, 64, 129, 130, 8, 65,
  3986. ];
  3987. let mut pattern = vec![0u8; 1024];
  3988. for (i, class) in CLASSES.into_iter().enumerate() {
  3989. let at = i / 4 * 256 + i % 4 * 2;
  3990. pattern[at..at + 2].copy_from_slice(&class.to_le_bytes());
  3991. }
  3992. let (upload, data) = host.upload_buffer(1024).unwrap();
  3993. // SAFETY: the buffer's mapping, 1024 bytes.
  3994. unsafe { std::ptr::copy_nonoverlapping(pattern.as_ptr(), data, 1024) };
  3995. let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| {
  3996. let heap = D3D12_HEAP_PROPERTIES {
  3997. Type: kind,
  3998. ..Default::default()
  3999. };
  4000. let desc = D3D12_RESOURCE_DESC {
  4001. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  4002. Width: 1024,
  4003. Height: 1,
  4004. DepthOrArraySize: 1,
  4005. MipLevels: 1,
  4006. SampleDesc: DXGI_SAMPLE_DESC {
  4007. Count: 1,
  4008. Quality: 0,
  4009. },
  4010. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  4011. ..Default::default()
  4012. };
  4013. let mut made: Option<ID3D12Resource> = None;
  4014. // SAFETY: plain creation of a buffer.
  4015. unsafe {
  4016. host.device
  4017. .CreateCommittedResource(
  4018. &heap,
  4019. D3D12_HEAP_FLAG_NONE,
  4020. &desc,
  4021. state,
  4022. None,
  4023. &mut made,
  4024. )
  4025. .unwrap();
  4026. }
  4027. made.unwrap()
  4028. };
  4029. let readback = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST);
  4030. // The colour target the draws cover: 4x4, 8 bits a texel.
  4031. let target = {
  4032. let heap = D3D12_HEAP_PROPERTIES {
  4033. Type: D3D12_HEAP_TYPE_DEFAULT,
  4034. ..Default::default()
  4035. };
  4036. let desc = D3D12_RESOURCE_DESC {
  4037. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  4038. Width: 4,
  4039. Height: 4,
  4040. DepthOrArraySize: 1,
  4041. MipLevels: 1,
  4042. Format: DXGI_FORMAT(61),
  4043. SampleDesc: DXGI_SAMPLE_DESC {
  4044. Count: 1,
  4045. Quality: 0,
  4046. },
  4047. Flags: D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET,
  4048. ..Default::default()
  4049. };
  4050. let mut made: Option<ID3D12Resource> = None;
  4051. // SAFETY: plain creation of a texture.
  4052. unsafe {
  4053. host.device
  4054. .CreateCommittedResource(
  4055. &heap,
  4056. D3D12_HEAP_FLAG_NONE,
  4057. &desc,
  4058. D3D12_RESOURCE_STATE_RENDER_TARGET,
  4059. None,
  4060. &mut made,
  4061. )
  4062. .unwrap();
  4063. }
  4064. made.unwrap()
  4065. };
  4066. let rows_of = |format: i32| D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  4067. Offset: 0,
  4068. Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
  4069. Format: DXGI_FORMAT(format),
  4070. Width: 4,
  4071. Height: 4,
  4072. Depth: 1,
  4073. RowPitch: 256,
  4074. },
  4075. };
  4076. // A texture's one subresource; rows of a buffer.
  4077. let whole = |texture: &ID3D12Resource| D3D12_TEXTURE_COPY_LOCATION {
  4078. // SAFETY: a borrowed pointer the location never releases.
  4079. pResource: unsafe { std::mem::transmute_copy(texture) },
  4080. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  4081. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  4082. SubresourceIndex: 0,
  4083. },
  4084. };
  4085. let rows = |buffer: &ID3D12Resource, placed: D3D12_PLACED_SUBRESOURCE_FOOTPRINT| {
  4086. D3D12_TEXTURE_COPY_LOCATION {
  4087. // SAFETY: as above.
  4088. pResource: unsafe { std::mem::transmute_copy(buffer) },
  4089. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  4090. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  4091. PlacedFootprint: placed,
  4092. },
  4093. }
  4094. };
  4095. let (written, source, dest, tested, drawn) = (
  4096. D3D12_RESOURCE_STATE_UNORDERED_ACCESS,
  4097. D3D12_RESOURCE_STATE_COPY_SOURCE,
  4098. D3D12_RESOURCE_STATE_COPY_DEST,
  4099. D3D12_RESOURCE_STATE_DEPTH_WRITE,
  4100. D3D12_RESOURCE_STATE_RENDER_TARGET,
  4101. );
  4102. let moved = crate::host::transition;
  4103. // The class numbers into the twin, where a shader would write them.
  4104. let fill = host.new_list().unwrap();
  4105. // SAFETY: an open list and live resources.
  4106. unsafe {
  4107. let l = &fill.list;
  4108. l.ResourceBarrier(&[moved(plane, written, dest)]);
  4109. l.CopyTextureRegion(&whole(plane), 0, 0, 0, &rows(&upload, rows_of(53)), None);
  4110. l.ResourceBarrier(&[moved(plane, dest, written)]);
  4111. }
  4112. fill.close();
  4113. host.execute(&[&fill]);
  4114. // A list in which a shader writes the twins: closing it draws the
  4115. // depth plane's twin into the plane.
  4116. let list = host.new_list().unwrap();
  4117. assert!(list.twin_use(depth, true, true));
  4118. list.twins_written();
  4119. list.close();
  4120. host.execute(&[&list]);
  4121. // The draws: a triangle over the target at the depth of a class,
  4122. // as the title's lighting places its rectangles.
  4123. const SOURCE: &str = r#"
  4124. #define RS "RootConstants(num32BitConstants = 1, b0)"
  4125. cbuffer Drawn : register(b0) { uint number; };
  4126. [RootSignature(RS)]
  4127. float4 corner(uint i : SV_VertexID) : SV_Position {
  4128. float z = float(number) * asfloat(0x37800080);
  4129. return float4(float(i & 1) * 4.0 - 1.0, float(i >> 1) * 4.0 - 1.0, z, 1.0);
  4130. }
  4131. float4 lit() : SV_Target { return 1.0; }
  4132. "#;
  4133. let vs = crate::host::compile(SOURCE, s!("corner"), s!("vs_5_1")).unwrap();
  4134. let ps = crate::host::compile(SOURCE, s!("lit"), s!("ps_5_1")).unwrap();
  4135. let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE {
  4136. pShaderBytecode: bytes.as_ptr().cast(),
  4137. BytecodeLength: bytes.len(),
  4138. };
  4139. let mut blend = D3D12_BLEND_DESC::default();
  4140. blend.RenderTarget[0].RenderTargetWriteMask = 0xf;
  4141. let mut formats = [DXGI_FORMAT(0); 8];
  4142. formats[0] = DXGI_FORMAT(61);
  4143. // SAFETY: plain creation; the description points at live data.
  4144. let (signature, pipeline) = unsafe {
  4145. let signature: ID3D12RootSignature =
  4146. host.device.CreateRootSignature(0, &vs[..]).unwrap();
  4147. let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
  4148. pRootSignature: std::mem::transmute_copy(&signature),
  4149. VS: code(&vs[..]),
  4150. PS: code(&ps[..]),
  4151. BlendState: blend,
  4152. SampleMask: u32::MAX,
  4153. RasterizerState: D3D12_RASTERIZER_DESC {
  4154. FillMode: D3D12_FILL_MODE_SOLID,
  4155. CullMode: D3D12_CULL_MODE_NONE,
  4156. DepthClipEnable: true.into(),
  4157. ..Default::default()
  4158. },
  4159. // As the title's lighting: test "equal", nothing written.
  4160. DepthStencilState: D3D12_DEPTH_STENCIL_DESC {
  4161. DepthEnable: true.into(),
  4162. DepthWriteMask: D3D12_DEPTH_WRITE_MASK_ZERO,
  4163. DepthFunc: D3D12_COMPARISON_FUNC_EQUAL,
  4164. ..Default::default()
  4165. },
  4166. PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
  4167. NumRenderTargets: 1,
  4168. RTVFormats: formats,
  4169. DSVFormat: DXGI_FORMAT(45),
  4170. SampleDesc: DXGI_SAMPLE_DESC {
  4171. Count: 1,
  4172. Quality: 0,
  4173. },
  4174. ..Default::default()
  4175. };
  4176. let pipeline: ID3D12PipelineState =
  4177. host.device.CreateGraphicsPipelineState(&desc).unwrap();
  4178. (signature, pipeline)
  4179. };
  4180. let state = host_copy(depth).unwrap().state.load(Relaxed);
  4181. let state = D3D12_RESOURCE_STATES(state as i32);
  4182. let colour = host.rtv(Some(&target), None);
  4183. let depth_view = host.dsv(
  4184. host_depth,
  4185. Some(&D3D12_DEPTH_STENCIL_VIEW_DESC {
  4186. Format: DXGI_FORMAT(45),
  4187. ViewDimension: D3D12_DSV_DIMENSION_TEXTURE2D,
  4188. ..Default::default()
  4189. }),
  4190. );
  4191. let back = host.new_list().unwrap();
  4192. // SAFETY: an open list and live resources and views.
  4193. unsafe {
  4194. let l = &back.list;
  4195. if state != tested {
  4196. l.ResourceBarrier(&[moved(host_depth, state, tested)]);
  4197. }
  4198. l.ClearRenderTargetView(colour, &[0.0; 4], None);
  4199. l.SetGraphicsRootSignature(&signature);
  4200. l.SetPipelineState(&pipeline);
  4201. l.OMSetRenderTargets(1, Some(&colour), false, Some(&depth_view));
  4202. l.RSSetViewports(&[D3D12_VIEWPORT {
  4203. TopLeftX: 0.0,
  4204. TopLeftY: 0.0,
  4205. Width: 4.0,
  4206. Height: 4.0,
  4207. MinDepth: 0.0,
  4208. MaxDepth: 1.0,
  4209. }]);
  4210. l.RSSetScissorRects(&[RECT {
  4211. left: 0,
  4212. top: 0,
  4213. right: 4,
  4214. bottom: 4,
  4215. }]);
  4216. l.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY(4));
  4217. // Classes 65 and 129 are drawn; the others are not.
  4218. for class in [65u32, 129] {
  4219. l.SetGraphicsRoot32BitConstant(0, class, 0);
  4220. l.DrawInstanced(3, 1, 0, 0);
  4221. }
  4222. l.ResourceBarrier(&[moved(&target, drawn, source)]);
  4223. let (to, from) = (rows(&readback, rows_of(61)), whole(&target));
  4224. l.CopyTextureRegion(&to, 0, 0, 0, &from, None);
  4225. }
  4226. back.close();
  4227. host.execute(&[&back]);
  4228. let mut mapped = std::ptr::null_mut();
  4229. // SAFETY: the copy finished (execute waits); the buffer is 1024 bytes.
  4230. let read = unsafe {
  4231. readback
  4232. .Map(
  4233. 0,
  4234. Some(&D3D12_RANGE {
  4235. Begin: 0,
  4236. End: 1024,
  4237. }),
  4238. Some(&mut mapped),
  4239. )
  4240. .unwrap();
  4241. std::slice::from_raw_parts(mapped.cast::<u8>(), 1024)
  4242. };
  4243. for (i, class) in CLASSES.into_iter().enumerate() {
  4244. let covered = read[i / 4 * 256 + i % 4] != 0;
  4245. let drawn = matches!(class, 65 | 129);
  4246. assert_eq!(covered, drawn, "texel {i}, class {class}");
  4247. }
  4248. }
  4249. #[test]
  4250. fn committed_and_placed_resources_map_at_their_gpu_address() {
  4251. let null = std::ptr::null();
  4252. let mut committed = null;
  4253. let hr = create_committed(
  4254. null,
  4255. &PROPERTIES,
  4256. 0,
  4257. &buffer(256),
  4258. 0,
  4259. null.cast(),
  4260. &RESOURCE_IIDS[0],
  4261. &mut committed,
  4262. );
  4263. assert_eq!(hr, S_OK);
  4264. let mut data = std::ptr::null_mut();
  4265. assert_eq!(
  4266. slot::<Map>(committed, 0x40)(committed, 0, null.cast(), &mut data),
  4267. S_OK
  4268. );
  4269. assert_eq!(slot::<Address>(committed, 0x58)(committed), data as u64);
  4270. // SAFETY: the buffer is at least 256 zeroed bytes.
  4271. assert_eq!(unsafe { *data.add(255) }, 0);
  4272. assert_eq!(slot::<Release>(committed, 0x10)(committed), 0);
  4273. let heap = heap(4 * KIB_64);
  4274. let place = |offset, desc: &ResourceDesc, out: &mut This| {
  4275. create_placed(
  4276. null,
  4277. heap,
  4278. offset,
  4279. desc,
  4280. 0,
  4281. null.cast(),
  4282. &RESOURCE_IIDS[0],
  4283. out,
  4284. )
  4285. };
  4286. let mut placed = null;
  4287. assert_eq!(place(KIB_64, &buffer(KIB_64), &mut placed), S_OK);
  4288. // SAFETY: a heap we made.
  4289. let base = unsafe { (*heap.cast::<Heap>()).memory.ptr.as_ptr() } as u64;
  4290. assert_eq!(slot::<Address>(placed, 0x58)(placed), base + KIB_64);
  4291. let mut other = null;
  4292. assert_eq!(
  4293. place(4 * KIB_64, &buffer(1), &mut other),
  4294. E_INVALIDARG,
  4295. "past the end"
  4296. );
  4297. assert_eq!(
  4298. place(100, &buffer(1), &mut other),
  4299. E_INVALIDARG,
  4300. "misaligned"
  4301. );
  4302. // The resource keeps the heap alive.
  4303. assert_eq!(slot::<Release>(heap, 0x10)(heap), 1);
  4304. assert_eq!(slot::<Release>(placed, 0x10)(placed), 0);
  4305. }
  4306. #[test]
  4307. fn texture_floor_scales_with_vram_budget() {
  4308. const GIB: u64 = 1 << 30;
  4309. assert_eq!(texture_floor_bytes(None), 2 * GIB);
  4310. assert_eq!(texture_floor_bytes(Some(4 * GIB)), GIB);
  4311. assert_eq!(texture_floor_bytes(Some(6 * GIB)), 6 * GIB / 4);
  4312. assert_eq!(texture_floor_bytes(Some(8 * GIB)), 2 * GIB);
  4313. assert_eq!(texture_floor_bytes(Some(12 * GIB)), 2 * GIB);
  4314. assert_eq!(texture_floor_bytes(Some(24 * GIB)), 2 * GIB);
  4315. assert_eq!(texture_floor_bytes(Some(32 * GIB)), 2 * GIB);
  4316. }
  4317. /// A placed texture viewed from a later level has a host copy of that
  4318. /// and the smaller levels; a view from an earlier one gets another.
  4319. #[cfg(windows)]
  4320. #[test]
  4321. fn a_placed_texture_is_kept_from_the_level_viewed() {
  4322. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
  4323. if crate::host::host().is_none() || !held_only() {
  4324. return;
  4325. }
  4326. // 256x256 BC7, nine levels, 4 KiB blocks.
  4327. let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0];
  4328. let whole = placed_bytes(&desc).unwrap();
  4329. let part = placed_bytes_from(&desc, 2).unwrap();
  4330. assert!(part * 8 < whole, "{part} of {whole}");
  4331. assert_eq!(placed_bytes_from(&desc, 0), Some(whole));
  4332. // SAFETY: memory of our own that stays.
  4333. let at = unsafe { VirtualAlloc(std::ptr::null(), whole as usize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
  4334. let texture = texture_at(at as u64, &desc).unwrap();
  4335. want_level(texture, 2);
  4336. let copy = host_copy(texture).unwrap();
  4337. // SAFETY: a live texture.
  4338. let d = unsafe { copy.texture.GetDesc() };
  4339. assert_eq!((copy.base, d.Width, d.Height, d.MipLevels), (2, 64, 64, 7));
  4340. want_level(texture, 5);
  4341. assert_eq!(host_copy(texture).unwrap().serial, copy.serial);
  4342. want_level(texture, 0);
  4343. let more = host_copy(texture).unwrap();
  4344. // SAFETY: as above.
  4345. let d = unsafe { more.texture.GetDesc() };
  4346. assert_eq!((more.base, d.Width, d.MipLevels), (0, 256, 9));
  4347. assert!(more.serial != copy.serial && more.grown.load(std::sync::atomic::Ordering::Relaxed));
  4348. }
  4349. }