texture_cache.h 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284
  1. // SPDX-FileCopyrightText: 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-3.0-or-later
  3. #pragma once
  4. #include <unordered_set>
  5. #include "common/alignment.h"
  6. #include "common/settings.h"
  7. #include "video_core/control/channel_state.h"
  8. #include "video_core/dirty_flags.h"
  9. #include "video_core/engines/kepler_compute.h"
  10. #include "video_core/texture_cache/image_view_base.h"
  11. #include "video_core/texture_cache/samples_helper.h"
  12. #include "video_core/texture_cache/texture_cache_base.h"
  13. #include "video_core/texture_cache/util.h"
  14. namespace VideoCommon {
  15. using Tegra::Texture::SwizzleSource;
  16. using Tegra::Texture::TextureType;
  17. using Tegra::Texture::TICEntry;
  18. using Tegra::Texture::TSCEntry;
  19. using VideoCore::Surface::GetFormatType;
  20. using VideoCore::Surface::IsCopyCompatible;
  21. using VideoCore::Surface::PixelFormat;
  22. using VideoCore::Surface::PixelFormatFromDepthFormat;
  23. using VideoCore::Surface::PixelFormatFromRenderTargetFormat;
  24. using VideoCore::Surface::SurfaceType;
  25. using namespace Common::Literals;
  26. template <class P>
  27. TextureCache<P>::TextureCache(Runtime& runtime_, VideoCore::RasterizerInterface& rasterizer_)
  28. : runtime{runtime_}, rasterizer{rasterizer_} {
  29. // Configure null sampler
  30. TSCEntry sampler_descriptor{};
  31. sampler_descriptor.min_filter.Assign(Tegra::Texture::TextureFilter::Linear);
  32. sampler_descriptor.mag_filter.Assign(Tegra::Texture::TextureFilter::Linear);
  33. sampler_descriptor.mipmap_filter.Assign(Tegra::Texture::TextureMipmapFilter::Linear);
  34. sampler_descriptor.cubemap_anisotropy.Assign(1);
  35. // These values were chosen based on typical peak swizzle data sizes seen in some titles
  36. static constexpr size_t SWIZZLE_DATA_BUFFER_INITIAL_CAPACITY = 8_MiB;
  37. static constexpr size_t UNSWIZZLE_DATA_BUFFER_INITIAL_CAPACITY = 1_MiB;
  38. swizzle_data_buffer.resize_destructive(SWIZZLE_DATA_BUFFER_INITIAL_CAPACITY);
  39. unswizzle_data_buffer.resize_destructive(UNSWIZZLE_DATA_BUFFER_INITIAL_CAPACITY);
  40. // Make sure the first index is reserved for the null resources
  41. // This way the null resource becomes a compile time constant
  42. void(slot_images.insert(NullImageParams{}));
  43. void(slot_image_views.insert(runtime, NullImageViewParams{}));
  44. void(slot_samplers.insert(runtime, sampler_descriptor));
  45. if constexpr (HAS_DEVICE_MEMORY_INFO) {
  46. const s64 device_memory = static_cast<s64>(runtime.GetDeviceLocalMemory());
  47. const s64 min_spacing_expected = device_memory - 1_GiB - 512_MiB;
  48. const s64 min_spacing_critical = device_memory - 1_GiB;
  49. const s64 mem_threshold = std::min(device_memory, TARGET_THRESHOLD);
  50. const s64 min_vacancy_expected = (6 * mem_threshold) / 10;
  51. const s64 min_vacancy_critical = (3 * mem_threshold) / 10;
  52. expected_memory = static_cast<u64>(
  53. std::max(std::min(device_memory - min_vacancy_expected, min_spacing_expected),
  54. DEFAULT_EXPECTED_MEMORY));
  55. critical_memory = static_cast<u64>(
  56. std::max(std::min(device_memory - min_vacancy_critical, min_spacing_critical),
  57. DEFAULT_CRITICAL_MEMORY));
  58. minimum_memory = static_cast<u64>((device_memory - mem_threshold) / 2);
  59. } else {
  60. expected_memory = DEFAULT_EXPECTED_MEMORY + 512_MiB;
  61. critical_memory = DEFAULT_CRITICAL_MEMORY + 1_GiB;
  62. minimum_memory = 0;
  63. }
  64. }
  65. template <class P>
  66. void TextureCache<P>::RunGarbageCollector() {
  67. bool high_priority_mode = total_used_memory >= expected_memory;
  68. bool aggressive_mode = total_used_memory >= critical_memory;
  69. const u64 ticks_to_destroy = aggressive_mode ? 10ULL : high_priority_mode ? 25ULL : 50ULL;
  70. size_t num_iterations = aggressive_mode ? 40 : (high_priority_mode ? 20 : 10);
  71. const auto clean_up = [this, &num_iterations, &high_priority_mode,
  72. &aggressive_mode](ImageId image_id) {
  73. if (num_iterations == 0) {
  74. return true;
  75. }
  76. --num_iterations;
  77. auto& image = slot_images[image_id];
  78. if (True(image.flags & ImageFlagBits::IsDecoding)) {
  79. // This image is still being decoded, deleting it will invalidate the slot
  80. // used by the async decoder thread.
  81. return false;
  82. }
  83. const bool must_download =
  84. image.IsSafeDownload() && False(image.flags & ImageFlagBits::BadOverlap);
  85. if (!high_priority_mode &&
  86. (must_download || True(image.flags & ImageFlagBits::CostlyLoad))) {
  87. return false;
  88. }
  89. if (must_download) {
  90. auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes);
  91. const auto copies = FullDownloadCopies(image.info);
  92. image.DownloadMemory(map, copies);
  93. runtime.Finish();
  94. SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span,
  95. swizzle_data_buffer);
  96. }
  97. if (True(image.flags & ImageFlagBits::Tracked)) {
  98. UntrackImage(image, image_id);
  99. }
  100. UnregisterImage(image_id);
  101. DeleteImage(image_id, image.scale_tick > frame_tick + 5);
  102. if (total_used_memory < critical_memory) {
  103. if (aggressive_mode) {
  104. // Sink the aggresiveness.
  105. num_iterations >>= 2;
  106. aggressive_mode = false;
  107. return false;
  108. }
  109. if (high_priority_mode && total_used_memory < expected_memory) {
  110. num_iterations >>= 1;
  111. high_priority_mode = false;
  112. }
  113. }
  114. return false;
  115. };
  116. lru_cache.ForEachItemBelow(frame_tick - ticks_to_destroy, clean_up);
  117. }
  118. template <class P>
  119. void TextureCache<P>::TickFrame() {
  120. // If we can obtain the memory info, use it instead of the estimate.
  121. if (runtime.CanReportMemoryUsage()) {
  122. total_used_memory = runtime.GetDeviceMemoryUsage();
  123. }
  124. if (total_used_memory > minimum_memory) {
  125. RunGarbageCollector();
  126. }
  127. sentenced_images.Tick();
  128. sentenced_framebuffers.Tick();
  129. sentenced_image_view.Tick();
  130. TickAsyncDecode();
  131. runtime.TickFrame();
  132. critical_gc = 0;
  133. ++frame_tick;
  134. }
  135. template <class P>
  136. const typename P::ImageView& TextureCache<P>::GetImageView(ImageViewId id) const noexcept {
  137. return slot_image_views[id];
  138. }
  139. template <class P>
  140. typename P::ImageView& TextureCache<P>::GetImageView(ImageViewId id) noexcept {
  141. return slot_image_views[id];
  142. }
  143. template <class P>
  144. typename P::ImageView& TextureCache<P>::GetImageView(u32 index) noexcept {
  145. const auto image_view_id = VisitImageView(channel_state->graphics_image_table,
  146. channel_state->graphics_image_view_ids, index);
  147. return slot_image_views[image_view_id];
  148. }
  149. template <class P>
  150. void TextureCache<P>::MarkModification(ImageId id) noexcept {
  151. MarkModification(slot_images[id]);
  152. }
  153. template <class P>
  154. template <bool has_blacklists>
  155. void TextureCache<P>::FillGraphicsImageViews(std::span<ImageViewInOut> views) {
  156. FillImageViews<has_blacklists>(channel_state->graphics_image_table,
  157. channel_state->graphics_image_view_ids, views);
  158. }
  159. template <class P>
  160. void TextureCache<P>::FillComputeImageViews(std::span<ImageViewInOut> views) {
  161. FillImageViews<true>(channel_state->compute_image_table, channel_state->compute_image_view_ids,
  162. views);
  163. }
  164. template <class P>
  165. typename P::Sampler* TextureCache<P>::GetGraphicsSampler(u32 index) {
  166. if (index > channel_state->graphics_sampler_table.Limit()) {
  167. LOG_DEBUG(HW_GPU, "Invalid sampler index={}", index);
  168. return &slot_samplers[NULL_SAMPLER_ID];
  169. }
  170. const auto [descriptor, is_new] = channel_state->graphics_sampler_table.Read(index);
  171. SamplerId& id = channel_state->graphics_sampler_ids[index];
  172. if (is_new) {
  173. id = FindSampler(descriptor);
  174. }
  175. return &slot_samplers[id];
  176. }
  177. template <class P>
  178. typename P::Sampler* TextureCache<P>::GetComputeSampler(u32 index) {
  179. if (index > channel_state->compute_sampler_table.Limit()) {
  180. LOG_DEBUG(HW_GPU, "Invalid sampler index={}", index);
  181. return &slot_samplers[NULL_SAMPLER_ID];
  182. }
  183. const auto [descriptor, is_new] = channel_state->compute_sampler_table.Read(index);
  184. SamplerId& id = channel_state->compute_sampler_ids[index];
  185. if (is_new) {
  186. id = FindSampler(descriptor);
  187. }
  188. return &slot_samplers[id];
  189. }
  190. template <class P>
  191. void TextureCache<P>::SynchronizeGraphicsDescriptors() {
  192. using SamplerBinding = Tegra::Engines::Maxwell3D::Regs::SamplerBinding;
  193. const bool linked_tsc = maxwell3d->regs.sampler_binding == SamplerBinding::ViaHeaderBinding;
  194. const u32 tic_limit = maxwell3d->regs.tex_header.limit;
  195. const u32 tsc_limit = linked_tsc ? tic_limit : maxwell3d->regs.tex_sampler.limit;
  196. if (channel_state->graphics_sampler_table.Synchronize(maxwell3d->regs.tex_sampler.Address(),
  197. tsc_limit)) {
  198. channel_state->graphics_sampler_ids.resize(tsc_limit + 1, CORRUPT_ID);
  199. }
  200. if (channel_state->graphics_image_table.Synchronize(maxwell3d->regs.tex_header.Address(),
  201. tic_limit)) {
  202. channel_state->graphics_image_view_ids.resize(tic_limit + 1, CORRUPT_ID);
  203. }
  204. }
  205. template <class P>
  206. void TextureCache<P>::SynchronizeComputeDescriptors() {
  207. const bool linked_tsc = kepler_compute->launch_description.linked_tsc;
  208. const u32 tic_limit = kepler_compute->regs.tic.limit;
  209. const u32 tsc_limit = linked_tsc ? tic_limit : kepler_compute->regs.tsc.limit;
  210. const GPUVAddr tsc_gpu_addr = kepler_compute->regs.tsc.Address();
  211. if (channel_state->compute_sampler_table.Synchronize(tsc_gpu_addr, tsc_limit)) {
  212. channel_state->compute_sampler_ids.resize(tsc_limit + 1, CORRUPT_ID);
  213. }
  214. if (channel_state->compute_image_table.Synchronize(kepler_compute->regs.tic.Address(),
  215. tic_limit)) {
  216. channel_state->compute_image_view_ids.resize(tic_limit + 1, CORRUPT_ID);
  217. }
  218. }
  219. template <class P>
  220. bool TextureCache<P>::RescaleRenderTargets(bool is_clear) {
  221. auto& flags = maxwell3d->dirty.flags;
  222. u32 scale_rating = 0;
  223. bool rescaled = false;
  224. std::array<ImageId, NUM_RT> tmp_color_images{};
  225. ImageId tmp_depth_image{};
  226. do {
  227. flags[Dirty::RenderTargets] = false;
  228. has_deleted_images = false;
  229. // Render target control is used on all render targets, so force look ups when this one is
  230. // up
  231. const bool force = flags[Dirty::RenderTargetControl];
  232. flags[Dirty::RenderTargetControl] = false;
  233. scale_rating = 0;
  234. bool any_rescaled = false;
  235. bool can_rescale = true;
  236. const auto check_rescale = [&](ImageViewId view_id, ImageId& id_save) {
  237. if (view_id != NULL_IMAGE_VIEW_ID && view_id != ImageViewId{}) {
  238. const auto& view = slot_image_views[view_id];
  239. const auto image_id = view.image_id;
  240. id_save = image_id;
  241. auto& image = slot_images[image_id];
  242. can_rescale &= ImageCanRescale(image);
  243. any_rescaled |= True(image.flags & ImageFlagBits::Rescaled) ||
  244. GetFormatType(image.info.format) != SurfaceType::ColorTexture;
  245. scale_rating = std::max<u32>(scale_rating, image.scale_tick <= frame_tick
  246. ? image.scale_rating + 1U
  247. : image.scale_rating);
  248. } else {
  249. id_save = CORRUPT_ID;
  250. }
  251. };
  252. for (size_t index = 0; index < NUM_RT; ++index) {
  253. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  254. if (flags[Dirty::ColorBuffer0 + index] || force) {
  255. flags[Dirty::ColorBuffer0 + index] = false;
  256. BindRenderTarget(&color_buffer_id, FindColorBuffer(index, is_clear));
  257. }
  258. check_rescale(color_buffer_id, tmp_color_images[index]);
  259. }
  260. if (flags[Dirty::ZetaBuffer] || force) {
  261. flags[Dirty::ZetaBuffer] = false;
  262. BindRenderTarget(&render_targets.depth_buffer_id, FindDepthBuffer(is_clear));
  263. }
  264. check_rescale(render_targets.depth_buffer_id, tmp_depth_image);
  265. if (can_rescale) {
  266. rescaled = any_rescaled || scale_rating >= 2;
  267. const auto scale_up = [this](ImageId image_id) {
  268. if (image_id != CORRUPT_ID) {
  269. Image& image = slot_images[image_id];
  270. ScaleUp(image);
  271. }
  272. };
  273. if (rescaled) {
  274. for (size_t index = 0; index < NUM_RT; ++index) {
  275. scale_up(tmp_color_images[index]);
  276. }
  277. scale_up(tmp_depth_image);
  278. scale_rating = 2;
  279. }
  280. } else {
  281. rescaled = false;
  282. const auto scale_down = [this](ImageId image_id) {
  283. if (image_id != CORRUPT_ID) {
  284. Image& image = slot_images[image_id];
  285. ScaleDown(image);
  286. }
  287. };
  288. for (size_t index = 0; index < NUM_RT; ++index) {
  289. scale_down(tmp_color_images[index]);
  290. }
  291. scale_down(tmp_depth_image);
  292. scale_rating = 1;
  293. }
  294. } while (has_deleted_images);
  295. const auto set_rating = [this, scale_rating](ImageId image_id) {
  296. if (image_id != CORRUPT_ID) {
  297. Image& image = slot_images[image_id];
  298. image.scale_rating = scale_rating;
  299. if (image.scale_tick <= frame_tick) {
  300. image.scale_tick = frame_tick + 1;
  301. }
  302. }
  303. };
  304. for (size_t index = 0; index < NUM_RT; ++index) {
  305. set_rating(tmp_color_images[index]);
  306. }
  307. set_rating(tmp_depth_image);
  308. return rescaled;
  309. }
  310. template <class P>
  311. void TextureCache<P>::UpdateRenderTargets(bool is_clear) {
  312. using namespace VideoCommon::Dirty;
  313. auto& flags = maxwell3d->dirty.flags;
  314. if (!flags[Dirty::RenderTargets]) {
  315. for (size_t index = 0; index < NUM_RT; ++index) {
  316. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  317. PrepareImageView(color_buffer_id, true, is_clear && IsFullClear(color_buffer_id));
  318. }
  319. const ImageViewId depth_buffer_id = render_targets.depth_buffer_id;
  320. PrepareImageView(depth_buffer_id, true, is_clear && IsFullClear(depth_buffer_id));
  321. return;
  322. }
  323. const bool rescaled = RescaleRenderTargets(is_clear);
  324. if (is_rescaling != rescaled) {
  325. flags[Dirty::RescaleViewports] = true;
  326. flags[Dirty::RescaleScissors] = true;
  327. is_rescaling = rescaled;
  328. }
  329. for (size_t index = 0; index < NUM_RT; ++index) {
  330. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  331. PrepareImageView(color_buffer_id, true, is_clear && IsFullClear(color_buffer_id));
  332. }
  333. const ImageViewId depth_buffer_id = render_targets.depth_buffer_id;
  334. PrepareImageView(depth_buffer_id, true, is_clear && IsFullClear(depth_buffer_id));
  335. for (size_t index = 0; index < NUM_RT; ++index) {
  336. render_targets.draw_buffers[index] = static_cast<u8>(maxwell3d->regs.rt_control.Map(index));
  337. }
  338. u32 up_scale = 1;
  339. u32 down_shift = 0;
  340. if (is_rescaling) {
  341. up_scale = Settings::values.resolution_info.up_scale;
  342. down_shift = Settings::values.resolution_info.down_shift;
  343. }
  344. render_targets.size = Extent2D{
  345. (maxwell3d->regs.surface_clip.width * up_scale) >> down_shift,
  346. (maxwell3d->regs.surface_clip.height * up_scale) >> down_shift,
  347. };
  348. render_targets.is_rescaled = is_rescaling;
  349. flags[Dirty::DepthBiasGlobal] = true;
  350. }
  351. template <class P>
  352. typename P::Framebuffer* TextureCache<P>::GetFramebuffer() {
  353. return &slot_framebuffers[GetFramebufferId(render_targets)];
  354. }
  355. template <class P>
  356. template <bool has_blacklists>
  357. void TextureCache<P>::FillImageViews(DescriptorTable<TICEntry>& table,
  358. std::span<ImageViewId> cached_image_view_ids,
  359. std::span<ImageViewInOut> views) {
  360. bool has_blacklisted = false;
  361. do {
  362. has_deleted_images = false;
  363. if constexpr (has_blacklists) {
  364. has_blacklisted = false;
  365. }
  366. for (ImageViewInOut& view : views) {
  367. view.id = VisitImageView(table, cached_image_view_ids, view.index);
  368. if constexpr (has_blacklists) {
  369. if (view.blacklist && view.id != NULL_IMAGE_VIEW_ID) {
  370. const ImageViewBase& image_view{slot_image_views[view.id]};
  371. auto& image = slot_images[image_view.image_id];
  372. has_blacklisted |= ScaleDown(image);
  373. image.scale_rating = 0;
  374. }
  375. }
  376. }
  377. } while (has_deleted_images || (has_blacklists && has_blacklisted));
  378. }
  379. template <class P>
  380. ImageViewId TextureCache<P>::VisitImageView(DescriptorTable<TICEntry>& table,
  381. std::span<ImageViewId> cached_image_view_ids,
  382. u32 index) {
  383. if (index > table.Limit()) {
  384. LOG_DEBUG(HW_GPU, "Invalid image view index={}", index);
  385. return NULL_IMAGE_VIEW_ID;
  386. }
  387. const auto [descriptor, is_new] = table.Read(index);
  388. ImageViewId& image_view_id = cached_image_view_ids[index];
  389. if (is_new) {
  390. image_view_id = FindImageView(descriptor);
  391. }
  392. if (image_view_id != NULL_IMAGE_VIEW_ID) {
  393. PrepareImageView(image_view_id, false, false);
  394. }
  395. return image_view_id;
  396. }
  397. template <class P>
  398. FramebufferId TextureCache<P>::GetFramebufferId(const RenderTargets& key) {
  399. const auto [pair, is_new] = framebuffers.try_emplace(key);
  400. FramebufferId& framebuffer_id = pair->second;
  401. if (!is_new) {
  402. return framebuffer_id;
  403. }
  404. std::array<ImageView*, NUM_RT> color_buffers;
  405. std::ranges::transform(key.color_buffer_ids, color_buffers.begin(),
  406. [this](ImageViewId id) { return id ? &slot_image_views[id] : nullptr; });
  407. ImageView* const depth_buffer =
  408. key.depth_buffer_id ? &slot_image_views[key.depth_buffer_id] : nullptr;
  409. framebuffer_id = slot_framebuffers.insert(runtime, color_buffers, depth_buffer, key);
  410. return framebuffer_id;
  411. }
  412. template <class P>
  413. void TextureCache<P>::WriteMemory(VAddr cpu_addr, size_t size) {
  414. ForEachImageInRegion(cpu_addr, size, [this](ImageId image_id, Image& image) {
  415. if (True(image.flags & ImageFlagBits::CpuModified)) {
  416. return;
  417. }
  418. image.flags |= ImageFlagBits::CpuModified;
  419. if (True(image.flags & ImageFlagBits::Tracked)) {
  420. UntrackImage(image, image_id);
  421. }
  422. });
  423. }
  424. template <class P>
  425. void TextureCache<P>::DownloadMemory(VAddr cpu_addr, size_t size) {
  426. std::vector<ImageId> images;
  427. ForEachImageInRegion(cpu_addr, size, [&images](ImageId image_id, ImageBase& image) {
  428. if (!image.IsSafeDownload()) {
  429. return;
  430. }
  431. image.flags &= ~ImageFlagBits::GpuModified;
  432. images.push_back(image_id);
  433. });
  434. if (images.empty()) {
  435. return;
  436. }
  437. std::ranges::sort(images, [this](ImageId lhs, ImageId rhs) {
  438. return slot_images[lhs].modification_tick < slot_images[rhs].modification_tick;
  439. });
  440. for (const ImageId image_id : images) {
  441. Image& image = slot_images[image_id];
  442. auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes);
  443. const auto copies = FullDownloadCopies(image.info);
  444. image.DownloadMemory(map, copies);
  445. runtime.Finish();
  446. SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span,
  447. swizzle_data_buffer);
  448. }
  449. }
  450. template <class P>
  451. void TextureCache<P>::UnmapMemory(VAddr cpu_addr, size_t size) {
  452. std::vector<ImageId> deleted_images;
  453. ForEachImageInRegion(cpu_addr, size, [&](ImageId id, Image&) { deleted_images.push_back(id); });
  454. for (const ImageId id : deleted_images) {
  455. Image& image = slot_images[id];
  456. if (True(image.flags & ImageFlagBits::Tracked)) {
  457. UntrackImage(image, id);
  458. }
  459. UnregisterImage(id);
  460. DeleteImage(id);
  461. }
  462. }
  463. template <class P>
  464. void TextureCache<P>::UnmapGPUMemory(size_t as_id, GPUVAddr gpu_addr, size_t size) {
  465. std::vector<ImageId> deleted_images;
  466. ForEachImageInRegionGPU(as_id, gpu_addr, size,
  467. [&](ImageId id, Image&) { deleted_images.push_back(id); });
  468. for (const ImageId id : deleted_images) {
  469. Image& image = slot_images[id];
  470. if (True(image.flags & ImageFlagBits::CpuModified)) {
  471. return;
  472. }
  473. image.flags |= ImageFlagBits::CpuModified;
  474. if (True(image.flags & ImageFlagBits::Tracked)) {
  475. UntrackImage(image, id);
  476. }
  477. /*
  478. if (True(image.flags & ImageFlagBits::Remapped)) {
  479. continue;
  480. }
  481. image.flags |= ImageFlagBits::Remapped;
  482. if (True(image.flags & ImageFlagBits::Tracked)) {
  483. UntrackImage(image, id);
  484. }
  485. */
  486. }
  487. }
  488. template <class P>
  489. bool TextureCache<P>::BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
  490. const Tegra::Engines::Fermi2D::Surface& src,
  491. const Tegra::Engines::Fermi2D::Config& copy) {
  492. const auto result = GetBlitImages(dst, src, copy);
  493. if (!result) {
  494. return false;
  495. }
  496. const BlitImages images = *result;
  497. const ImageId dst_id = images.dst_id;
  498. const ImageId src_id = images.src_id;
  499. PrepareImage(src_id, false, false);
  500. PrepareImage(dst_id, true, false);
  501. Image& dst_image = slot_images[dst_id];
  502. Image& src_image = slot_images[src_id];
  503. bool is_src_rescaled = True(src_image.flags & ImageFlagBits::Rescaled);
  504. bool is_dst_rescaled = True(dst_image.flags & ImageFlagBits::Rescaled);
  505. const bool is_resolve = src_image.info.num_samples != 1 && dst_image.info.num_samples == 1;
  506. if (is_src_rescaled != is_dst_rescaled) {
  507. if (ImageCanRescale(src_image)) {
  508. ScaleUp(src_image);
  509. is_src_rescaled = True(src_image.flags & ImageFlagBits::Rescaled);
  510. if (is_resolve) {
  511. dst_image.info.rescaleable = true;
  512. for (const auto& alias : dst_image.aliased_images) {
  513. Image& other_image = slot_images[alias.id];
  514. other_image.info.rescaleable = true;
  515. }
  516. }
  517. }
  518. if (ImageCanRescale(dst_image)) {
  519. ScaleUp(dst_image);
  520. is_dst_rescaled = True(dst_image.flags & ImageFlagBits::Rescaled);
  521. }
  522. }
  523. if (is_resolve && (is_src_rescaled != is_dst_rescaled)) {
  524. // A resolve requires both images to be the same dimensions. Resize down if needed.
  525. ScaleDown(src_image);
  526. ScaleDown(dst_image);
  527. is_src_rescaled = True(src_image.flags & ImageFlagBits::Rescaled);
  528. is_dst_rescaled = True(dst_image.flags & ImageFlagBits::Rescaled);
  529. }
  530. const auto& resolution = Settings::values.resolution_info;
  531. const auto scale_region = [&](Region2D& region) {
  532. region.start.x = resolution.ScaleUp(region.start.x);
  533. region.start.y = resolution.ScaleUp(region.start.y);
  534. region.end.x = resolution.ScaleUp(region.end.x);
  535. region.end.y = resolution.ScaleUp(region.end.y);
  536. };
  537. // TODO: Deduplicate
  538. const std::optional src_base = src_image.TryFindBase(src.Address());
  539. const SubresourceRange src_range{.base = src_base.value(), .extent = {1, 1}};
  540. const ImageViewInfo src_view_info(ImageViewType::e2D, images.src_format, src_range);
  541. const auto [src_framebuffer_id, src_view_id] = RenderTargetFromImage(src_id, src_view_info);
  542. const auto [src_samples_x, src_samples_y] = SamplesLog2(src_image.info.num_samples);
  543. Region2D src_region{
  544. Offset2D{.x = copy.src_x0 >> src_samples_x, .y = copy.src_y0 >> src_samples_y},
  545. Offset2D{.x = copy.src_x1 >> src_samples_x, .y = copy.src_y1 >> src_samples_y},
  546. };
  547. if (is_src_rescaled) {
  548. scale_region(src_region);
  549. }
  550. const std::optional dst_base = dst_image.TryFindBase(dst.Address());
  551. const SubresourceRange dst_range{.base = dst_base.value(), .extent = {1, 1}};
  552. const ImageViewInfo dst_view_info(ImageViewType::e2D, images.dst_format, dst_range);
  553. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  554. const auto [dst_samples_x, dst_samples_y] = SamplesLog2(dst_image.info.num_samples);
  555. Region2D dst_region{
  556. Offset2D{.x = copy.dst_x0 >> dst_samples_x, .y = copy.dst_y0 >> dst_samples_y},
  557. Offset2D{.x = copy.dst_x1 >> dst_samples_x, .y = copy.dst_y1 >> dst_samples_y},
  558. };
  559. if (is_dst_rescaled) {
  560. scale_region(dst_region);
  561. }
  562. // Always call this after src_framebuffer_id was queried, as the address might be invalidated.
  563. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  564. if constexpr (FRAMEBUFFER_BLITS) {
  565. // OpenGL blits from framebuffers, not images
  566. Framebuffer* const src_framebuffer = &slot_framebuffers[src_framebuffer_id];
  567. runtime.BlitFramebuffer(dst_framebuffer, src_framebuffer, dst_region, src_region,
  568. copy.filter, copy.operation);
  569. } else {
  570. // Vulkan can blit images, but it lacks format reinterpretations
  571. // Provide a framebuffer in case it's necessary
  572. ImageView& dst_view = slot_image_views[dst_view_id];
  573. ImageView& src_view = slot_image_views[src_view_id];
  574. runtime.BlitImage(dst_framebuffer, dst_view, src_view, dst_region, src_region, copy.filter,
  575. copy.operation);
  576. }
  577. return true;
  578. }
  579. template <class P>
  580. typename P::ImageView* TextureCache<P>::TryFindFramebufferImageView(VAddr cpu_addr) {
  581. // TODO: Properly implement this
  582. const auto it = page_table.find(cpu_addr >> YUZU_PAGEBITS);
  583. if (it == page_table.end()) {
  584. return nullptr;
  585. }
  586. const auto& image_map_ids = it->second;
  587. for (const ImageMapId map_id : image_map_ids) {
  588. const ImageMapView& map = slot_map_views[map_id];
  589. const ImageBase& image = slot_images[map.image_id];
  590. if (image.cpu_addr != cpu_addr) {
  591. continue;
  592. }
  593. if (image.image_view_ids.empty()) {
  594. continue;
  595. }
  596. return &slot_image_views[image.image_view_ids.at(0)];
  597. }
  598. return nullptr;
  599. }
  600. template <class P>
  601. bool TextureCache<P>::HasUncommittedFlushes() const noexcept {
  602. return !uncommitted_downloads.empty();
  603. }
  604. template <class P>
  605. bool TextureCache<P>::ShouldWaitAsyncFlushes() const noexcept {
  606. return !committed_downloads.empty() && !committed_downloads.front().empty();
  607. }
  608. template <class P>
  609. void TextureCache<P>::CommitAsyncFlushes() {
  610. // This is intentionally passing the value by copy
  611. if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
  612. const std::span<const ImageId> download_ids = uncommitted_downloads;
  613. if (download_ids.empty()) {
  614. committed_downloads.emplace_back(std::move(uncommitted_downloads));
  615. uncommitted_downloads.clear();
  616. async_buffers.emplace_back(std::optional<AsyncBuffer>{});
  617. return;
  618. }
  619. size_t total_size_bytes = 0;
  620. for (const ImageId image_id : download_ids) {
  621. total_size_bytes += slot_images[image_id].unswizzled_size_bytes;
  622. }
  623. auto download_map = runtime.DownloadStagingBuffer(total_size_bytes, true);
  624. for (const ImageId image_id : download_ids) {
  625. Image& image = slot_images[image_id];
  626. const auto copies = FullDownloadCopies(image.info);
  627. image.DownloadMemory(download_map, copies);
  628. download_map.offset += Common::AlignUp(image.unswizzled_size_bytes, 64);
  629. }
  630. async_buffers.emplace_back(download_map);
  631. }
  632. committed_downloads.emplace_back(std::move(uncommitted_downloads));
  633. uncommitted_downloads.clear();
  634. }
  635. template <class P>
  636. void TextureCache<P>::PopAsyncFlushes() {
  637. if (committed_downloads.empty()) {
  638. return;
  639. }
  640. if constexpr (IMPLEMENTS_ASYNC_DOWNLOADS) {
  641. const std::span<const ImageId> download_ids = committed_downloads.front();
  642. if (download_ids.empty()) {
  643. committed_downloads.pop_front();
  644. async_buffers.pop_front();
  645. return;
  646. }
  647. auto download_map = *async_buffers.front();
  648. std::span<u8> download_span = download_map.mapped_span;
  649. for (size_t i = download_ids.size(); i > 0; i--) {
  650. const ImageBase& image = slot_images[download_ids[i - 1]];
  651. const auto copies = FullDownloadCopies(image.info);
  652. download_map.offset -= Common::AlignUp(image.unswizzled_size_bytes, 64);
  653. std::span<u8> download_span_alt = download_span.subspan(download_map.offset);
  654. SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, download_span_alt,
  655. swizzle_data_buffer);
  656. }
  657. runtime.FreeDeferredStagingBuffer(download_map);
  658. committed_downloads.pop_front();
  659. async_buffers.pop_front();
  660. } else {
  661. const std::span<const ImageId> download_ids = committed_downloads.front();
  662. if (download_ids.empty()) {
  663. committed_downloads.pop_front();
  664. return;
  665. }
  666. size_t total_size_bytes = 0;
  667. for (const ImageId image_id : download_ids) {
  668. total_size_bytes += slot_images[image_id].unswizzled_size_bytes;
  669. }
  670. auto download_map = runtime.DownloadStagingBuffer(total_size_bytes);
  671. const size_t original_offset = download_map.offset;
  672. for (const ImageId image_id : download_ids) {
  673. Image& image = slot_images[image_id];
  674. const auto copies = FullDownloadCopies(image.info);
  675. image.DownloadMemory(download_map, copies);
  676. download_map.offset += image.unswizzled_size_bytes;
  677. }
  678. // Wait for downloads to finish
  679. runtime.Finish();
  680. download_map.offset = original_offset;
  681. std::span<u8> download_span = download_map.mapped_span;
  682. for (const ImageId image_id : download_ids) {
  683. const ImageBase& image = slot_images[image_id];
  684. const auto copies = FullDownloadCopies(image.info);
  685. SwizzleImage(*gpu_memory, image.gpu_addr, image.info, copies, download_span,
  686. swizzle_data_buffer);
  687. download_map.offset += image.unswizzled_size_bytes;
  688. download_span = download_span.subspan(image.unswizzled_size_bytes);
  689. }
  690. committed_downloads.pop_front();
  691. }
  692. }
  693. template <class P>
  694. ImageId TextureCache<P>::DmaImageId(const Tegra::DMA::ImageOperand& operand) {
  695. const ImageInfo dst_info(operand);
  696. const ImageId dst_id = FindDMAImage(dst_info, operand.address);
  697. if (!dst_id) {
  698. return NULL_IMAGE_ID;
  699. }
  700. const auto& image = slot_images[dst_id];
  701. if (False(image.flags & ImageFlagBits::GpuModified)) {
  702. // No need to waste time on an image that's synced with guest
  703. return NULL_IMAGE_ID;
  704. }
  705. const auto base = image.TryFindBase(operand.address);
  706. if (!base) {
  707. return NULL_IMAGE_ID;
  708. }
  709. return dst_id;
  710. }
  711. template <class P>
  712. bool TextureCache<P>::IsRescaling() const noexcept {
  713. return is_rescaling;
  714. }
  715. template <class P>
  716. bool TextureCache<P>::IsRescaling(const ImageViewBase& image_view) const noexcept {
  717. if (image_view.type == ImageViewType::Buffer) {
  718. return false;
  719. }
  720. const ImageBase& image = slot_images[image_view.image_id];
  721. return True(image.flags & ImageFlagBits::Rescaled);
  722. }
  723. template <class P>
  724. bool TextureCache<P>::IsRegionGpuModified(VAddr addr, size_t size) {
  725. bool is_modified = false;
  726. ForEachImageInRegion(addr, size, [&is_modified](ImageId, ImageBase& image) {
  727. if (False(image.flags & ImageFlagBits::GpuModified)) {
  728. return false;
  729. }
  730. is_modified = true;
  731. return true;
  732. });
  733. return is_modified;
  734. }
  735. template <class P>
  736. std::pair<typename TextureCache<P>::Image*, BufferImageCopy> TextureCache<P>::DmaBufferImageCopy(
  737. const Tegra::DMA::ImageCopy& copy_info, const Tegra::DMA::BufferOperand& buffer_operand,
  738. const Tegra::DMA::ImageOperand& image_operand, ImageId image_id, bool modifies_image) {
  739. const auto [level, base] = PrepareDmaImage(image_id, image_operand.address, modifies_image);
  740. auto* image = &slot_images[image_id];
  741. const u32 buffer_size = static_cast<u32>(buffer_operand.pitch * buffer_operand.height);
  742. const u32 bpp = VideoCore::Surface::BytesPerBlock(image->info.format);
  743. const auto convert = [old_bpp = image_operand.bytes_per_pixel, bpp](u32 value) {
  744. return (old_bpp * value) / bpp;
  745. };
  746. const u32 base_x = convert(image_operand.params.origin.x.Value());
  747. const u32 base_y = image_operand.params.origin.y.Value();
  748. const u32 length_x = convert(copy_info.length_x);
  749. const u32 length_y = copy_info.length_y;
  750. const BufferImageCopy copy{
  751. .buffer_offset = 0,
  752. .buffer_size = buffer_size,
  753. .buffer_row_length = convert(buffer_operand.pitch),
  754. .buffer_image_height = buffer_operand.height,
  755. .image_subresource =
  756. {
  757. .base_level = static_cast<s32>(level),
  758. .base_layer = static_cast<s32>(base),
  759. .num_layers = 1,
  760. },
  761. .image_offset =
  762. {
  763. .x = static_cast<s32>(base_x),
  764. .y = static_cast<s32>(base_y),
  765. .z = 0,
  766. },
  767. .image_extent =
  768. {
  769. .width = length_x,
  770. .height = length_y,
  771. .depth = 1,
  772. },
  773. };
  774. return {image, copy};
  775. }
  776. template <class P>
  777. void TextureCache<P>::RefreshContents(Image& image, ImageId image_id) {
  778. if (False(image.flags & ImageFlagBits::CpuModified)) {
  779. // Only upload modified images
  780. return;
  781. }
  782. image.flags &= ~ImageFlagBits::CpuModified;
  783. TrackImage(image, image_id);
  784. if (image.info.num_samples > 1 && !runtime.CanUploadMSAA()) {
  785. LOG_WARNING(HW_GPU, "MSAA image uploads are not implemented");
  786. return;
  787. }
  788. if (True(image.flags & ImageFlagBits::AsynchronousDecode)) {
  789. QueueAsyncDecode(image, image_id);
  790. return;
  791. }
  792. auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image));
  793. UploadImageContents(image, staging);
  794. runtime.InsertUploadMemoryBarrier();
  795. }
  796. template <class P>
  797. template <typename StagingBuffer>
  798. void TextureCache<P>::UploadImageContents(Image& image, StagingBuffer& staging) {
  799. const std::span<u8> mapped_span = staging.mapped_span;
  800. const GPUVAddr gpu_addr = image.gpu_addr;
  801. if (True(image.flags & ImageFlagBits::AcceleratedUpload)) {
  802. gpu_memory->ReadBlock(gpu_addr, mapped_span.data(), mapped_span.size_bytes(),
  803. VideoCommon::CacheType::NoTextureCache);
  804. const auto uploads = FullUploadSwizzles(image.info);
  805. runtime.AccelerateImageUpload(image, staging, uploads);
  806. return;
  807. }
  808. const size_t guest_size_bytes = image.guest_size_bytes;
  809. swizzle_data_buffer.resize_destructive(guest_size_bytes);
  810. gpu_memory->ReadBlockUnsafe(gpu_addr, swizzle_data_buffer.data(), guest_size_bytes);
  811. if (True(image.flags & ImageFlagBits::Converted)) {
  812. unswizzle_data_buffer.resize_destructive(image.unswizzled_size_bytes);
  813. auto copies = UnswizzleImage(*gpu_memory, gpu_addr, image.info, swizzle_data_buffer,
  814. unswizzle_data_buffer);
  815. ConvertImage(unswizzle_data_buffer, image.info, mapped_span, copies);
  816. image.UploadMemory(staging, copies);
  817. } else {
  818. const auto copies =
  819. UnswizzleImage(*gpu_memory, gpu_addr, image.info, swizzle_data_buffer, mapped_span);
  820. image.UploadMemory(staging, copies);
  821. }
  822. }
  823. template <class P>
  824. ImageViewId TextureCache<P>::FindImageView(const TICEntry& config) {
  825. if (!IsValidEntry(*gpu_memory, config)) {
  826. return NULL_IMAGE_VIEW_ID;
  827. }
  828. const auto [pair, is_new] = channel_state->image_views.try_emplace(config);
  829. ImageViewId& image_view_id = pair->second;
  830. if (is_new) {
  831. image_view_id = CreateImageView(config);
  832. }
  833. return image_view_id;
  834. }
  835. template <class P>
  836. ImageViewId TextureCache<P>::CreateImageView(const TICEntry& config) {
  837. const ImageInfo info(config);
  838. if (info.type == ImageType::Buffer) {
  839. const ImageViewInfo view_info(config, 0);
  840. return slot_image_views.insert(runtime, info, view_info, config.Address());
  841. }
  842. const u32 layer_offset = config.BaseLayer() * info.layer_stride;
  843. const GPUVAddr image_gpu_addr = config.Address() - layer_offset;
  844. const ImageId image_id = FindOrInsertImage(info, image_gpu_addr);
  845. if (!image_id) {
  846. return NULL_IMAGE_VIEW_ID;
  847. }
  848. ImageBase& image = slot_images[image_id];
  849. const SubresourceBase base = image.TryFindBase(config.Address()).value();
  850. ASSERT(base.level == 0);
  851. const ImageViewInfo view_info(config, base.layer);
  852. const ImageViewId image_view_id = FindOrEmplaceImageView(image_id, view_info);
  853. ImageViewBase& image_view = slot_image_views[image_view_id];
  854. image_view.flags |= ImageViewFlagBits::Strong;
  855. image.flags |= ImageFlagBits::Strong;
  856. return image_view_id;
  857. }
  858. template <class P>
  859. ImageId TextureCache<P>::FindOrInsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  860. RelaxedOptions options) {
  861. if (const ImageId image_id = FindImage(info, gpu_addr, options); image_id) {
  862. return image_id;
  863. }
  864. return InsertImage(info, gpu_addr, options);
  865. }
  866. template <class P>
  867. ImageId TextureCache<P>::FindImage(const ImageInfo& info, GPUVAddr gpu_addr,
  868. RelaxedOptions options) {
  869. std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  870. if (!cpu_addr) {
  871. cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr, CalculateGuestSizeInBytes(info));
  872. if (!cpu_addr) {
  873. return ImageId{};
  874. }
  875. }
  876. const bool broken_views =
  877. runtime.HasBrokenTextureViewFormats() || True(options & RelaxedOptions::ForceBrokenViews);
  878. const bool native_bgr = runtime.HasNativeBgr();
  879. const bool flexible_formats = True(options & RelaxedOptions::Format);
  880. ImageId image_id{};
  881. boost::container::small_vector<ImageId, 1> image_ids;
  882. const auto lambda = [&](ImageId existing_image_id, ImageBase& existing_image) {
  883. if (True(existing_image.flags & ImageFlagBits::Remapped)) {
  884. return false;
  885. }
  886. if (info.type == ImageType::Linear || existing_image.info.type == ImageType::Linear)
  887. [[unlikely]] {
  888. const bool strict_size = False(options & RelaxedOptions::Size) &&
  889. True(existing_image.flags & ImageFlagBits::Strong);
  890. const ImageInfo& existing = existing_image.info;
  891. if (existing_image.gpu_addr == gpu_addr && existing.type == info.type &&
  892. existing.pitch == info.pitch &&
  893. IsPitchLinearSameSize(existing, info, strict_size) &&
  894. IsViewCompatible(existing.format, info.format, broken_views, native_bgr)) {
  895. image_id = existing_image_id;
  896. image_ids.push_back(existing_image_id);
  897. return !flexible_formats && existing.format == info.format;
  898. }
  899. } else if (IsSubresource(info, existing_image, gpu_addr, options, broken_views,
  900. native_bgr)) {
  901. image_id = existing_image_id;
  902. image_ids.push_back(existing_image_id);
  903. return !flexible_formats && existing_image.info.format == info.format;
  904. }
  905. return false;
  906. };
  907. ForEachImageInRegion(*cpu_addr, CalculateGuestSizeInBytes(info), lambda);
  908. if (image_ids.size() <= 1) [[likely]] {
  909. return image_id;
  910. }
  911. auto image_ids_compare = [this](ImageId a, ImageId b) {
  912. auto& image_a = slot_images[a];
  913. auto& image_b = slot_images[b];
  914. return image_a.modification_tick < image_b.modification_tick;
  915. };
  916. return *std::ranges::max_element(image_ids, image_ids_compare);
  917. }
  918. template <class P>
  919. bool TextureCache<P>::ImageCanRescale(ImageBase& image) {
  920. if (!image.info.rescaleable) {
  921. return false;
  922. }
  923. if (Settings::values.resolution_info.downscale && !image.info.downscaleable) {
  924. return false;
  925. }
  926. if (True(image.flags & (ImageFlagBits::Rescaled | ImageFlagBits::CheckingRescalable))) {
  927. return true;
  928. }
  929. if (True(image.flags & ImageFlagBits::IsRescalable)) {
  930. return true;
  931. }
  932. image.flags |= ImageFlagBits::CheckingRescalable;
  933. for (const auto& alias : image.aliased_images) {
  934. Image& other_image = slot_images[alias.id];
  935. if (!ImageCanRescale(other_image)) {
  936. image.flags &= ~ImageFlagBits::CheckingRescalable;
  937. return false;
  938. }
  939. }
  940. image.flags &= ~ImageFlagBits::CheckingRescalable;
  941. image.flags |= ImageFlagBits::IsRescalable;
  942. return true;
  943. }
  944. template <class P>
  945. void TextureCache<P>::InvalidateScale(Image& image) {
  946. if (image.scale_tick <= frame_tick) {
  947. image.scale_tick = frame_tick + 1;
  948. }
  949. const std::span<const ImageViewId> image_view_ids = image.image_view_ids;
  950. auto& dirty = maxwell3d->dirty.flags;
  951. dirty[Dirty::RenderTargets] = true;
  952. dirty[Dirty::ZetaBuffer] = true;
  953. for (size_t rt = 0; rt < NUM_RT; ++rt) {
  954. dirty[Dirty::ColorBuffer0 + rt] = true;
  955. }
  956. for (const ImageViewId image_view_id : image_view_ids) {
  957. std::ranges::replace(render_targets.color_buffer_ids, image_view_id, ImageViewId{});
  958. if (render_targets.depth_buffer_id == image_view_id) {
  959. render_targets.depth_buffer_id = ImageViewId{};
  960. }
  961. }
  962. RemoveImageViewReferences(image_view_ids);
  963. RemoveFramebuffers(image_view_ids);
  964. for (const ImageViewId image_view_id : image_view_ids) {
  965. sentenced_image_view.Push(std::move(slot_image_views[image_view_id]));
  966. slot_image_views.erase(image_view_id);
  967. }
  968. image.image_view_ids.clear();
  969. image.image_view_infos.clear();
  970. for (size_t c : active_channel_ids) {
  971. auto& channel_info = channel_storage[c];
  972. if constexpr (ENABLE_VALIDATION) {
  973. std::ranges::fill(channel_info.graphics_image_view_ids, CORRUPT_ID);
  974. std::ranges::fill(channel_info.compute_image_view_ids, CORRUPT_ID);
  975. }
  976. channel_info.graphics_image_table.Invalidate();
  977. channel_info.compute_image_table.Invalidate();
  978. }
  979. has_deleted_images = true;
  980. }
  981. template <class P>
  982. u64 TextureCache<P>::GetScaledImageSizeBytes(const ImageBase& image) {
  983. const u64 scale_up = static_cast<u64>(Settings::values.resolution_info.up_scale *
  984. Settings::values.resolution_info.up_scale);
  985. const u64 down_shift = static_cast<u64>(Settings::values.resolution_info.down_shift +
  986. Settings::values.resolution_info.down_shift);
  987. const u64 image_size_bytes =
  988. static_cast<u64>(std::max(image.guest_size_bytes, image.unswizzled_size_bytes));
  989. const u64 tentative_size = (image_size_bytes * scale_up) >> down_shift;
  990. const u64 fitted_size = Common::AlignUp(tentative_size, 1024);
  991. return fitted_size;
  992. }
  993. template <class P>
  994. void TextureCache<P>::QueueAsyncDecode(Image& image, ImageId image_id) {
  995. UNIMPLEMENTED_IF(False(image.flags & ImageFlagBits::Converted));
  996. LOG_INFO(HW_GPU, "Queuing async texture decode");
  997. image.flags |= ImageFlagBits::IsDecoding;
  998. auto decode = std::make_unique<AsyncDecodeContext>();
  999. auto* decode_ptr = decode.get();
  1000. decode->image_id = image_id;
  1001. async_decodes.push_back(std::move(decode));
  1002. Common::ScratchBuffer<u8> local_unswizzle_data_buffer(image.unswizzled_size_bytes);
  1003. const size_t guest_size_bytes = image.guest_size_bytes;
  1004. swizzle_data_buffer.resize_destructive(guest_size_bytes);
  1005. gpu_memory->ReadBlockUnsafe(image.gpu_addr, swizzle_data_buffer.data(), guest_size_bytes);
  1006. auto copies = UnswizzleImage(*gpu_memory, image.gpu_addr, image.info, swizzle_data_buffer,
  1007. local_unswizzle_data_buffer);
  1008. const size_t out_size = MapSizeBytes(image);
  1009. auto func = [out_size, copies, info = image.info,
  1010. input = std::move(local_unswizzle_data_buffer),
  1011. async_decode = decode_ptr]() mutable {
  1012. async_decode->decoded_data.resize_destructive(out_size);
  1013. std::span copies_span{copies.data(), copies.size()};
  1014. ConvertImage(input, info, async_decode->decoded_data, copies_span);
  1015. // TODO: Do we need this lock?
  1016. std::unique_lock lock{async_decode->mutex};
  1017. async_decode->copies = std::move(copies);
  1018. async_decode->complete = true;
  1019. };
  1020. texture_decode_worker.QueueWork(std::move(func));
  1021. }
  1022. template <class P>
  1023. void TextureCache<P>::TickAsyncDecode() {
  1024. bool has_uploads{};
  1025. auto i = async_decodes.begin();
  1026. while (i != async_decodes.end()) {
  1027. auto* async_decode = i->get();
  1028. std::unique_lock lock{async_decode->mutex};
  1029. if (!async_decode->complete) {
  1030. ++i;
  1031. continue;
  1032. }
  1033. Image& image = slot_images[async_decode->image_id];
  1034. auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image));
  1035. std::memcpy(staging.mapped_span.data(), async_decode->decoded_data.data(),
  1036. async_decode->decoded_data.size());
  1037. image.UploadMemory(staging, async_decode->copies);
  1038. image.flags &= ~ImageFlagBits::IsDecoding;
  1039. has_uploads = true;
  1040. i = async_decodes.erase(i);
  1041. }
  1042. if (has_uploads) {
  1043. runtime.InsertUploadMemoryBarrier();
  1044. }
  1045. }
  1046. template <class P>
  1047. bool TextureCache<P>::ScaleUp(Image& image) {
  1048. const bool has_copy = image.HasScaled();
  1049. const bool rescaled = image.ScaleUp();
  1050. if (!rescaled) {
  1051. return false;
  1052. }
  1053. if (!has_copy) {
  1054. total_used_memory += GetScaledImageSizeBytes(image);
  1055. }
  1056. InvalidateScale(image);
  1057. return true;
  1058. }
  1059. template <class P>
  1060. bool TextureCache<P>::ScaleDown(Image& image) {
  1061. const bool rescaled = image.ScaleDown();
  1062. if (!rescaled) {
  1063. return false;
  1064. }
  1065. InvalidateScale(image);
  1066. return true;
  1067. }
  1068. template <class P>
  1069. ImageId TextureCache<P>::InsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  1070. RelaxedOptions options) {
  1071. std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1072. if (!cpu_addr) {
  1073. const auto size = CalculateGuestSizeInBytes(info);
  1074. cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr, size);
  1075. if (!cpu_addr) {
  1076. const VAddr fake_addr = ~(1ULL << 40ULL) + virtual_invalid_space;
  1077. virtual_invalid_space += Common::AlignUp(size, 32);
  1078. cpu_addr = std::optional<VAddr>(fake_addr);
  1079. }
  1080. }
  1081. ASSERT_MSG(cpu_addr, "Tried to insert an image to an invalid gpu_addr=0x{:x}", gpu_addr);
  1082. const ImageId image_id = JoinImages(info, gpu_addr, *cpu_addr);
  1083. const Image& image = slot_images[image_id];
  1084. // Using "image.gpu_addr" instead of "gpu_addr" is important because it might be different
  1085. const auto [it, is_new] = image_allocs_table.try_emplace(image.gpu_addr);
  1086. if (is_new) {
  1087. it->second = slot_image_allocs.insert();
  1088. }
  1089. slot_image_allocs[it->second].images.push_back(image_id);
  1090. return image_id;
  1091. }
  1092. template <class P>
  1093. ImageId TextureCache<P>::JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VAddr cpu_addr) {
  1094. ImageInfo new_info = info;
  1095. const size_t size_bytes = CalculateGuestSizeInBytes(new_info);
  1096. const bool broken_views = runtime.HasBrokenTextureViewFormats();
  1097. const bool native_bgr = runtime.HasNativeBgr();
  1098. std::vector<ImageId> overlap_ids;
  1099. std::unordered_set<ImageId> overlaps_found;
  1100. std::vector<ImageId> left_aliased_ids;
  1101. std::vector<ImageId> right_aliased_ids;
  1102. std::unordered_set<ImageId> ignore_textures;
  1103. std::vector<ImageId> bad_overlap_ids;
  1104. std::vector<ImageId> all_siblings;
  1105. const bool this_is_linear = info.type == ImageType::Linear;
  1106. const auto region_check = [&](ImageId overlap_id, ImageBase& overlap) {
  1107. if (True(overlap.flags & ImageFlagBits::Remapped)) {
  1108. ignore_textures.insert(overlap_id);
  1109. return;
  1110. }
  1111. const bool overlap_is_linear = overlap.info.type == ImageType::Linear;
  1112. if (this_is_linear != overlap_is_linear) {
  1113. return;
  1114. }
  1115. if (this_is_linear && overlap_is_linear) {
  1116. if (info.pitch == overlap.info.pitch && gpu_addr == overlap.gpu_addr) {
  1117. // Alias linear images with the same pitch
  1118. left_aliased_ids.push_back(overlap_id);
  1119. }
  1120. return;
  1121. }
  1122. overlaps_found.insert(overlap_id);
  1123. static constexpr bool strict_size = true;
  1124. const std::optional<OverlapResult> solution = ResolveOverlap(
  1125. new_info, gpu_addr, cpu_addr, overlap, strict_size, broken_views, native_bgr);
  1126. if (solution) {
  1127. gpu_addr = solution->gpu_addr;
  1128. cpu_addr = solution->cpu_addr;
  1129. new_info.resources = solution->resources;
  1130. overlap_ids.push_back(overlap_id);
  1131. all_siblings.push_back(overlap_id);
  1132. return;
  1133. }
  1134. static constexpr auto options = RelaxedOptions::Size | RelaxedOptions::Format;
  1135. const ImageBase new_image_base(new_info, gpu_addr, cpu_addr);
  1136. if (IsSubresource(new_info, overlap, gpu_addr, options, broken_views, native_bgr)) {
  1137. left_aliased_ids.push_back(overlap_id);
  1138. overlap.flags |= ImageFlagBits::Alias;
  1139. all_siblings.push_back(overlap_id);
  1140. } else if (IsSubresource(overlap.info, new_image_base, overlap.gpu_addr, options,
  1141. broken_views, native_bgr)) {
  1142. right_aliased_ids.push_back(overlap_id);
  1143. overlap.flags |= ImageFlagBits::Alias;
  1144. all_siblings.push_back(overlap_id);
  1145. } else {
  1146. bad_overlap_ids.push_back(overlap_id);
  1147. overlap.flags |= ImageFlagBits::BadOverlap;
  1148. }
  1149. };
  1150. ForEachImageInRegion(cpu_addr, size_bytes, region_check);
  1151. const auto region_check_gpu = [&](ImageId overlap_id, ImageBase& overlap) {
  1152. if (!overlaps_found.contains(overlap_id)) {
  1153. if (True(overlap.flags & ImageFlagBits::Remapped)) {
  1154. ignore_textures.insert(overlap_id);
  1155. }
  1156. if (overlap.gpu_addr == gpu_addr && overlap.guest_size_bytes == size_bytes) {
  1157. ignore_textures.insert(overlap_id);
  1158. }
  1159. }
  1160. };
  1161. ForEachSparseImageInRegion(gpu_addr, size_bytes, region_check_gpu);
  1162. bool can_rescale = info.rescaleable;
  1163. bool any_rescaled = false;
  1164. for (const ImageId sibling_id : all_siblings) {
  1165. if (!can_rescale) {
  1166. break;
  1167. }
  1168. Image& sibling = slot_images[sibling_id];
  1169. can_rescale &= ImageCanRescale(sibling);
  1170. any_rescaled |= True(sibling.flags & ImageFlagBits::Rescaled);
  1171. }
  1172. can_rescale &= any_rescaled;
  1173. if (can_rescale) {
  1174. for (const ImageId sibling_id : all_siblings) {
  1175. Image& sibling = slot_images[sibling_id];
  1176. ScaleUp(sibling);
  1177. }
  1178. } else {
  1179. for (const ImageId sibling_id : all_siblings) {
  1180. Image& sibling = slot_images[sibling_id];
  1181. ScaleDown(sibling);
  1182. }
  1183. }
  1184. const ImageId new_image_id = slot_images.insert(runtime, new_info, gpu_addr, cpu_addr);
  1185. Image& new_image = slot_images[new_image_id];
  1186. if (!gpu_memory->IsContinousRange(new_image.gpu_addr, new_image.guest_size_bytes)) {
  1187. new_image.flags |= ImageFlagBits::Sparse;
  1188. }
  1189. for (const ImageId overlap_id : ignore_textures) {
  1190. Image& overlap = slot_images[overlap_id];
  1191. if (True(overlap.flags & ImageFlagBits::GpuModified)) {
  1192. UNIMPLEMENTED();
  1193. }
  1194. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  1195. UntrackImage(overlap, overlap_id);
  1196. }
  1197. UnregisterImage(overlap_id);
  1198. DeleteImage(overlap_id);
  1199. }
  1200. // TODO: Only upload what we need
  1201. RefreshContents(new_image, new_image_id);
  1202. if (can_rescale) {
  1203. ScaleUp(new_image);
  1204. } else {
  1205. ScaleDown(new_image);
  1206. }
  1207. for (const ImageId overlap_id : overlap_ids) {
  1208. Image& overlap = slot_images[overlap_id];
  1209. if (True(overlap.flags & ImageFlagBits::GpuModified)) {
  1210. new_image.flags |= ImageFlagBits::GpuModified;
  1211. }
  1212. const auto& resolution = Settings::values.resolution_info;
  1213. const SubresourceBase base = new_image.TryFindBase(overlap.gpu_addr).value();
  1214. const u32 up_scale = can_rescale ? resolution.up_scale : 1;
  1215. const u32 down_shift = can_rescale ? resolution.down_shift : 0;
  1216. auto copies = MakeShrinkImageCopies(new_info, overlap.info, base, up_scale, down_shift);
  1217. if (overlap.info.num_samples != new_image.info.num_samples) {
  1218. runtime.CopyImageMSAA(new_image, overlap, std::move(copies));
  1219. } else {
  1220. runtime.CopyImage(new_image, overlap, std::move(copies));
  1221. }
  1222. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  1223. UntrackImage(overlap, overlap_id);
  1224. }
  1225. UnregisterImage(overlap_id);
  1226. DeleteImage(overlap_id);
  1227. }
  1228. ImageBase& new_image_base = new_image;
  1229. for (const ImageId aliased_id : right_aliased_ids) {
  1230. ImageBase& aliased = slot_images[aliased_id];
  1231. AddImageAlias(new_image_base, aliased, new_image_id, aliased_id);
  1232. new_image.flags |= ImageFlagBits::Alias;
  1233. }
  1234. for (const ImageId aliased_id : left_aliased_ids) {
  1235. ImageBase& aliased = slot_images[aliased_id];
  1236. AddImageAlias(aliased, new_image_base, aliased_id, new_image_id);
  1237. new_image.flags |= ImageFlagBits::Alias;
  1238. }
  1239. for (const ImageId aliased_id : bad_overlap_ids) {
  1240. ImageBase& aliased = slot_images[aliased_id];
  1241. aliased.overlapping_images.push_back(new_image_id);
  1242. new_image.overlapping_images.push_back(aliased_id);
  1243. new_image.flags |= ImageFlagBits::BadOverlap;
  1244. }
  1245. RegisterImage(new_image_id);
  1246. return new_image_id;
  1247. }
  1248. template <class P>
  1249. std::optional<typename TextureCache<P>::BlitImages> TextureCache<P>::GetBlitImages(
  1250. const Tegra::Engines::Fermi2D::Surface& dst, const Tegra::Engines::Fermi2D::Surface& src,
  1251. const Tegra::Engines::Fermi2D::Config& copy) {
  1252. static constexpr auto FIND_OPTIONS = RelaxedOptions::Samples;
  1253. const GPUVAddr dst_addr = dst.Address();
  1254. const GPUVAddr src_addr = src.Address();
  1255. ImageInfo dst_info(dst);
  1256. ImageInfo src_info(src);
  1257. const bool can_be_depth_blit =
  1258. dst_info.format == src_info.format && copy.filter == Tegra::Engines::Fermi2D::Filter::Point;
  1259. ImageId dst_id;
  1260. ImageId src_id;
  1261. RelaxedOptions try_options = FIND_OPTIONS;
  1262. if (can_be_depth_blit) {
  1263. try_options |= RelaxedOptions::Format;
  1264. }
  1265. do {
  1266. has_deleted_images = false;
  1267. src_id = FindImage(src_info, src_addr, try_options);
  1268. dst_id = FindImage(dst_info, dst_addr, try_options);
  1269. if (!copy.must_accelerate) {
  1270. do {
  1271. if (!src_id && !dst_id) {
  1272. return std::nullopt;
  1273. }
  1274. if (src_id && True(slot_images[src_id].flags & ImageFlagBits::GpuModified)) {
  1275. break;
  1276. }
  1277. if (dst_id && True(slot_images[dst_id].flags & ImageFlagBits::GpuModified)) {
  1278. break;
  1279. }
  1280. return std::nullopt;
  1281. } while (false);
  1282. }
  1283. const ImageBase* const src_image = src_id ? &slot_images[src_id] : nullptr;
  1284. if (src_image && src_image->info.num_samples > 1) {
  1285. RelaxedOptions find_options{FIND_OPTIONS | RelaxedOptions::ForceBrokenViews};
  1286. src_id = FindOrInsertImage(src_info, src_addr, find_options);
  1287. dst_id = FindOrInsertImage(dst_info, dst_addr, find_options);
  1288. if (has_deleted_images) {
  1289. continue;
  1290. }
  1291. break;
  1292. }
  1293. if (can_be_depth_blit) {
  1294. const ImageBase* const dst_image = dst_id ? &slot_images[dst_id] : nullptr;
  1295. DeduceBlitImages(dst_info, src_info, dst_image, src_image);
  1296. if (GetFormatType(dst_info.format) != GetFormatType(src_info.format)) {
  1297. continue;
  1298. }
  1299. }
  1300. if (!src_id) {
  1301. src_id = InsertImage(src_info, src_addr, RelaxedOptions{});
  1302. }
  1303. if (!dst_id) {
  1304. dst_id = InsertImage(dst_info, dst_addr, RelaxedOptions{});
  1305. }
  1306. } while (has_deleted_images);
  1307. const ImageBase& src_image = slot_images[src_id];
  1308. const ImageBase& dst_image = slot_images[dst_id];
  1309. const bool native_bgr = runtime.HasNativeBgr();
  1310. if (GetFormatType(dst_info.format) != GetFormatType(dst_image.info.format) ||
  1311. GetFormatType(src_info.format) != GetFormatType(src_image.info.format) ||
  1312. !VideoCore::Surface::IsViewCompatible(dst_info.format, dst_image.info.format, false,
  1313. native_bgr) ||
  1314. !VideoCore::Surface::IsViewCompatible(src_info.format, src_image.info.format, false,
  1315. native_bgr)) {
  1316. // Make sure the images match the expected format.
  1317. do {
  1318. has_deleted_images = false;
  1319. src_id = FindOrInsertImage(src_info, src_addr, RelaxedOptions{});
  1320. dst_id = FindOrInsertImage(dst_info, dst_addr, RelaxedOptions{});
  1321. } while (has_deleted_images);
  1322. }
  1323. return {BlitImages{
  1324. .dst_id = dst_id,
  1325. .src_id = src_id,
  1326. .dst_format = dst_info.format,
  1327. .src_format = src_info.format,
  1328. }};
  1329. }
  1330. template <class P>
  1331. ImageId TextureCache<P>::FindDMAImage(const ImageInfo& info, GPUVAddr gpu_addr) {
  1332. std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1333. if (!cpu_addr) {
  1334. cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr, CalculateGuestSizeInBytes(info));
  1335. if (!cpu_addr) {
  1336. return ImageId{};
  1337. }
  1338. }
  1339. ImageId image_id{};
  1340. boost::container::small_vector<ImageId, 1> image_ids;
  1341. const auto lambda = [&](ImageId existing_image_id, ImageBase& existing_image) {
  1342. if (True(existing_image.flags & ImageFlagBits::Remapped)) {
  1343. return false;
  1344. }
  1345. if (info.type == ImageType::Linear || existing_image.info.type == ImageType::Linear)
  1346. [[unlikely]] {
  1347. const bool strict_size = True(existing_image.flags & ImageFlagBits::Strong);
  1348. const ImageInfo& existing = existing_image.info;
  1349. if (existing_image.gpu_addr == gpu_addr && existing.type == info.type &&
  1350. existing.pitch == info.pitch &&
  1351. IsPitchLinearSameSize(existing, info, strict_size) &&
  1352. IsViewCompatible(existing.format, info.format, false, true)) {
  1353. image_id = existing_image_id;
  1354. image_ids.push_back(existing_image_id);
  1355. return true;
  1356. }
  1357. } else if (IsSubCopy(info, existing_image, gpu_addr)) {
  1358. image_id = existing_image_id;
  1359. image_ids.push_back(existing_image_id);
  1360. return true;
  1361. }
  1362. return false;
  1363. };
  1364. ForEachImageInRegion(*cpu_addr, CalculateGuestSizeInBytes(info), lambda);
  1365. if (image_ids.size() <= 1) [[likely]] {
  1366. return image_id;
  1367. }
  1368. auto image_ids_compare = [this](ImageId a, ImageId b) {
  1369. auto& image_a = slot_images[a];
  1370. auto& image_b = slot_images[b];
  1371. return image_a.modification_tick < image_b.modification_tick;
  1372. };
  1373. return *std::ranges::max_element(image_ids, image_ids_compare);
  1374. }
  1375. template <class P>
  1376. std::pair<u32, u32> TextureCache<P>::PrepareDmaImage(ImageId dst_id, GPUVAddr base_addr,
  1377. bool mark_as_modified) {
  1378. const auto& image = slot_images[dst_id];
  1379. const auto base = image.TryFindBase(base_addr);
  1380. PrepareImage(dst_id, mark_as_modified, false);
  1381. const auto& new_image = slot_images[dst_id];
  1382. lru_cache.Touch(new_image.lru_index, frame_tick);
  1383. return std::make_pair(base->level, base->layer);
  1384. }
  1385. template <class P>
  1386. SamplerId TextureCache<P>::FindSampler(const TSCEntry& config) {
  1387. if (std::ranges::all_of(config.raw, [](u64 value) { return value == 0; })) {
  1388. return NULL_SAMPLER_ID;
  1389. }
  1390. const auto [pair, is_new] = channel_state->samplers.try_emplace(config);
  1391. if (is_new) {
  1392. pair->second = slot_samplers.insert(runtime, config);
  1393. }
  1394. return pair->second;
  1395. }
  1396. template <class P>
  1397. ImageViewId TextureCache<P>::FindColorBuffer(size_t index, bool is_clear) {
  1398. const auto& regs = maxwell3d->regs;
  1399. if (index >= regs.rt_control.count) {
  1400. return ImageViewId{};
  1401. }
  1402. const auto& rt = regs.rt[index];
  1403. const GPUVAddr gpu_addr = rt.Address();
  1404. if (gpu_addr == 0) {
  1405. return ImageViewId{};
  1406. }
  1407. if (rt.format == Tegra::RenderTargetFormat::NONE) {
  1408. return ImageViewId{};
  1409. }
  1410. const ImageInfo info(regs, index);
  1411. return FindRenderTargetView(info, gpu_addr, is_clear);
  1412. }
  1413. template <class P>
  1414. ImageViewId TextureCache<P>::FindDepthBuffer(bool is_clear) {
  1415. const auto& regs = maxwell3d->regs;
  1416. if (!regs.zeta_enable) {
  1417. return ImageViewId{};
  1418. }
  1419. const GPUVAddr gpu_addr = regs.zeta.Address();
  1420. if (gpu_addr == 0) {
  1421. return ImageViewId{};
  1422. }
  1423. const ImageInfo info(regs);
  1424. return FindRenderTargetView(info, gpu_addr, is_clear);
  1425. }
  1426. template <class P>
  1427. ImageViewId TextureCache<P>::FindRenderTargetView(const ImageInfo& info, GPUVAddr gpu_addr,
  1428. bool is_clear) {
  1429. const auto options = is_clear ? RelaxedOptions::Samples : RelaxedOptions{};
  1430. ImageId image_id{};
  1431. bool delete_state = has_deleted_images;
  1432. do {
  1433. has_deleted_images = false;
  1434. image_id = FindOrInsertImage(info, gpu_addr, options);
  1435. delete_state |= has_deleted_images;
  1436. } while (has_deleted_images);
  1437. has_deleted_images = delete_state;
  1438. if (!image_id) {
  1439. return NULL_IMAGE_VIEW_ID;
  1440. }
  1441. Image& image = slot_images[image_id];
  1442. const ImageViewType view_type = RenderTargetImageViewType(info);
  1443. SubresourceBase base;
  1444. if (image.info.type == ImageType::Linear) {
  1445. base = SubresourceBase{.level = 0, .layer = 0};
  1446. } else {
  1447. base = image.TryFindBase(gpu_addr).value();
  1448. }
  1449. const s32 layers = image.info.type == ImageType::e3D ? info.size.depth : info.resources.layers;
  1450. const SubresourceRange range{
  1451. .base = base,
  1452. .extent = {.levels = 1, .layers = layers},
  1453. };
  1454. return FindOrEmplaceImageView(image_id, ImageViewInfo(view_type, info.format, range));
  1455. }
  1456. template <class P>
  1457. template <typename Func>
  1458. void TextureCache<P>::ForEachImageInRegion(VAddr cpu_addr, size_t size, Func&& func) {
  1459. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1460. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1461. boost::container::small_vector<ImageId, 32> images;
  1462. boost::container::small_vector<ImageMapId, 32> maps;
  1463. ForEachCPUPage(cpu_addr, size, [this, &images, &maps, cpu_addr, size, func](u64 page) {
  1464. const auto it = page_table.find(page);
  1465. if (it == page_table.end()) {
  1466. if constexpr (BOOL_BREAK) {
  1467. return false;
  1468. } else {
  1469. return;
  1470. }
  1471. }
  1472. for (const ImageMapId map_id : it->second) {
  1473. ImageMapView& map = slot_map_views[map_id];
  1474. if (map.picked) {
  1475. continue;
  1476. }
  1477. if (!map.Overlaps(cpu_addr, size)) {
  1478. continue;
  1479. }
  1480. map.picked = true;
  1481. maps.push_back(map_id);
  1482. Image& image = slot_images[map.image_id];
  1483. if (True(image.flags & ImageFlagBits::Picked)) {
  1484. continue;
  1485. }
  1486. image.flags |= ImageFlagBits::Picked;
  1487. images.push_back(map.image_id);
  1488. if constexpr (BOOL_BREAK) {
  1489. if (func(map.image_id, image)) {
  1490. return true;
  1491. }
  1492. } else {
  1493. func(map.image_id, image);
  1494. }
  1495. }
  1496. if constexpr (BOOL_BREAK) {
  1497. return false;
  1498. }
  1499. });
  1500. for (const ImageId image_id : images) {
  1501. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1502. }
  1503. for (const ImageMapId map_id : maps) {
  1504. slot_map_views[map_id].picked = false;
  1505. }
  1506. }
  1507. template <class P>
  1508. template <typename Func>
  1509. void TextureCache<P>::ForEachImageInRegionGPU(size_t as_id, GPUVAddr gpu_addr, size_t size,
  1510. Func&& func) {
  1511. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1512. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1513. boost::container::small_vector<ImageId, 8> images;
  1514. auto storage_id = getStorageID(as_id);
  1515. if (!storage_id) {
  1516. return;
  1517. }
  1518. auto& gpu_page_table = gpu_page_table_storage[*storage_id];
  1519. ForEachGPUPage(gpu_addr, size,
  1520. [this, &gpu_page_table, &images, gpu_addr, size, func](u64 page) {
  1521. const auto it = gpu_page_table.find(page);
  1522. if (it == gpu_page_table.end()) {
  1523. if constexpr (BOOL_BREAK) {
  1524. return false;
  1525. } else {
  1526. return;
  1527. }
  1528. }
  1529. for (const ImageId image_id : it->second) {
  1530. Image& image = slot_images[image_id];
  1531. if (True(image.flags & ImageFlagBits::Picked)) {
  1532. continue;
  1533. }
  1534. if (!image.OverlapsGPU(gpu_addr, size)) {
  1535. continue;
  1536. }
  1537. image.flags |= ImageFlagBits::Picked;
  1538. images.push_back(image_id);
  1539. if constexpr (BOOL_BREAK) {
  1540. if (func(image_id, image)) {
  1541. return true;
  1542. }
  1543. } else {
  1544. func(image_id, image);
  1545. }
  1546. }
  1547. if constexpr (BOOL_BREAK) {
  1548. return false;
  1549. }
  1550. });
  1551. for (const ImageId image_id : images) {
  1552. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1553. }
  1554. }
  1555. template <class P>
  1556. template <typename Func>
  1557. void TextureCache<P>::ForEachSparseImageInRegion(GPUVAddr gpu_addr, size_t size, Func&& func) {
  1558. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1559. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1560. boost::container::small_vector<ImageId, 8> images;
  1561. ForEachGPUPage(gpu_addr, size, [this, &images, gpu_addr, size, func](u64 page) {
  1562. const auto it = sparse_page_table.find(page);
  1563. if (it == sparse_page_table.end()) {
  1564. if constexpr (BOOL_BREAK) {
  1565. return false;
  1566. } else {
  1567. return;
  1568. }
  1569. }
  1570. for (const ImageId image_id : it->second) {
  1571. Image& image = slot_images[image_id];
  1572. if (True(image.flags & ImageFlagBits::Picked)) {
  1573. continue;
  1574. }
  1575. if (!image.OverlapsGPU(gpu_addr, size)) {
  1576. continue;
  1577. }
  1578. image.flags |= ImageFlagBits::Picked;
  1579. images.push_back(image_id);
  1580. if constexpr (BOOL_BREAK) {
  1581. if (func(image_id, image)) {
  1582. return true;
  1583. }
  1584. } else {
  1585. func(image_id, image);
  1586. }
  1587. }
  1588. if constexpr (BOOL_BREAK) {
  1589. return false;
  1590. }
  1591. });
  1592. for (const ImageId image_id : images) {
  1593. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1594. }
  1595. }
  1596. template <class P>
  1597. template <typename Func>
  1598. void TextureCache<P>::ForEachSparseSegment(ImageBase& image, Func&& func) {
  1599. using FuncReturn = typename std::invoke_result<Func, GPUVAddr, VAddr, size_t>::type;
  1600. static constexpr bool RETURNS_BOOL = std::is_same_v<FuncReturn, bool>;
  1601. const auto segments = gpu_memory->GetSubmappedRange(image.gpu_addr, image.guest_size_bytes);
  1602. for (const auto& [gpu_addr, size] : segments) {
  1603. std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1604. ASSERT(cpu_addr);
  1605. if constexpr (RETURNS_BOOL) {
  1606. if (func(gpu_addr, *cpu_addr, size)) {
  1607. break;
  1608. }
  1609. } else {
  1610. func(gpu_addr, *cpu_addr, size);
  1611. }
  1612. }
  1613. }
  1614. template <class P>
  1615. ImageViewId TextureCache<P>::FindOrEmplaceImageView(ImageId image_id, const ImageViewInfo& info) {
  1616. Image& image = slot_images[image_id];
  1617. if (const ImageViewId image_view_id = image.FindView(info); image_view_id) {
  1618. return image_view_id;
  1619. }
  1620. const ImageViewId image_view_id =
  1621. slot_image_views.insert(runtime, info, image_id, image, slot_images);
  1622. image.InsertView(info, image_view_id);
  1623. return image_view_id;
  1624. }
  1625. template <class P>
  1626. void TextureCache<P>::RegisterImage(ImageId image_id) {
  1627. ImageBase& image = slot_images[image_id];
  1628. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered),
  1629. "Trying to register an already registered image");
  1630. image.flags |= ImageFlagBits::Registered;
  1631. u64 tentative_size = std::max(image.guest_size_bytes, image.unswizzled_size_bytes);
  1632. if ((IsPixelFormatASTC(image.info.format) &&
  1633. True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
  1634. True(image.flags & ImageFlagBits::Converted)) {
  1635. tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format);
  1636. }
  1637. total_used_memory += Common::AlignUp(tentative_size, 1024);
  1638. if (total_used_memory > critical_memory && critical_gc < GC_EMERGENCY_COUNTS) {
  1639. RunGarbageCollector();
  1640. critical_gc++;
  1641. }
  1642. image.lru_index = lru_cache.Insert(image_id, frame_tick);
  1643. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, image_id](u64 page) {
  1644. (*channel_state->gpu_page_table)[page].push_back(image_id);
  1645. });
  1646. if (False(image.flags & ImageFlagBits::Sparse)) {
  1647. auto map_id =
  1648. slot_map_views.insert(image.gpu_addr, image.cpu_addr, image.guest_size_bytes, image_id);
  1649. ForEachCPUPage(image.cpu_addr, image.guest_size_bytes,
  1650. [this, map_id](u64 page) { page_table[page].push_back(map_id); });
  1651. image.map_view_id = map_id;
  1652. return;
  1653. }
  1654. std::vector<ImageViewId> sparse_maps{};
  1655. ForEachSparseSegment(
  1656. image, [this, image_id, &sparse_maps](GPUVAddr gpu_addr, VAddr cpu_addr, size_t size) {
  1657. auto map_id = slot_map_views.insert(gpu_addr, cpu_addr, size, image_id);
  1658. ForEachCPUPage(cpu_addr, size,
  1659. [this, map_id](u64 page) { page_table[page].push_back(map_id); });
  1660. sparse_maps.push_back(map_id);
  1661. });
  1662. sparse_views.emplace(image_id, std::move(sparse_maps));
  1663. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes,
  1664. [this, image_id](u64 page) { sparse_page_table[page].push_back(image_id); });
  1665. }
  1666. template <class P>
  1667. void TextureCache<P>::UnregisterImage(ImageId image_id) {
  1668. Image& image = slot_images[image_id];
  1669. ASSERT_MSG(True(image.flags & ImageFlagBits::Registered),
  1670. "Trying to unregister an already registered image");
  1671. image.flags &= ~ImageFlagBits::Registered;
  1672. image.flags &= ~ImageFlagBits::BadOverlap;
  1673. lru_cache.Free(image.lru_index);
  1674. const auto& clear_page_table =
  1675. [image_id](u64 page,
  1676. std::unordered_map<u64, std::vector<ImageId>, Common::IdentityHash<u64>>&
  1677. selected_page_table) {
  1678. const auto page_it = selected_page_table.find(page);
  1679. if (page_it == selected_page_table.end()) {
  1680. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1681. return;
  1682. }
  1683. std::vector<ImageId>& image_ids = page_it->second;
  1684. const auto vector_it = std::ranges::find(image_ids, image_id);
  1685. if (vector_it == image_ids.end()) {
  1686. ASSERT_MSG(false, "Unregistering unregistered image in page=0x{:x}",
  1687. page << YUZU_PAGEBITS);
  1688. return;
  1689. }
  1690. image_ids.erase(vector_it);
  1691. };
  1692. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, &clear_page_table](u64 page) {
  1693. clear_page_table(page, (*channel_state->gpu_page_table));
  1694. });
  1695. if (False(image.flags & ImageFlagBits::Sparse)) {
  1696. const auto map_id = image.map_view_id;
  1697. ForEachCPUPage(image.cpu_addr, image.guest_size_bytes, [this, map_id](u64 page) {
  1698. const auto page_it = page_table.find(page);
  1699. if (page_it == page_table.end()) {
  1700. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1701. return;
  1702. }
  1703. std::vector<ImageMapId>& image_map_ids = page_it->second;
  1704. const auto vector_it = std::ranges::find(image_map_ids, map_id);
  1705. if (vector_it == image_map_ids.end()) {
  1706. ASSERT_MSG(false, "Unregistering unregistered image in page=0x{:x}",
  1707. page << YUZU_PAGEBITS);
  1708. return;
  1709. }
  1710. image_map_ids.erase(vector_it);
  1711. });
  1712. slot_map_views.erase(map_id);
  1713. return;
  1714. }
  1715. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, &clear_page_table](u64 page) {
  1716. clear_page_table(page, sparse_page_table);
  1717. });
  1718. auto it = sparse_views.find(image_id);
  1719. ASSERT(it != sparse_views.end());
  1720. auto& sparse_maps = it->second;
  1721. for (auto& map_view_id : sparse_maps) {
  1722. const auto& map_range = slot_map_views[map_view_id];
  1723. const VAddr cpu_addr = map_range.cpu_addr;
  1724. const std::size_t size = map_range.size;
  1725. ForEachCPUPage(cpu_addr, size, [this, image_id](u64 page) {
  1726. const auto page_it = page_table.find(page);
  1727. if (page_it == page_table.end()) {
  1728. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1729. return;
  1730. }
  1731. std::vector<ImageMapId>& image_map_ids = page_it->second;
  1732. auto vector_it = image_map_ids.begin();
  1733. while (vector_it != image_map_ids.end()) {
  1734. ImageMapView& map = slot_map_views[*vector_it];
  1735. if (map.image_id != image_id) {
  1736. vector_it++;
  1737. continue;
  1738. }
  1739. if (!map.picked) {
  1740. map.picked = true;
  1741. }
  1742. vector_it = image_map_ids.erase(vector_it);
  1743. }
  1744. });
  1745. slot_map_views.erase(map_view_id);
  1746. }
  1747. sparse_views.erase(it);
  1748. }
  1749. template <class P>
  1750. void TextureCache<P>::TrackImage(ImageBase& image, ImageId image_id) {
  1751. ASSERT(False(image.flags & ImageFlagBits::Tracked));
  1752. image.flags |= ImageFlagBits::Tracked;
  1753. if (False(image.flags & ImageFlagBits::Sparse)) {
  1754. rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, 1);
  1755. return;
  1756. }
  1757. if (True(image.flags & ImageFlagBits::Registered)) {
  1758. auto it = sparse_views.find(image_id);
  1759. ASSERT(it != sparse_views.end());
  1760. auto& sparse_maps = it->second;
  1761. for (auto& map_view_id : sparse_maps) {
  1762. const auto& map = slot_map_views[map_view_id];
  1763. const VAddr cpu_addr = map.cpu_addr;
  1764. const std::size_t size = map.size;
  1765. rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1);
  1766. }
  1767. return;
  1768. }
  1769. ForEachSparseSegment(image,
  1770. [this]([[maybe_unused]] GPUVAddr gpu_addr, VAddr cpu_addr, size_t size) {
  1771. rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1);
  1772. });
  1773. }
  1774. template <class P>
  1775. void TextureCache<P>::UntrackImage(ImageBase& image, ImageId image_id) {
  1776. ASSERT(True(image.flags & ImageFlagBits::Tracked));
  1777. image.flags &= ~ImageFlagBits::Tracked;
  1778. if (False(image.flags & ImageFlagBits::Sparse)) {
  1779. rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, -1);
  1780. return;
  1781. }
  1782. ASSERT(True(image.flags & ImageFlagBits::Registered));
  1783. auto it = sparse_views.find(image_id);
  1784. ASSERT(it != sparse_views.end());
  1785. auto& sparse_maps = it->second;
  1786. for (auto& map_view_id : sparse_maps) {
  1787. const auto& map = slot_map_views[map_view_id];
  1788. const VAddr cpu_addr = map.cpu_addr;
  1789. const std::size_t size = map.size;
  1790. rasterizer.UpdatePagesCachedCount(cpu_addr, size, -1);
  1791. }
  1792. }
  1793. template <class P>
  1794. void TextureCache<P>::DeleteImage(ImageId image_id, bool immediate_delete) {
  1795. ImageBase& image = slot_images[image_id];
  1796. if (image.HasScaled()) {
  1797. total_used_memory -= GetScaledImageSizeBytes(image);
  1798. }
  1799. u64 tentative_size = std::max(image.guest_size_bytes, image.unswizzled_size_bytes);
  1800. if ((IsPixelFormatASTC(image.info.format) &&
  1801. True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
  1802. True(image.flags & ImageFlagBits::Converted)) {
  1803. tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format);
  1804. }
  1805. total_used_memory -= Common::AlignUp(tentative_size, 1024);
  1806. const GPUVAddr gpu_addr = image.gpu_addr;
  1807. const auto alloc_it = image_allocs_table.find(gpu_addr);
  1808. if (alloc_it == image_allocs_table.end()) {
  1809. ASSERT_MSG(false, "Trying to delete an image alloc that does not exist in address 0x{:x}",
  1810. gpu_addr);
  1811. return;
  1812. }
  1813. const ImageAllocId alloc_id = alloc_it->second;
  1814. std::vector<ImageId>& alloc_images = slot_image_allocs[alloc_id].images;
  1815. const auto alloc_image_it = std::ranges::find(alloc_images, image_id);
  1816. if (alloc_image_it == alloc_images.end()) {
  1817. ASSERT_MSG(false, "Trying to delete an image that does not exist");
  1818. return;
  1819. }
  1820. ASSERT_MSG(False(image.flags & ImageFlagBits::Tracked), "Image was not untracked");
  1821. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered), "Image was not unregistered");
  1822. // Mark render targets as dirty
  1823. auto& dirty = maxwell3d->dirty.flags;
  1824. dirty[Dirty::RenderTargets] = true;
  1825. dirty[Dirty::ZetaBuffer] = true;
  1826. for (size_t rt = 0; rt < NUM_RT; ++rt) {
  1827. dirty[Dirty::ColorBuffer0 + rt] = true;
  1828. }
  1829. const std::span<const ImageViewId> image_view_ids = image.image_view_ids;
  1830. for (const ImageViewId image_view_id : image_view_ids) {
  1831. std::ranges::replace(render_targets.color_buffer_ids, image_view_id, ImageViewId{});
  1832. if (render_targets.depth_buffer_id == image_view_id) {
  1833. render_targets.depth_buffer_id = ImageViewId{};
  1834. }
  1835. }
  1836. RemoveImageViewReferences(image_view_ids);
  1837. RemoveFramebuffers(image_view_ids);
  1838. for (const AliasedImage& alias : image.aliased_images) {
  1839. ImageBase& other_image = slot_images[alias.id];
  1840. [[maybe_unused]] const size_t num_removed_aliases =
  1841. std::erase_if(other_image.aliased_images, [image_id](const AliasedImage& other_alias) {
  1842. return other_alias.id == image_id;
  1843. });
  1844. other_image.CheckAliasState();
  1845. ASSERT_MSG(num_removed_aliases == 1, "Invalid number of removed aliases: {}",
  1846. num_removed_aliases);
  1847. }
  1848. for (const ImageId overlap_id : image.overlapping_images) {
  1849. ImageBase& other_image = slot_images[overlap_id];
  1850. [[maybe_unused]] const size_t num_removed_overlaps = std::erase_if(
  1851. other_image.overlapping_images,
  1852. [image_id](const ImageId other_overlap_id) { return other_overlap_id == image_id; });
  1853. other_image.CheckBadOverlapState();
  1854. ASSERT_MSG(num_removed_overlaps == 1, "Invalid number of removed overlapps: {}",
  1855. num_removed_overlaps);
  1856. }
  1857. for (const ImageViewId image_view_id : image_view_ids) {
  1858. if (!immediate_delete) {
  1859. sentenced_image_view.Push(std::move(slot_image_views[image_view_id]));
  1860. }
  1861. slot_image_views.erase(image_view_id);
  1862. }
  1863. if (!immediate_delete) {
  1864. sentenced_images.Push(std::move(slot_images[image_id]));
  1865. }
  1866. slot_images.erase(image_id);
  1867. alloc_images.erase(alloc_image_it);
  1868. if (alloc_images.empty()) {
  1869. image_allocs_table.erase(alloc_it);
  1870. }
  1871. for (size_t c : active_channel_ids) {
  1872. auto& channel_info = channel_storage[c];
  1873. if constexpr (ENABLE_VALIDATION) {
  1874. std::ranges::fill(channel_info.graphics_image_view_ids, CORRUPT_ID);
  1875. std::ranges::fill(channel_info.compute_image_view_ids, CORRUPT_ID);
  1876. }
  1877. channel_info.graphics_image_table.Invalidate();
  1878. channel_info.compute_image_table.Invalidate();
  1879. }
  1880. has_deleted_images = true;
  1881. }
  1882. template <class P>
  1883. void TextureCache<P>::RemoveImageViewReferences(std::span<const ImageViewId> removed_views) {
  1884. for (size_t c : active_channel_ids) {
  1885. auto& channel_info = channel_storage[c];
  1886. auto it = channel_info.image_views.begin();
  1887. while (it != channel_info.image_views.end()) {
  1888. const auto found = std::ranges::find(removed_views, it->second);
  1889. if (found != removed_views.end()) {
  1890. it = channel_info.image_views.erase(it);
  1891. } else {
  1892. ++it;
  1893. }
  1894. }
  1895. }
  1896. }
  1897. template <class P>
  1898. void TextureCache<P>::RemoveFramebuffers(std::span<const ImageViewId> removed_views) {
  1899. auto it = framebuffers.begin();
  1900. while (it != framebuffers.end()) {
  1901. if (it->first.Contains(removed_views)) {
  1902. auto framebuffer_id = it->second;
  1903. ASSERT(framebuffer_id);
  1904. sentenced_framebuffers.Push(std::move(slot_framebuffers[framebuffer_id]));
  1905. it = framebuffers.erase(it);
  1906. } else {
  1907. ++it;
  1908. }
  1909. }
  1910. }
  1911. template <class P>
  1912. void TextureCache<P>::MarkModification(ImageBase& image) noexcept {
  1913. image.flags |= ImageFlagBits::GpuModified;
  1914. image.modification_tick = ++modification_tick;
  1915. }
  1916. template <class P>
  1917. void TextureCache<P>::SynchronizeAliases(ImageId image_id) {
  1918. boost::container::small_vector<const AliasedImage*, 1> aliased_images;
  1919. Image& image = slot_images[image_id];
  1920. bool any_rescaled = True(image.flags & ImageFlagBits::Rescaled);
  1921. bool any_modified = True(image.flags & ImageFlagBits::GpuModified);
  1922. u64 most_recent_tick = image.modification_tick;
  1923. for (const AliasedImage& aliased : image.aliased_images) {
  1924. ImageBase& aliased_image = slot_images[aliased.id];
  1925. if (image.modification_tick < aliased_image.modification_tick) {
  1926. most_recent_tick = std::max(most_recent_tick, aliased_image.modification_tick);
  1927. aliased_images.push_back(&aliased);
  1928. any_rescaled |= True(aliased_image.flags & ImageFlagBits::Rescaled);
  1929. any_modified |= True(aliased_image.flags & ImageFlagBits::GpuModified);
  1930. }
  1931. }
  1932. if (aliased_images.empty()) {
  1933. return;
  1934. }
  1935. const bool can_rescale = ImageCanRescale(image);
  1936. if (any_rescaled) {
  1937. if (can_rescale) {
  1938. ScaleUp(image);
  1939. } else {
  1940. ScaleDown(image);
  1941. }
  1942. }
  1943. image.modification_tick = most_recent_tick;
  1944. if (any_modified) {
  1945. image.flags |= ImageFlagBits::GpuModified;
  1946. }
  1947. std::ranges::sort(aliased_images, [this](const AliasedImage* lhs, const AliasedImage* rhs) {
  1948. const ImageBase& lhs_image = slot_images[lhs->id];
  1949. const ImageBase& rhs_image = slot_images[rhs->id];
  1950. return lhs_image.modification_tick < rhs_image.modification_tick;
  1951. });
  1952. const auto& resolution = Settings::values.resolution_info;
  1953. for (const AliasedImage* const aliased : aliased_images) {
  1954. if (!resolution.active || !any_rescaled) {
  1955. CopyImage(image_id, aliased->id, aliased->copies);
  1956. continue;
  1957. }
  1958. Image& aliased_image = slot_images[aliased->id];
  1959. if (!can_rescale) {
  1960. ScaleDown(aliased_image);
  1961. CopyImage(image_id, aliased->id, aliased->copies);
  1962. continue;
  1963. }
  1964. ScaleUp(aliased_image);
  1965. CopyImage(image_id, aliased->id, aliased->copies);
  1966. }
  1967. }
  1968. template <class P>
  1969. void TextureCache<P>::PrepareImage(ImageId image_id, bool is_modification, bool invalidate) {
  1970. Image& image = slot_images[image_id];
  1971. if (invalidate) {
  1972. image.flags &= ~(ImageFlagBits::CpuModified | ImageFlagBits::GpuModified);
  1973. if (False(image.flags & ImageFlagBits::Tracked)) {
  1974. TrackImage(image, image_id);
  1975. }
  1976. } else {
  1977. RefreshContents(image, image_id);
  1978. SynchronizeAliases(image_id);
  1979. }
  1980. if (is_modification) {
  1981. MarkModification(image);
  1982. }
  1983. lru_cache.Touch(image.lru_index, frame_tick);
  1984. }
  1985. template <class P>
  1986. void TextureCache<P>::PrepareImageView(ImageViewId image_view_id, bool is_modification,
  1987. bool invalidate) {
  1988. if (!image_view_id) {
  1989. return;
  1990. }
  1991. const ImageViewBase& image_view = slot_image_views[image_view_id];
  1992. if (image_view.IsBuffer()) {
  1993. return;
  1994. }
  1995. PrepareImage(image_view.image_id, is_modification, invalidate);
  1996. }
  1997. template <class P>
  1998. void TextureCache<P>::CopyImage(ImageId dst_id, ImageId src_id, std::vector<ImageCopy> copies) {
  1999. Image& dst = slot_images[dst_id];
  2000. Image& src = slot_images[src_id];
  2001. const bool is_rescaled = True(src.flags & ImageFlagBits::Rescaled);
  2002. if (is_rescaled) {
  2003. ASSERT(True(dst.flags & ImageFlagBits::Rescaled));
  2004. const bool both_2d{src.info.type == ImageType::e2D && dst.info.type == ImageType::e2D};
  2005. const auto& resolution = Settings::values.resolution_info;
  2006. for (auto& copy : copies) {
  2007. copy.src_offset.x = resolution.ScaleUp(copy.src_offset.x);
  2008. copy.dst_offset.x = resolution.ScaleUp(copy.dst_offset.x);
  2009. copy.extent.width = resolution.ScaleUp(copy.extent.width);
  2010. if (both_2d) {
  2011. copy.src_offset.y = resolution.ScaleUp(copy.src_offset.y);
  2012. copy.dst_offset.y = resolution.ScaleUp(copy.dst_offset.y);
  2013. copy.extent.height = resolution.ScaleUp(copy.extent.height);
  2014. }
  2015. }
  2016. }
  2017. const auto dst_format_type = GetFormatType(dst.info.format);
  2018. const auto src_format_type = GetFormatType(src.info.format);
  2019. if (src_format_type == dst_format_type) {
  2020. if constexpr (HAS_EMULATED_COPIES) {
  2021. if (!runtime.CanImageBeCopied(dst, src)) {
  2022. return runtime.EmulateCopyImage(dst, src, copies);
  2023. }
  2024. }
  2025. return runtime.CopyImage(dst, src, copies);
  2026. }
  2027. UNIMPLEMENTED_IF(dst.info.type != ImageType::e2D);
  2028. UNIMPLEMENTED_IF(src.info.type != ImageType::e2D);
  2029. if (runtime.ShouldReinterpret(dst, src)) {
  2030. return runtime.ReinterpretImage(dst, src, copies);
  2031. }
  2032. for (const ImageCopy& copy : copies) {
  2033. UNIMPLEMENTED_IF(copy.dst_subresource.num_layers != 1);
  2034. UNIMPLEMENTED_IF(copy.src_subresource.num_layers != 1);
  2035. UNIMPLEMENTED_IF(copy.src_offset != Offset3D{});
  2036. UNIMPLEMENTED_IF(copy.dst_offset != Offset3D{});
  2037. const SubresourceBase dst_base{
  2038. .level = copy.dst_subresource.base_level,
  2039. .layer = copy.dst_subresource.base_layer,
  2040. };
  2041. const SubresourceBase src_base{
  2042. .level = copy.src_subresource.base_level,
  2043. .layer = copy.src_subresource.base_layer,
  2044. };
  2045. const SubresourceExtent dst_extent{.levels = 1, .layers = 1};
  2046. const SubresourceExtent src_extent{.levels = 1, .layers = 1};
  2047. const SubresourceRange dst_range{.base = dst_base, .extent = dst_extent};
  2048. const SubresourceRange src_range{.base = src_base, .extent = src_extent};
  2049. PixelFormat dst_format = dst.info.format;
  2050. if (GetFormatType(src.info.format) == SurfaceType::DepthStencil &&
  2051. GetFormatType(dst_format) == SurfaceType::ColorTexture &&
  2052. BytesPerBlock(dst_format) == 4) {
  2053. dst_format = PixelFormat::A8B8G8R8_UNORM;
  2054. }
  2055. const ImageViewInfo dst_view_info(ImageViewType::e2D, dst_format, dst_range);
  2056. const ImageViewInfo src_view_info(ImageViewType::e2D, src.info.format, src_range);
  2057. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  2058. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  2059. const ImageViewId src_view_id = FindOrEmplaceImageView(src_id, src_view_info);
  2060. ImageView& dst_view = slot_image_views[dst_view_id];
  2061. ImageView& src_view = slot_image_views[src_view_id];
  2062. [[maybe_unused]] const Extent3D expected_size{
  2063. .width = std::min(dst_view.size.width, src_view.size.width),
  2064. .height = std::min(dst_view.size.height, src_view.size.height),
  2065. .depth = std::min(dst_view.size.depth, src_view.size.depth),
  2066. };
  2067. const Extent3D scaled_extent = [is_rescaled, expected_size]() {
  2068. if (!is_rescaled) {
  2069. return expected_size;
  2070. }
  2071. const auto& resolution = Settings::values.resolution_info;
  2072. return Extent3D{
  2073. .width = resolution.ScaleUp(expected_size.width),
  2074. .height = resolution.ScaleUp(expected_size.height),
  2075. .depth = expected_size.depth,
  2076. };
  2077. }();
  2078. UNIMPLEMENTED_IF(copy.extent != scaled_extent);
  2079. runtime.ConvertImage(dst_framebuffer, dst_view, src_view);
  2080. }
  2081. }
  2082. template <class P>
  2083. void TextureCache<P>::BindRenderTarget(ImageViewId* old_id, ImageViewId new_id) {
  2084. if (*old_id == new_id) {
  2085. return;
  2086. }
  2087. if (new_id) {
  2088. const ImageViewBase& old_view = slot_image_views[new_id];
  2089. if (True(old_view.flags & ImageViewFlagBits::PreemtiveDownload)) {
  2090. uncommitted_downloads.push_back(old_view.image_id);
  2091. }
  2092. }
  2093. *old_id = new_id;
  2094. }
  2095. template <class P>
  2096. std::pair<FramebufferId, ImageViewId> TextureCache<P>::RenderTargetFromImage(
  2097. ImageId image_id, const ImageViewInfo& view_info) {
  2098. const ImageViewId view_id = FindOrEmplaceImageView(image_id, view_info);
  2099. const ImageBase& image = slot_images[image_id];
  2100. const bool is_rescaled = True(image.flags & ImageFlagBits::Rescaled);
  2101. const bool is_color = GetFormatType(image.info.format) == SurfaceType::ColorTexture;
  2102. const ImageViewId color_view_id = is_color ? view_id : ImageViewId{};
  2103. const ImageViewId depth_view_id = is_color ? ImageViewId{} : view_id;
  2104. Extent3D extent = MipSize(image.info.size, view_info.range.base.level);
  2105. if (is_rescaled) {
  2106. const auto& resolution = Settings::values.resolution_info;
  2107. extent.width = resolution.ScaleUp(extent.width);
  2108. if (image.info.type == ImageType::e2D) {
  2109. extent.height = resolution.ScaleUp(extent.height);
  2110. }
  2111. }
  2112. const u32 num_samples = image.info.num_samples;
  2113. const auto [samples_x, samples_y] = SamplesLog2(num_samples);
  2114. const FramebufferId framebuffer_id = GetFramebufferId(RenderTargets{
  2115. .color_buffer_ids = {color_view_id},
  2116. .depth_buffer_id = depth_view_id,
  2117. .size = {extent.width >> samples_x, extent.height >> samples_y},
  2118. .is_rescaled = is_rescaled,
  2119. });
  2120. return {framebuffer_id, view_id};
  2121. }
  2122. template <class P>
  2123. bool TextureCache<P>::IsFullClear(ImageViewId id) {
  2124. if (!id) {
  2125. return true;
  2126. }
  2127. const ImageViewBase& image_view = slot_image_views[id];
  2128. const ImageBase& image = slot_images[image_view.image_id];
  2129. const Extent3D size = image_view.size;
  2130. const auto& regs = maxwell3d->regs;
  2131. const auto& scissor = regs.scissor_test[0];
  2132. if (image.info.resources.levels > 1 || image.info.resources.layers > 1) {
  2133. // Images with multiple resources can't be cleared in a single call
  2134. return false;
  2135. }
  2136. if (regs.clear_control.use_scissor == 0) {
  2137. // If scissor testing is disabled, the clear is always full
  2138. return true;
  2139. }
  2140. // Make sure the clear covers all texels in the subresource
  2141. return scissor.min_x == 0 && scissor.min_y == 0 && scissor.max_x >= size.width &&
  2142. scissor.max_y >= size.height;
  2143. }
  2144. template <class P>
  2145. void TextureCache<P>::CreateChannel(struct Tegra::Control::ChannelState& channel) {
  2146. VideoCommon::ChannelSetupCaches<TextureCacheChannelInfo>::CreateChannel(channel);
  2147. const auto it = channel_map.find(channel.bind_id);
  2148. auto* this_state = &channel_storage[it->second];
  2149. const auto& this_as_ref = address_spaces[channel.memory_manager->GetID()];
  2150. this_state->gpu_page_table = &gpu_page_table_storage[this_as_ref.storage_id];
  2151. }
  2152. /// Bind a channel for execution.
  2153. template <class P>
  2154. void TextureCache<P>::OnGPUASRegister([[maybe_unused]] size_t map_id) {
  2155. gpu_page_table_storage.emplace_back();
  2156. }
  2157. } // namespace VideoCommon