texture_cache.h 99 KB

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