texture_cache.h 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  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. bool TextureCache<P>::IsRescaling() const noexcept {
  695. return is_rescaling;
  696. }
  697. template <class P>
  698. bool TextureCache<P>::IsRescaling(const ImageViewBase& image_view) const noexcept {
  699. if (image_view.type == ImageViewType::Buffer) {
  700. return false;
  701. }
  702. const ImageBase& image = slot_images[image_view.image_id];
  703. return True(image.flags & ImageFlagBits::Rescaled);
  704. }
  705. template <class P>
  706. bool TextureCache<P>::IsRegionGpuModified(VAddr addr, size_t size) {
  707. bool is_modified = false;
  708. ForEachImageInRegion(addr, size, [&is_modified](ImageId, ImageBase& image) {
  709. if (False(image.flags & ImageFlagBits::GpuModified)) {
  710. return false;
  711. }
  712. is_modified = true;
  713. return true;
  714. });
  715. return is_modified;
  716. }
  717. template <class P>
  718. void TextureCache<P>::RefreshContents(Image& image, ImageId image_id) {
  719. if (False(image.flags & ImageFlagBits::CpuModified)) {
  720. // Only upload modified images
  721. return;
  722. }
  723. image.flags &= ~ImageFlagBits::CpuModified;
  724. TrackImage(image, image_id);
  725. if (image.info.num_samples > 1 && !runtime.CanUploadMSAA()) {
  726. LOG_WARNING(HW_GPU, "MSAA image uploads are not implemented");
  727. return;
  728. }
  729. if (True(image.flags & ImageFlagBits::AsynchronousDecode)) {
  730. QueueAsyncDecode(image, image_id);
  731. return;
  732. }
  733. auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image));
  734. UploadImageContents(image, staging);
  735. runtime.InsertUploadMemoryBarrier();
  736. }
  737. template <class P>
  738. template <typename StagingBuffer>
  739. void TextureCache<P>::UploadImageContents(Image& image, StagingBuffer& staging) {
  740. const std::span<u8> mapped_span = staging.mapped_span;
  741. const GPUVAddr gpu_addr = image.gpu_addr;
  742. if (True(image.flags & ImageFlagBits::AcceleratedUpload)) {
  743. gpu_memory->ReadBlock(gpu_addr, mapped_span.data(), mapped_span.size_bytes(),
  744. VideoCommon::CacheType::NoTextureCache);
  745. const auto uploads = FullUploadSwizzles(image.info);
  746. runtime.AccelerateImageUpload(image, staging, uploads);
  747. return;
  748. }
  749. const size_t guest_size_bytes = image.guest_size_bytes;
  750. swizzle_data_buffer.resize_destructive(guest_size_bytes);
  751. gpu_memory->ReadBlockUnsafe(gpu_addr, swizzle_data_buffer.data(), guest_size_bytes);
  752. if (True(image.flags & ImageFlagBits::Converted)) {
  753. unswizzle_data_buffer.resize_destructive(image.unswizzled_size_bytes);
  754. auto copies = UnswizzleImage(*gpu_memory, gpu_addr, image.info, swizzle_data_buffer,
  755. unswizzle_data_buffer);
  756. ConvertImage(unswizzle_data_buffer, image.info, mapped_span, copies);
  757. image.UploadMemory(staging, copies);
  758. } else {
  759. const auto copies =
  760. UnswizzleImage(*gpu_memory, gpu_addr, image.info, swizzle_data_buffer, mapped_span);
  761. image.UploadMemory(staging, copies);
  762. }
  763. }
  764. template <class P>
  765. ImageViewId TextureCache<P>::FindImageView(const TICEntry& config) {
  766. if (!IsValidEntry(*gpu_memory, config)) {
  767. return NULL_IMAGE_VIEW_ID;
  768. }
  769. const auto [pair, is_new] = channel_state->image_views.try_emplace(config);
  770. ImageViewId& image_view_id = pair->second;
  771. if (is_new) {
  772. image_view_id = CreateImageView(config);
  773. }
  774. return image_view_id;
  775. }
  776. template <class P>
  777. ImageViewId TextureCache<P>::CreateImageView(const TICEntry& config) {
  778. const ImageInfo info(config);
  779. if (info.type == ImageType::Buffer) {
  780. const ImageViewInfo view_info(config, 0);
  781. return slot_image_views.insert(runtime, info, view_info, config.Address());
  782. }
  783. const u32 layer_offset = config.BaseLayer() * info.layer_stride;
  784. const GPUVAddr image_gpu_addr = config.Address() - layer_offset;
  785. const ImageId image_id = FindOrInsertImage(info, image_gpu_addr);
  786. if (!image_id) {
  787. return NULL_IMAGE_VIEW_ID;
  788. }
  789. ImageBase& image = slot_images[image_id];
  790. const SubresourceBase base = image.TryFindBase(config.Address()).value();
  791. ASSERT(base.level == 0);
  792. const ImageViewInfo view_info(config, base.layer);
  793. const ImageViewId image_view_id = FindOrEmplaceImageView(image_id, view_info);
  794. ImageViewBase& image_view = slot_image_views[image_view_id];
  795. image_view.flags |= ImageViewFlagBits::Strong;
  796. image.flags |= ImageFlagBits::Strong;
  797. return image_view_id;
  798. }
  799. template <class P>
  800. ImageId TextureCache<P>::FindOrInsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  801. RelaxedOptions options) {
  802. if (const ImageId image_id = FindImage(info, gpu_addr, options); image_id) {
  803. return image_id;
  804. }
  805. return InsertImage(info, gpu_addr, options);
  806. }
  807. template <class P>
  808. ImageId TextureCache<P>::FindImage(const ImageInfo& info, GPUVAddr gpu_addr,
  809. RelaxedOptions options) {
  810. std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  811. if (!cpu_addr) {
  812. cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr, CalculateGuestSizeInBytes(info));
  813. if (!cpu_addr) {
  814. return ImageId{};
  815. }
  816. }
  817. const bool broken_views =
  818. runtime.HasBrokenTextureViewFormats() || True(options & RelaxedOptions::ForceBrokenViews);
  819. const bool native_bgr = runtime.HasNativeBgr();
  820. const bool flexible_formats = True(options & RelaxedOptions::Format);
  821. ImageId image_id{};
  822. boost::container::small_vector<ImageId, 1> image_ids;
  823. const auto lambda = [&](ImageId existing_image_id, ImageBase& existing_image) {
  824. if (True(existing_image.flags & ImageFlagBits::Remapped)) {
  825. return false;
  826. }
  827. if (info.type == ImageType::Linear || existing_image.info.type == ImageType::Linear)
  828. [[unlikely]] {
  829. const bool strict_size = False(options & RelaxedOptions::Size) &&
  830. True(existing_image.flags & ImageFlagBits::Strong);
  831. const ImageInfo& existing = existing_image.info;
  832. if (existing_image.gpu_addr == gpu_addr && existing.type == info.type &&
  833. existing.pitch == info.pitch &&
  834. IsPitchLinearSameSize(existing, info, strict_size) &&
  835. IsViewCompatible(existing.format, info.format, broken_views, native_bgr)) {
  836. image_id = existing_image_id;
  837. image_ids.push_back(existing_image_id);
  838. return !flexible_formats && existing.format == info.format;
  839. }
  840. } else if (IsSubresource(info, existing_image, gpu_addr, options, broken_views,
  841. native_bgr)) {
  842. image_id = existing_image_id;
  843. image_ids.push_back(existing_image_id);
  844. return !flexible_formats && existing_image.info.format == info.format;
  845. }
  846. return false;
  847. };
  848. ForEachImageInRegion(*cpu_addr, CalculateGuestSizeInBytes(info), lambda);
  849. if (image_ids.size() <= 1) [[likely]] {
  850. return image_id;
  851. }
  852. auto image_ids_compare = [this](ImageId a, ImageId b) {
  853. auto& image_a = slot_images[a];
  854. auto& image_b = slot_images[b];
  855. return image_a.modification_tick < image_b.modification_tick;
  856. };
  857. return *std::ranges::max_element(image_ids, image_ids_compare);
  858. }
  859. template <class P>
  860. bool TextureCache<P>::ImageCanRescale(ImageBase& image) {
  861. if (!image.info.rescaleable) {
  862. return false;
  863. }
  864. if (Settings::values.resolution_info.downscale && !image.info.downscaleable) {
  865. return false;
  866. }
  867. if (True(image.flags & (ImageFlagBits::Rescaled | ImageFlagBits::CheckingRescalable))) {
  868. return true;
  869. }
  870. if (True(image.flags & ImageFlagBits::IsRescalable)) {
  871. return true;
  872. }
  873. image.flags |= ImageFlagBits::CheckingRescalable;
  874. for (const auto& alias : image.aliased_images) {
  875. Image& other_image = slot_images[alias.id];
  876. if (!ImageCanRescale(other_image)) {
  877. image.flags &= ~ImageFlagBits::CheckingRescalable;
  878. return false;
  879. }
  880. }
  881. image.flags &= ~ImageFlagBits::CheckingRescalable;
  882. image.flags |= ImageFlagBits::IsRescalable;
  883. return true;
  884. }
  885. template <class P>
  886. void TextureCache<P>::InvalidateScale(Image& image) {
  887. if (image.scale_tick <= frame_tick) {
  888. image.scale_tick = frame_tick + 1;
  889. }
  890. const std::span<const ImageViewId> image_view_ids = image.image_view_ids;
  891. auto& dirty = maxwell3d->dirty.flags;
  892. dirty[Dirty::RenderTargets] = true;
  893. dirty[Dirty::ZetaBuffer] = true;
  894. for (size_t rt = 0; rt < NUM_RT; ++rt) {
  895. dirty[Dirty::ColorBuffer0 + rt] = true;
  896. }
  897. for (const ImageViewId image_view_id : image_view_ids) {
  898. std::ranges::replace(render_targets.color_buffer_ids, image_view_id, ImageViewId{});
  899. if (render_targets.depth_buffer_id == image_view_id) {
  900. render_targets.depth_buffer_id = ImageViewId{};
  901. }
  902. }
  903. RemoveImageViewReferences(image_view_ids);
  904. RemoveFramebuffers(image_view_ids);
  905. for (const ImageViewId image_view_id : image_view_ids) {
  906. sentenced_image_view.Push(std::move(slot_image_views[image_view_id]));
  907. slot_image_views.erase(image_view_id);
  908. }
  909. image.image_view_ids.clear();
  910. image.image_view_infos.clear();
  911. for (size_t c : active_channel_ids) {
  912. auto& channel_info = channel_storage[c];
  913. if constexpr (ENABLE_VALIDATION) {
  914. std::ranges::fill(channel_info.graphics_image_view_ids, CORRUPT_ID);
  915. std::ranges::fill(channel_info.compute_image_view_ids, CORRUPT_ID);
  916. }
  917. channel_info.graphics_image_table.Invalidate();
  918. channel_info.compute_image_table.Invalidate();
  919. }
  920. has_deleted_images = true;
  921. }
  922. template <class P>
  923. u64 TextureCache<P>::GetScaledImageSizeBytes(const ImageBase& image) {
  924. const u64 scale_up = static_cast<u64>(Settings::values.resolution_info.up_scale *
  925. Settings::values.resolution_info.up_scale);
  926. const u64 down_shift = static_cast<u64>(Settings::values.resolution_info.down_shift +
  927. Settings::values.resolution_info.down_shift);
  928. const u64 image_size_bytes =
  929. static_cast<u64>(std::max(image.guest_size_bytes, image.unswizzled_size_bytes));
  930. const u64 tentative_size = (image_size_bytes * scale_up) >> down_shift;
  931. const u64 fitted_size = Common::AlignUp(tentative_size, 1024);
  932. return fitted_size;
  933. }
  934. template <class P>
  935. void TextureCache<P>::QueueAsyncDecode(Image& image, ImageId image_id) {
  936. UNIMPLEMENTED_IF(False(image.flags & ImageFlagBits::Converted));
  937. image.flags |= ImageFlagBits::IsDecoding;
  938. auto decode = std::make_unique<AsyncDecodeContext>();
  939. auto* decode_ptr = decode.get();
  940. decode->image_id = image_id;
  941. async_decodes.push_back(std::move(decode));
  942. Common::ScratchBuffer<u8> local_unswizzle_data_buffer(image.unswizzled_size_bytes);
  943. const size_t guest_size_bytes = image.guest_size_bytes;
  944. swizzle_data_buffer.resize_destructive(guest_size_bytes);
  945. gpu_memory->ReadBlockUnsafe(image.gpu_addr, swizzle_data_buffer.data(), guest_size_bytes);
  946. auto copies = UnswizzleImage(*gpu_memory, image.gpu_addr, image.info, swizzle_data_buffer,
  947. local_unswizzle_data_buffer);
  948. const size_t out_size = MapSizeBytes(image);
  949. auto func = [out_size, copies, info = image.info,
  950. input = std::move(local_unswizzle_data_buffer),
  951. async_decode = decode_ptr]() mutable {
  952. async_decode->decoded_data.resize_destructive(out_size);
  953. std::span copies_span{copies.data(), copies.size()};
  954. ConvertImage(input, info, async_decode->decoded_data, copies_span);
  955. // TODO: Do we need this lock?
  956. std::unique_lock lock{async_decode->mutex};
  957. async_decode->copies = std::move(copies);
  958. async_decode->complete = true;
  959. };
  960. texture_decode_worker.QueueWork(std::move(func));
  961. }
  962. template <class P>
  963. void TextureCache<P>::TickAsyncDecode() {
  964. bool has_uploads{};
  965. auto i = async_decodes.begin();
  966. while (i != async_decodes.end()) {
  967. auto* async_decode = i->get();
  968. std::unique_lock lock{async_decode->mutex};
  969. if (!async_decode->complete) {
  970. ++i;
  971. continue;
  972. }
  973. Image& image = slot_images[async_decode->image_id];
  974. auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image));
  975. std::memcpy(staging.mapped_span.data(), async_decode->decoded_data.data(),
  976. async_decode->decoded_data.size());
  977. image.UploadMemory(staging, async_decode->copies);
  978. image.flags &= ~ImageFlagBits::IsDecoding;
  979. has_uploads = true;
  980. i = async_decodes.erase(i);
  981. }
  982. if (has_uploads) {
  983. runtime.InsertUploadMemoryBarrier();
  984. }
  985. }
  986. template <class P>
  987. bool TextureCache<P>::ScaleUp(Image& image) {
  988. const bool has_copy = image.HasScaled();
  989. const bool rescaled = image.ScaleUp();
  990. if (!rescaled) {
  991. return false;
  992. }
  993. if (!has_copy) {
  994. total_used_memory += GetScaledImageSizeBytes(image);
  995. }
  996. InvalidateScale(image);
  997. return true;
  998. }
  999. template <class P>
  1000. bool TextureCache<P>::ScaleDown(Image& image) {
  1001. const bool rescaled = image.ScaleDown();
  1002. if (!rescaled) {
  1003. return false;
  1004. }
  1005. InvalidateScale(image);
  1006. return true;
  1007. }
  1008. template <class P>
  1009. ImageId TextureCache<P>::InsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  1010. RelaxedOptions options) {
  1011. std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1012. if (!cpu_addr) {
  1013. const auto size = CalculateGuestSizeInBytes(info);
  1014. cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr, size);
  1015. if (!cpu_addr) {
  1016. const VAddr fake_addr = ~(1ULL << 40ULL) + virtual_invalid_space;
  1017. virtual_invalid_space += Common::AlignUp(size, 32);
  1018. cpu_addr = std::optional<VAddr>(fake_addr);
  1019. }
  1020. }
  1021. ASSERT_MSG(cpu_addr, "Tried to insert an image to an invalid gpu_addr=0x{:x}", gpu_addr);
  1022. const ImageId image_id = JoinImages(info, gpu_addr, *cpu_addr);
  1023. const Image& image = slot_images[image_id];
  1024. // Using "image.gpu_addr" instead of "gpu_addr" is important because it might be different
  1025. const auto [it, is_new] = image_allocs_table.try_emplace(image.gpu_addr);
  1026. if (is_new) {
  1027. it->second = slot_image_allocs.insert();
  1028. }
  1029. slot_image_allocs[it->second].images.push_back(image_id);
  1030. return image_id;
  1031. }
  1032. template <class P>
  1033. ImageId TextureCache<P>::JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VAddr cpu_addr) {
  1034. ImageInfo new_info = info;
  1035. const size_t size_bytes = CalculateGuestSizeInBytes(new_info);
  1036. const bool broken_views = runtime.HasBrokenTextureViewFormats();
  1037. const bool native_bgr = runtime.HasNativeBgr();
  1038. std::vector<ImageId> overlap_ids;
  1039. std::unordered_set<ImageId> overlaps_found;
  1040. std::vector<ImageId> left_aliased_ids;
  1041. std::vector<ImageId> right_aliased_ids;
  1042. std::unordered_set<ImageId> ignore_textures;
  1043. std::vector<ImageId> bad_overlap_ids;
  1044. std::vector<ImageId> all_siblings;
  1045. const bool this_is_linear = info.type == ImageType::Linear;
  1046. const auto region_check = [&](ImageId overlap_id, ImageBase& overlap) {
  1047. if (True(overlap.flags & ImageFlagBits::Remapped)) {
  1048. ignore_textures.insert(overlap_id);
  1049. return;
  1050. }
  1051. const bool overlap_is_linear = overlap.info.type == ImageType::Linear;
  1052. if (this_is_linear != overlap_is_linear) {
  1053. return;
  1054. }
  1055. if (this_is_linear && overlap_is_linear) {
  1056. if (info.pitch == overlap.info.pitch && gpu_addr == overlap.gpu_addr) {
  1057. // Alias linear images with the same pitch
  1058. left_aliased_ids.push_back(overlap_id);
  1059. }
  1060. return;
  1061. }
  1062. overlaps_found.insert(overlap_id);
  1063. static constexpr bool strict_size = true;
  1064. const std::optional<OverlapResult> solution = ResolveOverlap(
  1065. new_info, gpu_addr, cpu_addr, overlap, strict_size, broken_views, native_bgr);
  1066. if (solution) {
  1067. gpu_addr = solution->gpu_addr;
  1068. cpu_addr = solution->cpu_addr;
  1069. new_info.resources = solution->resources;
  1070. overlap_ids.push_back(overlap_id);
  1071. all_siblings.push_back(overlap_id);
  1072. return;
  1073. }
  1074. static constexpr auto options = RelaxedOptions::Size | RelaxedOptions::Format;
  1075. const ImageBase new_image_base(new_info, gpu_addr, cpu_addr);
  1076. if (IsSubresource(new_info, overlap, gpu_addr, options, broken_views, native_bgr)) {
  1077. left_aliased_ids.push_back(overlap_id);
  1078. overlap.flags |= ImageFlagBits::Alias;
  1079. all_siblings.push_back(overlap_id);
  1080. } else if (IsSubresource(overlap.info, new_image_base, overlap.gpu_addr, options,
  1081. broken_views, native_bgr)) {
  1082. right_aliased_ids.push_back(overlap_id);
  1083. overlap.flags |= ImageFlagBits::Alias;
  1084. all_siblings.push_back(overlap_id);
  1085. } else {
  1086. bad_overlap_ids.push_back(overlap_id);
  1087. overlap.flags |= ImageFlagBits::BadOverlap;
  1088. }
  1089. };
  1090. ForEachImageInRegion(cpu_addr, size_bytes, region_check);
  1091. const auto region_check_gpu = [&](ImageId overlap_id, ImageBase& overlap) {
  1092. if (!overlaps_found.contains(overlap_id)) {
  1093. if (True(overlap.flags & ImageFlagBits::Remapped)) {
  1094. ignore_textures.insert(overlap_id);
  1095. }
  1096. if (overlap.gpu_addr == gpu_addr && overlap.guest_size_bytes == size_bytes) {
  1097. ignore_textures.insert(overlap_id);
  1098. }
  1099. }
  1100. };
  1101. ForEachSparseImageInRegion(gpu_addr, size_bytes, region_check_gpu);
  1102. bool can_rescale = info.rescaleable;
  1103. bool any_rescaled = false;
  1104. for (const ImageId sibling_id : all_siblings) {
  1105. if (!can_rescale) {
  1106. break;
  1107. }
  1108. Image& sibling = slot_images[sibling_id];
  1109. can_rescale &= ImageCanRescale(sibling);
  1110. any_rescaled |= True(sibling.flags & ImageFlagBits::Rescaled);
  1111. }
  1112. can_rescale &= any_rescaled;
  1113. if (can_rescale) {
  1114. for (const ImageId sibling_id : all_siblings) {
  1115. Image& sibling = slot_images[sibling_id];
  1116. ScaleUp(sibling);
  1117. }
  1118. } else {
  1119. for (const ImageId sibling_id : all_siblings) {
  1120. Image& sibling = slot_images[sibling_id];
  1121. ScaleDown(sibling);
  1122. }
  1123. }
  1124. const ImageId new_image_id = slot_images.insert(runtime, new_info, gpu_addr, cpu_addr);
  1125. Image& new_image = slot_images[new_image_id];
  1126. if (!gpu_memory->IsContinousRange(new_image.gpu_addr, new_image.guest_size_bytes)) {
  1127. new_image.flags |= ImageFlagBits::Sparse;
  1128. }
  1129. for (const ImageId overlap_id : ignore_textures) {
  1130. Image& overlap = slot_images[overlap_id];
  1131. if (True(overlap.flags & ImageFlagBits::GpuModified)) {
  1132. UNIMPLEMENTED();
  1133. }
  1134. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  1135. UntrackImage(overlap, overlap_id);
  1136. }
  1137. UnregisterImage(overlap_id);
  1138. DeleteImage(overlap_id);
  1139. }
  1140. // TODO: Only upload what we need
  1141. RefreshContents(new_image, new_image_id);
  1142. if (can_rescale) {
  1143. ScaleUp(new_image);
  1144. } else {
  1145. ScaleDown(new_image);
  1146. }
  1147. for (const ImageId overlap_id : overlap_ids) {
  1148. Image& overlap = slot_images[overlap_id];
  1149. if (True(overlap.flags & ImageFlagBits::GpuModified)) {
  1150. new_image.flags |= ImageFlagBits::GpuModified;
  1151. }
  1152. const auto& resolution = Settings::values.resolution_info;
  1153. const SubresourceBase base = new_image.TryFindBase(overlap.gpu_addr).value();
  1154. const u32 up_scale = can_rescale ? resolution.up_scale : 1;
  1155. const u32 down_shift = can_rescale ? resolution.down_shift : 0;
  1156. auto copies = MakeShrinkImageCopies(new_info, overlap.info, base, up_scale, down_shift);
  1157. if (overlap.info.num_samples != new_image.info.num_samples) {
  1158. runtime.CopyImageMSAA(new_image, overlap, std::move(copies));
  1159. } else {
  1160. runtime.CopyImage(new_image, overlap, std::move(copies));
  1161. }
  1162. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  1163. UntrackImage(overlap, overlap_id);
  1164. }
  1165. UnregisterImage(overlap_id);
  1166. DeleteImage(overlap_id);
  1167. }
  1168. ImageBase& new_image_base = new_image;
  1169. for (const ImageId aliased_id : right_aliased_ids) {
  1170. ImageBase& aliased = slot_images[aliased_id];
  1171. AddImageAlias(new_image_base, aliased, new_image_id, aliased_id);
  1172. new_image.flags |= ImageFlagBits::Alias;
  1173. }
  1174. for (const ImageId aliased_id : left_aliased_ids) {
  1175. ImageBase& aliased = slot_images[aliased_id];
  1176. AddImageAlias(aliased, new_image_base, aliased_id, new_image_id);
  1177. new_image.flags |= ImageFlagBits::Alias;
  1178. }
  1179. for (const ImageId aliased_id : bad_overlap_ids) {
  1180. ImageBase& aliased = slot_images[aliased_id];
  1181. aliased.overlapping_images.push_back(new_image_id);
  1182. new_image.overlapping_images.push_back(aliased_id);
  1183. new_image.flags |= ImageFlagBits::BadOverlap;
  1184. }
  1185. RegisterImage(new_image_id);
  1186. return new_image_id;
  1187. }
  1188. template <class P>
  1189. std::optional<typename TextureCache<P>::BlitImages> TextureCache<P>::GetBlitImages(
  1190. const Tegra::Engines::Fermi2D::Surface& dst, const Tegra::Engines::Fermi2D::Surface& src,
  1191. const Tegra::Engines::Fermi2D::Config& copy) {
  1192. static constexpr auto FIND_OPTIONS = RelaxedOptions::Samples;
  1193. const GPUVAddr dst_addr = dst.Address();
  1194. const GPUVAddr src_addr = src.Address();
  1195. ImageInfo dst_info(dst);
  1196. ImageInfo src_info(src);
  1197. const bool can_be_depth_blit =
  1198. dst_info.format == src_info.format && copy.filter == Tegra::Engines::Fermi2D::Filter::Point;
  1199. ImageId dst_id;
  1200. ImageId src_id;
  1201. RelaxedOptions try_options = FIND_OPTIONS;
  1202. if (can_be_depth_blit) {
  1203. try_options |= RelaxedOptions::Format;
  1204. }
  1205. do {
  1206. has_deleted_images = false;
  1207. src_id = FindImage(src_info, src_addr, try_options);
  1208. dst_id = FindImage(dst_info, dst_addr, try_options);
  1209. if (!copy.must_accelerate) {
  1210. do {
  1211. if (!src_id && !dst_id) {
  1212. return std::nullopt;
  1213. }
  1214. if (src_id && True(slot_images[src_id].flags & ImageFlagBits::GpuModified)) {
  1215. break;
  1216. }
  1217. if (dst_id && True(slot_images[dst_id].flags & ImageFlagBits::GpuModified)) {
  1218. break;
  1219. }
  1220. return std::nullopt;
  1221. } while (false);
  1222. }
  1223. const ImageBase* const src_image = src_id ? &slot_images[src_id] : nullptr;
  1224. if (src_image && src_image->info.num_samples > 1) {
  1225. RelaxedOptions find_options{FIND_OPTIONS | RelaxedOptions::ForceBrokenViews};
  1226. src_id = FindOrInsertImage(src_info, src_addr, find_options);
  1227. dst_id = FindOrInsertImage(dst_info, dst_addr, find_options);
  1228. if (has_deleted_images) {
  1229. continue;
  1230. }
  1231. break;
  1232. }
  1233. if (can_be_depth_blit) {
  1234. const ImageBase* const dst_image = dst_id ? &slot_images[dst_id] : nullptr;
  1235. DeduceBlitImages(dst_info, src_info, dst_image, src_image);
  1236. if (GetFormatType(dst_info.format) != GetFormatType(src_info.format)) {
  1237. continue;
  1238. }
  1239. }
  1240. if (!src_id) {
  1241. src_id = InsertImage(src_info, src_addr, RelaxedOptions{});
  1242. }
  1243. if (!dst_id) {
  1244. dst_id = InsertImage(dst_info, dst_addr, RelaxedOptions{});
  1245. }
  1246. } while (has_deleted_images);
  1247. const ImageBase& src_image = slot_images[src_id];
  1248. const ImageBase& dst_image = slot_images[dst_id];
  1249. const bool native_bgr = runtime.HasNativeBgr();
  1250. if (GetFormatType(dst_info.format) != GetFormatType(dst_image.info.format) ||
  1251. GetFormatType(src_info.format) != GetFormatType(src_image.info.format) ||
  1252. !VideoCore::Surface::IsViewCompatible(dst_info.format, dst_image.info.format, false,
  1253. native_bgr) ||
  1254. !VideoCore::Surface::IsViewCompatible(src_info.format, src_image.info.format, false,
  1255. native_bgr)) {
  1256. // Make sure the images match the expected format.
  1257. do {
  1258. has_deleted_images = false;
  1259. src_id = FindOrInsertImage(src_info, src_addr, RelaxedOptions{});
  1260. dst_id = FindOrInsertImage(dst_info, dst_addr, RelaxedOptions{});
  1261. } while (has_deleted_images);
  1262. }
  1263. return {BlitImages{
  1264. .dst_id = dst_id,
  1265. .src_id = src_id,
  1266. .dst_format = dst_info.format,
  1267. .src_format = src_info.format,
  1268. }};
  1269. }
  1270. template <class P>
  1271. SamplerId TextureCache<P>::FindSampler(const TSCEntry& config) {
  1272. if (std::ranges::all_of(config.raw, [](u64 value) { return value == 0; })) {
  1273. return NULL_SAMPLER_ID;
  1274. }
  1275. const auto [pair, is_new] = channel_state->samplers.try_emplace(config);
  1276. if (is_new) {
  1277. pair->second = slot_samplers.insert(runtime, config);
  1278. }
  1279. return pair->second;
  1280. }
  1281. template <class P>
  1282. ImageViewId TextureCache<P>::FindColorBuffer(size_t index, bool is_clear) {
  1283. const auto& regs = maxwell3d->regs;
  1284. if (index >= regs.rt_control.count) {
  1285. return ImageViewId{};
  1286. }
  1287. const auto& rt = regs.rt[index];
  1288. const GPUVAddr gpu_addr = rt.Address();
  1289. if (gpu_addr == 0) {
  1290. return ImageViewId{};
  1291. }
  1292. if (rt.format == Tegra::RenderTargetFormat::NONE) {
  1293. return ImageViewId{};
  1294. }
  1295. const ImageInfo info(regs, index);
  1296. return FindRenderTargetView(info, gpu_addr, is_clear);
  1297. }
  1298. template <class P>
  1299. ImageViewId TextureCache<P>::FindDepthBuffer(bool is_clear) {
  1300. const auto& regs = maxwell3d->regs;
  1301. if (!regs.zeta_enable) {
  1302. return ImageViewId{};
  1303. }
  1304. const GPUVAddr gpu_addr = regs.zeta.Address();
  1305. if (gpu_addr == 0) {
  1306. return ImageViewId{};
  1307. }
  1308. const ImageInfo info(regs);
  1309. return FindRenderTargetView(info, gpu_addr, is_clear);
  1310. }
  1311. template <class P>
  1312. ImageViewId TextureCache<P>::FindRenderTargetView(const ImageInfo& info, GPUVAddr gpu_addr,
  1313. bool is_clear) {
  1314. const auto options = is_clear ? RelaxedOptions::Samples : RelaxedOptions{};
  1315. ImageId image_id{};
  1316. bool delete_state = has_deleted_images;
  1317. do {
  1318. has_deleted_images = false;
  1319. image_id = FindOrInsertImage(info, gpu_addr, options);
  1320. delete_state |= has_deleted_images;
  1321. } while (has_deleted_images);
  1322. has_deleted_images = delete_state;
  1323. if (!image_id) {
  1324. return NULL_IMAGE_VIEW_ID;
  1325. }
  1326. Image& image = slot_images[image_id];
  1327. const ImageViewType view_type = RenderTargetImageViewType(info);
  1328. SubresourceBase base;
  1329. if (image.info.type == ImageType::Linear) {
  1330. base = SubresourceBase{.level = 0, .layer = 0};
  1331. } else {
  1332. base = image.TryFindBase(gpu_addr).value();
  1333. }
  1334. const s32 layers = image.info.type == ImageType::e3D ? info.size.depth : info.resources.layers;
  1335. const SubresourceRange range{
  1336. .base = base,
  1337. .extent = {.levels = 1, .layers = layers},
  1338. };
  1339. return FindOrEmplaceImageView(image_id, ImageViewInfo(view_type, info.format, range));
  1340. }
  1341. template <class P>
  1342. template <typename Func>
  1343. void TextureCache<P>::ForEachImageInRegion(VAddr cpu_addr, size_t size, Func&& func) {
  1344. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1345. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1346. boost::container::small_vector<ImageId, 32> images;
  1347. boost::container::small_vector<ImageMapId, 32> maps;
  1348. ForEachCPUPage(cpu_addr, size, [this, &images, &maps, cpu_addr, size, func](u64 page) {
  1349. const auto it = page_table.find(page);
  1350. if (it == page_table.end()) {
  1351. if constexpr (BOOL_BREAK) {
  1352. return false;
  1353. } else {
  1354. return;
  1355. }
  1356. }
  1357. for (const ImageMapId map_id : it->second) {
  1358. ImageMapView& map = slot_map_views[map_id];
  1359. if (map.picked) {
  1360. continue;
  1361. }
  1362. if (!map.Overlaps(cpu_addr, size)) {
  1363. continue;
  1364. }
  1365. map.picked = true;
  1366. maps.push_back(map_id);
  1367. Image& image = slot_images[map.image_id];
  1368. if (True(image.flags & ImageFlagBits::Picked)) {
  1369. continue;
  1370. }
  1371. image.flags |= ImageFlagBits::Picked;
  1372. images.push_back(map.image_id);
  1373. if constexpr (BOOL_BREAK) {
  1374. if (func(map.image_id, image)) {
  1375. return true;
  1376. }
  1377. } else {
  1378. func(map.image_id, image);
  1379. }
  1380. }
  1381. if constexpr (BOOL_BREAK) {
  1382. return false;
  1383. }
  1384. });
  1385. for (const ImageId image_id : images) {
  1386. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1387. }
  1388. for (const ImageMapId map_id : maps) {
  1389. slot_map_views[map_id].picked = false;
  1390. }
  1391. }
  1392. template <class P>
  1393. template <typename Func>
  1394. void TextureCache<P>::ForEachImageInRegionGPU(size_t as_id, GPUVAddr gpu_addr, size_t size,
  1395. Func&& func) {
  1396. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1397. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1398. boost::container::small_vector<ImageId, 8> images;
  1399. auto storage_id = getStorageID(as_id);
  1400. if (!storage_id) {
  1401. return;
  1402. }
  1403. auto& gpu_page_table = gpu_page_table_storage[*storage_id];
  1404. ForEachGPUPage(gpu_addr, size, [this, gpu_page_table, &images, gpu_addr, size, func](u64 page) {
  1405. const auto it = gpu_page_table.find(page);
  1406. if (it == gpu_page_table.end()) {
  1407. if constexpr (BOOL_BREAK) {
  1408. return false;
  1409. } else {
  1410. return;
  1411. }
  1412. }
  1413. for (const ImageId image_id : it->second) {
  1414. Image& image = slot_images[image_id];
  1415. if (True(image.flags & ImageFlagBits::Picked)) {
  1416. continue;
  1417. }
  1418. if (!image.OverlapsGPU(gpu_addr, size)) {
  1419. continue;
  1420. }
  1421. image.flags |= ImageFlagBits::Picked;
  1422. images.push_back(image_id);
  1423. if constexpr (BOOL_BREAK) {
  1424. if (func(image_id, image)) {
  1425. return true;
  1426. }
  1427. } else {
  1428. func(image_id, image);
  1429. }
  1430. }
  1431. if constexpr (BOOL_BREAK) {
  1432. return false;
  1433. }
  1434. });
  1435. for (const ImageId image_id : images) {
  1436. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1437. }
  1438. }
  1439. template <class P>
  1440. template <typename Func>
  1441. void TextureCache<P>::ForEachSparseImageInRegion(GPUVAddr gpu_addr, size_t size, Func&& func) {
  1442. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  1443. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  1444. boost::container::small_vector<ImageId, 8> images;
  1445. ForEachGPUPage(gpu_addr, size, [this, &images, gpu_addr, size, func](u64 page) {
  1446. const auto it = sparse_page_table.find(page);
  1447. if (it == sparse_page_table.end()) {
  1448. if constexpr (BOOL_BREAK) {
  1449. return false;
  1450. } else {
  1451. return;
  1452. }
  1453. }
  1454. for (const ImageId image_id : it->second) {
  1455. Image& image = slot_images[image_id];
  1456. if (True(image.flags & ImageFlagBits::Picked)) {
  1457. continue;
  1458. }
  1459. if (!image.OverlapsGPU(gpu_addr, size)) {
  1460. continue;
  1461. }
  1462. image.flags |= ImageFlagBits::Picked;
  1463. images.push_back(image_id);
  1464. if constexpr (BOOL_BREAK) {
  1465. if (func(image_id, image)) {
  1466. return true;
  1467. }
  1468. } else {
  1469. func(image_id, image);
  1470. }
  1471. }
  1472. if constexpr (BOOL_BREAK) {
  1473. return false;
  1474. }
  1475. });
  1476. for (const ImageId image_id : images) {
  1477. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1478. }
  1479. }
  1480. template <class P>
  1481. template <typename Func>
  1482. void TextureCache<P>::ForEachSparseSegment(ImageBase& image, Func&& func) {
  1483. using FuncReturn = typename std::invoke_result<Func, GPUVAddr, VAddr, size_t>::type;
  1484. static constexpr bool RETURNS_BOOL = std::is_same_v<FuncReturn, bool>;
  1485. const auto segments = gpu_memory->GetSubmappedRange(image.gpu_addr, image.guest_size_bytes);
  1486. for (const auto& [gpu_addr, size] : segments) {
  1487. std::optional<VAddr> cpu_addr = gpu_memory->GpuToCpuAddress(gpu_addr);
  1488. ASSERT(cpu_addr);
  1489. if constexpr (RETURNS_BOOL) {
  1490. if (func(gpu_addr, *cpu_addr, size)) {
  1491. break;
  1492. }
  1493. } else {
  1494. func(gpu_addr, *cpu_addr, size);
  1495. }
  1496. }
  1497. }
  1498. template <class P>
  1499. ImageViewId TextureCache<P>::FindOrEmplaceImageView(ImageId image_id, const ImageViewInfo& info) {
  1500. Image& image = slot_images[image_id];
  1501. if (const ImageViewId image_view_id = image.FindView(info); image_view_id) {
  1502. return image_view_id;
  1503. }
  1504. const ImageViewId image_view_id =
  1505. slot_image_views.insert(runtime, info, image_id, image, slot_images);
  1506. image.InsertView(info, image_view_id);
  1507. return image_view_id;
  1508. }
  1509. template <class P>
  1510. void TextureCache<P>::RegisterImage(ImageId image_id) {
  1511. ImageBase& image = slot_images[image_id];
  1512. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered),
  1513. "Trying to register an already registered image");
  1514. image.flags |= ImageFlagBits::Registered;
  1515. u64 tentative_size = std::max(image.guest_size_bytes, image.unswizzled_size_bytes);
  1516. if ((IsPixelFormatASTC(image.info.format) &&
  1517. True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
  1518. True(image.flags & ImageFlagBits::Converted)) {
  1519. tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format);
  1520. }
  1521. total_used_memory += Common::AlignUp(tentative_size, 1024);
  1522. if (total_used_memory > critical_memory && critical_gc < GC_EMERGENCY_COUNTS) {
  1523. RunGarbageCollector();
  1524. critical_gc++;
  1525. }
  1526. image.lru_index = lru_cache.Insert(image_id, frame_tick);
  1527. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, image_id](u64 page) {
  1528. (*channel_state->gpu_page_table)[page].push_back(image_id);
  1529. });
  1530. if (False(image.flags & ImageFlagBits::Sparse)) {
  1531. auto map_id =
  1532. slot_map_views.insert(image.gpu_addr, image.cpu_addr, image.guest_size_bytes, image_id);
  1533. ForEachCPUPage(image.cpu_addr, image.guest_size_bytes,
  1534. [this, map_id](u64 page) { page_table[page].push_back(map_id); });
  1535. image.map_view_id = map_id;
  1536. return;
  1537. }
  1538. std::vector<ImageViewId> sparse_maps{};
  1539. ForEachSparseSegment(
  1540. image, [this, image_id, &sparse_maps](GPUVAddr gpu_addr, VAddr cpu_addr, size_t size) {
  1541. auto map_id = slot_map_views.insert(gpu_addr, cpu_addr, size, image_id);
  1542. ForEachCPUPage(cpu_addr, size,
  1543. [this, map_id](u64 page) { page_table[page].push_back(map_id); });
  1544. sparse_maps.push_back(map_id);
  1545. });
  1546. sparse_views.emplace(image_id, std::move(sparse_maps));
  1547. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes,
  1548. [this, image_id](u64 page) { sparse_page_table[page].push_back(image_id); });
  1549. }
  1550. template <class P>
  1551. void TextureCache<P>::UnregisterImage(ImageId image_id) {
  1552. Image& image = slot_images[image_id];
  1553. ASSERT_MSG(True(image.flags & ImageFlagBits::Registered),
  1554. "Trying to unregister an already registered image");
  1555. image.flags &= ~ImageFlagBits::Registered;
  1556. image.flags &= ~ImageFlagBits::BadOverlap;
  1557. lru_cache.Free(image.lru_index);
  1558. const auto& clear_page_table =
  1559. [image_id](u64 page,
  1560. std::unordered_map<u64, std::vector<ImageId>, Common::IdentityHash<u64>>&
  1561. selected_page_table) {
  1562. const auto page_it = selected_page_table.find(page);
  1563. if (page_it == selected_page_table.end()) {
  1564. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1565. return;
  1566. }
  1567. std::vector<ImageId>& image_ids = page_it->second;
  1568. const auto vector_it = std::ranges::find(image_ids, image_id);
  1569. if (vector_it == image_ids.end()) {
  1570. ASSERT_MSG(false, "Unregistering unregistered image in page=0x{:x}",
  1571. page << YUZU_PAGEBITS);
  1572. return;
  1573. }
  1574. image_ids.erase(vector_it);
  1575. };
  1576. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, &clear_page_table](u64 page) {
  1577. clear_page_table(page, (*channel_state->gpu_page_table));
  1578. });
  1579. if (False(image.flags & ImageFlagBits::Sparse)) {
  1580. const auto map_id = image.map_view_id;
  1581. ForEachCPUPage(image.cpu_addr, image.guest_size_bytes, [this, map_id](u64 page) {
  1582. const auto page_it = page_table.find(page);
  1583. if (page_it == page_table.end()) {
  1584. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1585. return;
  1586. }
  1587. std::vector<ImageMapId>& image_map_ids = page_it->second;
  1588. const auto vector_it = std::ranges::find(image_map_ids, map_id);
  1589. if (vector_it == image_map_ids.end()) {
  1590. ASSERT_MSG(false, "Unregistering unregistered image in page=0x{:x}",
  1591. page << YUZU_PAGEBITS);
  1592. return;
  1593. }
  1594. image_map_ids.erase(vector_it);
  1595. });
  1596. slot_map_views.erase(map_id);
  1597. return;
  1598. }
  1599. ForEachGPUPage(image.gpu_addr, image.guest_size_bytes, [this, &clear_page_table](u64 page) {
  1600. clear_page_table(page, sparse_page_table);
  1601. });
  1602. auto it = sparse_views.find(image_id);
  1603. ASSERT(it != sparse_views.end());
  1604. auto& sparse_maps = it->second;
  1605. for (auto& map_view_id : sparse_maps) {
  1606. const auto& map_range = slot_map_views[map_view_id];
  1607. const VAddr cpu_addr = map_range.cpu_addr;
  1608. const std::size_t size = map_range.size;
  1609. ForEachCPUPage(cpu_addr, size, [this, image_id](u64 page) {
  1610. const auto page_it = page_table.find(page);
  1611. if (page_it == page_table.end()) {
  1612. ASSERT_MSG(false, "Unregistering unregistered page=0x{:x}", page << YUZU_PAGEBITS);
  1613. return;
  1614. }
  1615. std::vector<ImageMapId>& image_map_ids = page_it->second;
  1616. auto vector_it = image_map_ids.begin();
  1617. while (vector_it != image_map_ids.end()) {
  1618. ImageMapView& map = slot_map_views[*vector_it];
  1619. if (map.image_id != image_id) {
  1620. vector_it++;
  1621. continue;
  1622. }
  1623. if (!map.picked) {
  1624. map.picked = true;
  1625. }
  1626. vector_it = image_map_ids.erase(vector_it);
  1627. }
  1628. });
  1629. slot_map_views.erase(map_view_id);
  1630. }
  1631. sparse_views.erase(it);
  1632. }
  1633. template <class P>
  1634. void TextureCache<P>::TrackImage(ImageBase& image, ImageId image_id) {
  1635. ASSERT(False(image.flags & ImageFlagBits::Tracked));
  1636. image.flags |= ImageFlagBits::Tracked;
  1637. if (False(image.flags & ImageFlagBits::Sparse)) {
  1638. rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, 1);
  1639. return;
  1640. }
  1641. if (True(image.flags & ImageFlagBits::Registered)) {
  1642. auto it = sparse_views.find(image_id);
  1643. ASSERT(it != sparse_views.end());
  1644. auto& sparse_maps = it->second;
  1645. for (auto& map_view_id : sparse_maps) {
  1646. const auto& map = slot_map_views[map_view_id];
  1647. const VAddr cpu_addr = map.cpu_addr;
  1648. const std::size_t size = map.size;
  1649. rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1);
  1650. }
  1651. return;
  1652. }
  1653. ForEachSparseSegment(image,
  1654. [this]([[maybe_unused]] GPUVAddr gpu_addr, VAddr cpu_addr, size_t size) {
  1655. rasterizer.UpdatePagesCachedCount(cpu_addr, size, 1);
  1656. });
  1657. }
  1658. template <class P>
  1659. void TextureCache<P>::UntrackImage(ImageBase& image, ImageId image_id) {
  1660. ASSERT(True(image.flags & ImageFlagBits::Tracked));
  1661. image.flags &= ~ImageFlagBits::Tracked;
  1662. if (False(image.flags & ImageFlagBits::Sparse)) {
  1663. rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, -1);
  1664. return;
  1665. }
  1666. ASSERT(True(image.flags & ImageFlagBits::Registered));
  1667. auto it = sparse_views.find(image_id);
  1668. ASSERT(it != sparse_views.end());
  1669. auto& sparse_maps = it->second;
  1670. for (auto& map_view_id : sparse_maps) {
  1671. const auto& map = slot_map_views[map_view_id];
  1672. const VAddr cpu_addr = map.cpu_addr;
  1673. const std::size_t size = map.size;
  1674. rasterizer.UpdatePagesCachedCount(cpu_addr, size, -1);
  1675. }
  1676. }
  1677. template <class P>
  1678. void TextureCache<P>::DeleteImage(ImageId image_id, bool immediate_delete) {
  1679. ImageBase& image = slot_images[image_id];
  1680. if (image.HasScaled()) {
  1681. total_used_memory -= GetScaledImageSizeBytes(image);
  1682. }
  1683. u64 tentative_size = std::max(image.guest_size_bytes, image.unswizzled_size_bytes);
  1684. if ((IsPixelFormatASTC(image.info.format) &&
  1685. True(image.flags & ImageFlagBits::AcceleratedUpload)) ||
  1686. True(image.flags & ImageFlagBits::Converted)) {
  1687. tentative_size = EstimatedDecompressedSize(tentative_size, image.info.format);
  1688. }
  1689. total_used_memory -= Common::AlignUp(tentative_size, 1024);
  1690. const GPUVAddr gpu_addr = image.gpu_addr;
  1691. const auto alloc_it = image_allocs_table.find(gpu_addr);
  1692. if (alloc_it == image_allocs_table.end()) {
  1693. ASSERT_MSG(false, "Trying to delete an image alloc that does not exist in address 0x{:x}",
  1694. gpu_addr);
  1695. return;
  1696. }
  1697. const ImageAllocId alloc_id = alloc_it->second;
  1698. std::vector<ImageId>& alloc_images = slot_image_allocs[alloc_id].images;
  1699. const auto alloc_image_it = std::ranges::find(alloc_images, image_id);
  1700. if (alloc_image_it == alloc_images.end()) {
  1701. ASSERT_MSG(false, "Trying to delete an image that does not exist");
  1702. return;
  1703. }
  1704. ASSERT_MSG(False(image.flags & ImageFlagBits::Tracked), "Image was not untracked");
  1705. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered), "Image was not unregistered");
  1706. // Mark render targets as dirty
  1707. auto& dirty = maxwell3d->dirty.flags;
  1708. dirty[Dirty::RenderTargets] = true;
  1709. dirty[Dirty::ZetaBuffer] = true;
  1710. for (size_t rt = 0; rt < NUM_RT; ++rt) {
  1711. dirty[Dirty::ColorBuffer0 + rt] = true;
  1712. }
  1713. const std::span<const ImageViewId> image_view_ids = image.image_view_ids;
  1714. for (const ImageViewId image_view_id : image_view_ids) {
  1715. std::ranges::replace(render_targets.color_buffer_ids, image_view_id, ImageViewId{});
  1716. if (render_targets.depth_buffer_id == image_view_id) {
  1717. render_targets.depth_buffer_id = ImageViewId{};
  1718. }
  1719. }
  1720. RemoveImageViewReferences(image_view_ids);
  1721. RemoveFramebuffers(image_view_ids);
  1722. for (const AliasedImage& alias : image.aliased_images) {
  1723. ImageBase& other_image = slot_images[alias.id];
  1724. [[maybe_unused]] const size_t num_removed_aliases =
  1725. std::erase_if(other_image.aliased_images, [image_id](const AliasedImage& other_alias) {
  1726. return other_alias.id == image_id;
  1727. });
  1728. other_image.CheckAliasState();
  1729. ASSERT_MSG(num_removed_aliases == 1, "Invalid number of removed aliases: {}",
  1730. num_removed_aliases);
  1731. }
  1732. for (const ImageId overlap_id : image.overlapping_images) {
  1733. ImageBase& other_image = slot_images[overlap_id];
  1734. [[maybe_unused]] const size_t num_removed_overlaps = std::erase_if(
  1735. other_image.overlapping_images,
  1736. [image_id](const ImageId other_overlap_id) { return other_overlap_id == image_id; });
  1737. other_image.CheckBadOverlapState();
  1738. ASSERT_MSG(num_removed_overlaps == 1, "Invalid number of removed overlapps: {}",
  1739. num_removed_overlaps);
  1740. }
  1741. for (const ImageViewId image_view_id : image_view_ids) {
  1742. if (!immediate_delete) {
  1743. sentenced_image_view.Push(std::move(slot_image_views[image_view_id]));
  1744. }
  1745. slot_image_views.erase(image_view_id);
  1746. }
  1747. if (!immediate_delete) {
  1748. sentenced_images.Push(std::move(slot_images[image_id]));
  1749. }
  1750. slot_images.erase(image_id);
  1751. alloc_images.erase(alloc_image_it);
  1752. if (alloc_images.empty()) {
  1753. image_allocs_table.erase(alloc_it);
  1754. }
  1755. for (size_t c : active_channel_ids) {
  1756. auto& channel_info = channel_storage[c];
  1757. if constexpr (ENABLE_VALIDATION) {
  1758. std::ranges::fill(channel_info.graphics_image_view_ids, CORRUPT_ID);
  1759. std::ranges::fill(channel_info.compute_image_view_ids, CORRUPT_ID);
  1760. }
  1761. channel_info.graphics_image_table.Invalidate();
  1762. channel_info.compute_image_table.Invalidate();
  1763. }
  1764. has_deleted_images = true;
  1765. }
  1766. template <class P>
  1767. void TextureCache<P>::RemoveImageViewReferences(std::span<const ImageViewId> removed_views) {
  1768. for (size_t c : active_channel_ids) {
  1769. auto& channel_info = channel_storage[c];
  1770. auto it = channel_info.image_views.begin();
  1771. while (it != channel_info.image_views.end()) {
  1772. const auto found = std::ranges::find(removed_views, it->second);
  1773. if (found != removed_views.end()) {
  1774. it = channel_info.image_views.erase(it);
  1775. } else {
  1776. ++it;
  1777. }
  1778. }
  1779. }
  1780. }
  1781. template <class P>
  1782. void TextureCache<P>::RemoveFramebuffers(std::span<const ImageViewId> removed_views) {
  1783. auto it = framebuffers.begin();
  1784. while (it != framebuffers.end()) {
  1785. if (it->first.Contains(removed_views)) {
  1786. auto framebuffer_id = it->second;
  1787. ASSERT(framebuffer_id);
  1788. sentenced_framebuffers.Push(std::move(slot_framebuffers[framebuffer_id]));
  1789. it = framebuffers.erase(it);
  1790. } else {
  1791. ++it;
  1792. }
  1793. }
  1794. }
  1795. template <class P>
  1796. void TextureCache<P>::MarkModification(ImageBase& image) noexcept {
  1797. image.flags |= ImageFlagBits::GpuModified;
  1798. image.modification_tick = ++modification_tick;
  1799. }
  1800. template <class P>
  1801. void TextureCache<P>::SynchronizeAliases(ImageId image_id) {
  1802. boost::container::small_vector<const AliasedImage*, 1> aliased_images;
  1803. Image& image = slot_images[image_id];
  1804. bool any_rescaled = True(image.flags & ImageFlagBits::Rescaled);
  1805. bool any_modified = True(image.flags & ImageFlagBits::GpuModified);
  1806. u64 most_recent_tick = image.modification_tick;
  1807. for (const AliasedImage& aliased : image.aliased_images) {
  1808. ImageBase& aliased_image = slot_images[aliased.id];
  1809. if (image.modification_tick < aliased_image.modification_tick) {
  1810. most_recent_tick = std::max(most_recent_tick, aliased_image.modification_tick);
  1811. aliased_images.push_back(&aliased);
  1812. any_rescaled |= True(aliased_image.flags & ImageFlagBits::Rescaled);
  1813. any_modified |= True(aliased_image.flags & ImageFlagBits::GpuModified);
  1814. }
  1815. }
  1816. if (aliased_images.empty()) {
  1817. return;
  1818. }
  1819. const bool can_rescale = ImageCanRescale(image);
  1820. if (any_rescaled) {
  1821. if (can_rescale) {
  1822. ScaleUp(image);
  1823. } else {
  1824. ScaleDown(image);
  1825. }
  1826. }
  1827. image.modification_tick = most_recent_tick;
  1828. if (any_modified) {
  1829. image.flags |= ImageFlagBits::GpuModified;
  1830. }
  1831. std::ranges::sort(aliased_images, [this](const AliasedImage* lhs, const AliasedImage* rhs) {
  1832. const ImageBase& lhs_image = slot_images[lhs->id];
  1833. const ImageBase& rhs_image = slot_images[rhs->id];
  1834. return lhs_image.modification_tick < rhs_image.modification_tick;
  1835. });
  1836. const auto& resolution = Settings::values.resolution_info;
  1837. for (const AliasedImage* const aliased : aliased_images) {
  1838. if (!resolution.active || !any_rescaled) {
  1839. CopyImage(image_id, aliased->id, aliased->copies);
  1840. continue;
  1841. }
  1842. Image& aliased_image = slot_images[aliased->id];
  1843. if (!can_rescale) {
  1844. ScaleDown(aliased_image);
  1845. CopyImage(image_id, aliased->id, aliased->copies);
  1846. continue;
  1847. }
  1848. ScaleUp(aliased_image);
  1849. CopyImage(image_id, aliased->id, aliased->copies);
  1850. }
  1851. }
  1852. template <class P>
  1853. void TextureCache<P>::PrepareImage(ImageId image_id, bool is_modification, bool invalidate) {
  1854. Image& image = slot_images[image_id];
  1855. if (invalidate) {
  1856. image.flags &= ~(ImageFlagBits::CpuModified | ImageFlagBits::GpuModified);
  1857. if (False(image.flags & ImageFlagBits::Tracked)) {
  1858. TrackImage(image, image_id);
  1859. }
  1860. } else {
  1861. RefreshContents(image, image_id);
  1862. SynchronizeAliases(image_id);
  1863. }
  1864. if (is_modification) {
  1865. MarkModification(image);
  1866. }
  1867. lru_cache.Touch(image.lru_index, frame_tick);
  1868. }
  1869. template <class P>
  1870. void TextureCache<P>::PrepareImageView(ImageViewId image_view_id, bool is_modification,
  1871. bool invalidate) {
  1872. if (!image_view_id) {
  1873. return;
  1874. }
  1875. const ImageViewBase& image_view = slot_image_views[image_view_id];
  1876. if (image_view.IsBuffer()) {
  1877. return;
  1878. }
  1879. PrepareImage(image_view.image_id, is_modification, invalidate);
  1880. }
  1881. template <class P>
  1882. void TextureCache<P>::CopyImage(ImageId dst_id, ImageId src_id, std::vector<ImageCopy> copies) {
  1883. Image& dst = slot_images[dst_id];
  1884. Image& src = slot_images[src_id];
  1885. const bool is_rescaled = True(src.flags & ImageFlagBits::Rescaled);
  1886. if (is_rescaled) {
  1887. ASSERT(True(dst.flags & ImageFlagBits::Rescaled));
  1888. const bool both_2d{src.info.type == ImageType::e2D && dst.info.type == ImageType::e2D};
  1889. const auto& resolution = Settings::values.resolution_info;
  1890. for (auto& copy : copies) {
  1891. copy.src_offset.x = resolution.ScaleUp(copy.src_offset.x);
  1892. copy.dst_offset.x = resolution.ScaleUp(copy.dst_offset.x);
  1893. copy.extent.width = resolution.ScaleUp(copy.extent.width);
  1894. if (both_2d) {
  1895. copy.src_offset.y = resolution.ScaleUp(copy.src_offset.y);
  1896. copy.dst_offset.y = resolution.ScaleUp(copy.dst_offset.y);
  1897. copy.extent.height = resolution.ScaleUp(copy.extent.height);
  1898. }
  1899. }
  1900. }
  1901. const auto dst_format_type = GetFormatType(dst.info.format);
  1902. const auto src_format_type = GetFormatType(src.info.format);
  1903. if (src_format_type == dst_format_type) {
  1904. if constexpr (HAS_EMULATED_COPIES) {
  1905. if (!runtime.CanImageBeCopied(dst, src)) {
  1906. return runtime.EmulateCopyImage(dst, src, copies);
  1907. }
  1908. }
  1909. return runtime.CopyImage(dst, src, copies);
  1910. }
  1911. UNIMPLEMENTED_IF(dst.info.type != ImageType::e2D);
  1912. UNIMPLEMENTED_IF(src.info.type != ImageType::e2D);
  1913. if (runtime.ShouldReinterpret(dst, src)) {
  1914. return runtime.ReinterpretImage(dst, src, copies);
  1915. }
  1916. for (const ImageCopy& copy : copies) {
  1917. UNIMPLEMENTED_IF(copy.dst_subresource.num_layers != 1);
  1918. UNIMPLEMENTED_IF(copy.src_subresource.num_layers != 1);
  1919. UNIMPLEMENTED_IF(copy.src_offset != Offset3D{});
  1920. UNIMPLEMENTED_IF(copy.dst_offset != Offset3D{});
  1921. const SubresourceBase dst_base{
  1922. .level = copy.dst_subresource.base_level,
  1923. .layer = copy.dst_subresource.base_layer,
  1924. };
  1925. const SubresourceBase src_base{
  1926. .level = copy.src_subresource.base_level,
  1927. .layer = copy.src_subresource.base_layer,
  1928. };
  1929. const SubresourceExtent dst_extent{.levels = 1, .layers = 1};
  1930. const SubresourceExtent src_extent{.levels = 1, .layers = 1};
  1931. const SubresourceRange dst_range{.base = dst_base, .extent = dst_extent};
  1932. const SubresourceRange src_range{.base = src_base, .extent = src_extent};
  1933. PixelFormat dst_format = dst.info.format;
  1934. if (GetFormatType(src.info.format) == SurfaceType::DepthStencil &&
  1935. GetFormatType(dst_format) == SurfaceType::ColorTexture &&
  1936. BytesPerBlock(dst_format) == 4) {
  1937. dst_format = PixelFormat::A8B8G8R8_UNORM;
  1938. }
  1939. const ImageViewInfo dst_view_info(ImageViewType::e2D, dst_format, dst_range);
  1940. const ImageViewInfo src_view_info(ImageViewType::e2D, src.info.format, src_range);
  1941. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  1942. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  1943. const ImageViewId src_view_id = FindOrEmplaceImageView(src_id, src_view_info);
  1944. ImageView& dst_view = slot_image_views[dst_view_id];
  1945. ImageView& src_view = slot_image_views[src_view_id];
  1946. [[maybe_unused]] const Extent3D expected_size{
  1947. .width = std::min(dst_view.size.width, src_view.size.width),
  1948. .height = std::min(dst_view.size.height, src_view.size.height),
  1949. .depth = std::min(dst_view.size.depth, src_view.size.depth),
  1950. };
  1951. const Extent3D scaled_extent = [is_rescaled, expected_size]() {
  1952. if (!is_rescaled) {
  1953. return expected_size;
  1954. }
  1955. const auto& resolution = Settings::values.resolution_info;
  1956. return Extent3D{
  1957. .width = resolution.ScaleUp(expected_size.width),
  1958. .height = resolution.ScaleUp(expected_size.height),
  1959. .depth = expected_size.depth,
  1960. };
  1961. }();
  1962. UNIMPLEMENTED_IF(copy.extent != scaled_extent);
  1963. runtime.ConvertImage(dst_framebuffer, dst_view, src_view);
  1964. }
  1965. }
  1966. template <class P>
  1967. void TextureCache<P>::BindRenderTarget(ImageViewId* old_id, ImageViewId new_id) {
  1968. if (*old_id == new_id) {
  1969. return;
  1970. }
  1971. if (new_id) {
  1972. const ImageViewBase& old_view = slot_image_views[new_id];
  1973. if (True(old_view.flags & ImageViewFlagBits::PreemtiveDownload)) {
  1974. uncommitted_downloads.push_back(old_view.image_id);
  1975. }
  1976. }
  1977. *old_id = new_id;
  1978. }
  1979. template <class P>
  1980. std::pair<FramebufferId, ImageViewId> TextureCache<P>::RenderTargetFromImage(
  1981. ImageId image_id, const ImageViewInfo& view_info) {
  1982. const ImageViewId view_id = FindOrEmplaceImageView(image_id, view_info);
  1983. const ImageBase& image = slot_images[image_id];
  1984. const bool is_rescaled = True(image.flags & ImageFlagBits::Rescaled);
  1985. const bool is_color = GetFormatType(image.info.format) == SurfaceType::ColorTexture;
  1986. const ImageViewId color_view_id = is_color ? view_id : ImageViewId{};
  1987. const ImageViewId depth_view_id = is_color ? ImageViewId{} : view_id;
  1988. Extent3D extent = MipSize(image.info.size, view_info.range.base.level);
  1989. if (is_rescaled) {
  1990. const auto& resolution = Settings::values.resolution_info;
  1991. extent.width = resolution.ScaleUp(extent.width);
  1992. if (image.info.type == ImageType::e2D) {
  1993. extent.height = resolution.ScaleUp(extent.height);
  1994. }
  1995. }
  1996. const u32 num_samples = image.info.num_samples;
  1997. const auto [samples_x, samples_y] = SamplesLog2(num_samples);
  1998. const FramebufferId framebuffer_id = GetFramebufferId(RenderTargets{
  1999. .color_buffer_ids = {color_view_id},
  2000. .depth_buffer_id = depth_view_id,
  2001. .size = {extent.width >> samples_x, extent.height >> samples_y},
  2002. .is_rescaled = is_rescaled,
  2003. });
  2004. return {framebuffer_id, view_id};
  2005. }
  2006. template <class P>
  2007. bool TextureCache<P>::IsFullClear(ImageViewId id) {
  2008. if (!id) {
  2009. return true;
  2010. }
  2011. const ImageViewBase& image_view = slot_image_views[id];
  2012. const ImageBase& image = slot_images[image_view.image_id];
  2013. const Extent3D size = image_view.size;
  2014. const auto& regs = maxwell3d->regs;
  2015. const auto& scissor = regs.scissor_test[0];
  2016. if (image.info.resources.levels > 1 || image.info.resources.layers > 1) {
  2017. // Images with multiple resources can't be cleared in a single call
  2018. return false;
  2019. }
  2020. if (regs.clear_control.use_scissor == 0) {
  2021. // If scissor testing is disabled, the clear is always full
  2022. return true;
  2023. }
  2024. // Make sure the clear covers all texels in the subresource
  2025. return scissor.min_x == 0 && scissor.min_y == 0 && scissor.max_x >= size.width &&
  2026. scissor.max_y >= size.height;
  2027. }
  2028. template <class P>
  2029. void TextureCache<P>::CreateChannel(struct Tegra::Control::ChannelState& channel) {
  2030. VideoCommon::ChannelSetupCaches<TextureCacheChannelInfo>::CreateChannel(channel);
  2031. const auto it = channel_map.find(channel.bind_id);
  2032. auto* this_state = &channel_storage[it->second];
  2033. const auto& this_as_ref = address_spaces[channel.memory_manager->GetID()];
  2034. this_state->gpu_page_table = &gpu_page_table_storage[this_as_ref.storage_id];
  2035. }
  2036. /// Bind a channel for execution.
  2037. template <class P>
  2038. void TextureCache<P>::OnGPUASRegister([[maybe_unused]] size_t map_id) {
  2039. gpu_page_table_storage.emplace_back();
  2040. }
  2041. } // namespace VideoCommon