resource.rs 155 KB

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