resource.rs 167 KB

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