texture_cache.h 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495
  1. // Copyright 2019 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <algorithm>
  6. #include <array>
  7. #include <bit>
  8. #include <memory>
  9. #include <mutex>
  10. #include <optional>
  11. #include <span>
  12. #include <type_traits>
  13. #include <unordered_map>
  14. #include <utility>
  15. #include <vector>
  16. #include <boost/container/small_vector.hpp>
  17. #include "common/alignment.h"
  18. #include "common/common_funcs.h"
  19. #include "common/common_types.h"
  20. #include "common/logging/log.h"
  21. #include "video_core/compatible_formats.h"
  22. #include "video_core/delayed_destruction_ring.h"
  23. #include "video_core/dirty_flags.h"
  24. #include "video_core/engines/fermi_2d.h"
  25. #include "video_core/engines/kepler_compute.h"
  26. #include "video_core/engines/maxwell_3d.h"
  27. #include "video_core/memory_manager.h"
  28. #include "video_core/rasterizer_interface.h"
  29. #include "video_core/surface.h"
  30. #include "video_core/texture_cache/descriptor_table.h"
  31. #include "video_core/texture_cache/format_lookup_table.h"
  32. #include "video_core/texture_cache/formatter.h"
  33. #include "video_core/texture_cache/image_base.h"
  34. #include "video_core/texture_cache/image_info.h"
  35. #include "video_core/texture_cache/image_view_base.h"
  36. #include "video_core/texture_cache/image_view_info.h"
  37. #include "video_core/texture_cache/render_targets.h"
  38. #include "video_core/texture_cache/samples_helper.h"
  39. #include "video_core/texture_cache/slot_vector.h"
  40. #include "video_core/texture_cache/types.h"
  41. #include "video_core/texture_cache/util.h"
  42. #include "video_core/textures/texture.h"
  43. namespace VideoCommon {
  44. using Tegra::Texture::SwizzleSource;
  45. using Tegra::Texture::TextureType;
  46. using Tegra::Texture::TICEntry;
  47. using Tegra::Texture::TSCEntry;
  48. using VideoCore::Surface::GetFormatType;
  49. using VideoCore::Surface::IsCopyCompatible;
  50. using VideoCore::Surface::PixelFormat;
  51. using VideoCore::Surface::PixelFormatFromDepthFormat;
  52. using VideoCore::Surface::PixelFormatFromRenderTargetFormat;
  53. using VideoCore::Surface::SurfaceType;
  54. template <class P>
  55. class TextureCache {
  56. /// Address shift for caching images into a hash table
  57. static constexpr u64 PAGE_BITS = 20;
  58. /// Enables debugging features to the texture cache
  59. static constexpr bool ENABLE_VALIDATION = P::ENABLE_VALIDATION;
  60. /// Implement blits as copies between framebuffers
  61. static constexpr bool FRAMEBUFFER_BLITS = P::FRAMEBUFFER_BLITS;
  62. /// True when some copies have to be emulated
  63. static constexpr bool HAS_EMULATED_COPIES = P::HAS_EMULATED_COPIES;
  64. /// Image view ID for null descriptors
  65. static constexpr ImageViewId NULL_IMAGE_VIEW_ID{0};
  66. /// Sampler ID for bugged sampler ids
  67. static constexpr SamplerId NULL_SAMPLER_ID{0};
  68. using Runtime = typename P::Runtime;
  69. using Image = typename P::Image;
  70. using ImageAlloc = typename P::ImageAlloc;
  71. using ImageView = typename P::ImageView;
  72. using Sampler = typename P::Sampler;
  73. using Framebuffer = typename P::Framebuffer;
  74. struct BlitImages {
  75. ImageId dst_id;
  76. ImageId src_id;
  77. PixelFormat dst_format;
  78. PixelFormat src_format;
  79. };
  80. template <typename T>
  81. struct IdentityHash {
  82. [[nodiscard]] size_t operator()(T value) const noexcept {
  83. return static_cast<size_t>(value);
  84. }
  85. };
  86. public:
  87. explicit TextureCache(Runtime&, VideoCore::RasterizerInterface&, Tegra::Engines::Maxwell3D&,
  88. Tegra::Engines::KeplerCompute&, Tegra::MemoryManager&);
  89. /// Notify the cache that a new frame has been queued
  90. void TickFrame();
  91. /// Return a constant reference to the given image view id
  92. [[nodiscard]] const ImageView& GetImageView(ImageViewId id) const noexcept;
  93. /// Return a reference to the given image view id
  94. [[nodiscard]] ImageView& GetImageView(ImageViewId id) noexcept;
  95. /// Fill image_view_ids with the graphics images in indices
  96. void FillGraphicsImageViews(std::span<const u32> indices,
  97. std::span<ImageViewId> image_view_ids);
  98. /// Fill image_view_ids with the compute images in indices
  99. void FillComputeImageViews(std::span<const u32> indices, std::span<ImageViewId> image_view_ids);
  100. /// Get the sampler from the graphics descriptor table in the specified index
  101. Sampler* GetGraphicsSampler(u32 index);
  102. /// Get the sampler from the compute descriptor table in the specified index
  103. Sampler* GetComputeSampler(u32 index);
  104. /// Refresh the state for graphics image view and sampler descriptors
  105. void SynchronizeGraphicsDescriptors();
  106. /// Refresh the state for compute image view and sampler descriptors
  107. void SynchronizeComputeDescriptors();
  108. /// Update bound render targets and upload memory if necessary
  109. /// @param is_clear True when the render targets are being used for clears
  110. void UpdateRenderTargets(bool is_clear);
  111. /// Find a framebuffer with the currently bound render targets
  112. /// UpdateRenderTargets should be called before this
  113. Framebuffer* GetFramebuffer();
  114. /// Mark images in a range as modified from the CPU
  115. void WriteMemory(VAddr cpu_addr, size_t size);
  116. /// Download contents of host images to guest memory in a region
  117. void DownloadMemory(VAddr cpu_addr, size_t size);
  118. /// Remove images in a region
  119. void UnmapMemory(VAddr cpu_addr, size_t size);
  120. /// Blit an image with the given parameters
  121. void BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
  122. const Tegra::Engines::Fermi2D::Surface& src,
  123. const Tegra::Engines::Fermi2D::Config& copy,
  124. std::optional<Region2D> src_region_override = {},
  125. std::optional<Region2D> dst_region_override = {});
  126. /// Invalidate the contents of the color buffer index
  127. /// These contents become unspecified, the cache can assume aggressive optimizations.
  128. void InvalidateColorBuffer(size_t index);
  129. /// Invalidate the contents of the depth buffer
  130. /// These contents become unspecified, the cache can assume aggressive optimizations.
  131. void InvalidateDepthBuffer();
  132. /// Try to find a cached image view in the given CPU address
  133. [[nodiscard]] ImageView* TryFindFramebufferImageView(VAddr cpu_addr);
  134. /// Return true when there are uncommitted images to be downloaded
  135. [[nodiscard]] bool HasUncommittedFlushes() const noexcept;
  136. /// Return true when the caller should wait for async downloads
  137. [[nodiscard]] bool ShouldWaitAsyncFlushes() const noexcept;
  138. /// Commit asynchronous downloads
  139. void CommitAsyncFlushes();
  140. /// Pop asynchronous downloads
  141. void PopAsyncFlushes();
  142. /// Return true when a CPU region is modified from the GPU
  143. [[nodiscard]] bool IsRegionGpuModified(VAddr addr, size_t size);
  144. std::mutex mutex;
  145. private:
  146. /// Iterate over all page indices in a range
  147. template <typename Func>
  148. static void ForEachPage(VAddr addr, size_t size, Func&& func) {
  149. static constexpr bool RETURNS_BOOL = std::is_same_v<std::invoke_result<Func, u64>, bool>;
  150. const u64 page_end = (addr + size - 1) >> PAGE_BITS;
  151. for (u64 page = addr >> PAGE_BITS; page <= page_end; ++page) {
  152. if constexpr (RETURNS_BOOL) {
  153. if (func(page)) {
  154. break;
  155. }
  156. } else {
  157. func(page);
  158. }
  159. }
  160. }
  161. /// Fills image_view_ids in the image views in indices
  162. void FillImageViews(DescriptorTable<TICEntry>& table,
  163. std::span<ImageViewId> cached_image_view_ids, std::span<const u32> indices,
  164. std::span<ImageViewId> image_view_ids);
  165. /// Find or create an image view in the guest descriptor table
  166. ImageViewId VisitImageView(DescriptorTable<TICEntry>& table,
  167. std::span<ImageViewId> cached_image_view_ids, u32 index);
  168. /// Find or create a framebuffer with the given render target parameters
  169. FramebufferId GetFramebufferId(const RenderTargets& key);
  170. /// Refresh the contents (pixel data) of an image
  171. void RefreshContents(Image& image);
  172. /// Upload data from guest to an image
  173. template <typename StagingBuffer>
  174. void UploadImageContents(Image& image, StagingBuffer& staging_buffer);
  175. /// Find or create an image view from a guest descriptor
  176. [[nodiscard]] ImageViewId FindImageView(const TICEntry& config);
  177. /// Create a new image view from a guest descriptor
  178. [[nodiscard]] ImageViewId CreateImageView(const TICEntry& config);
  179. /// Find or create an image from the given parameters
  180. [[nodiscard]] ImageId FindOrInsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  181. RelaxedOptions options = RelaxedOptions{});
  182. /// Find an image from the given parameters
  183. [[nodiscard]] ImageId FindImage(const ImageInfo& info, GPUVAddr gpu_addr,
  184. RelaxedOptions options);
  185. /// Create an image from the given parameters
  186. [[nodiscard]] ImageId InsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  187. RelaxedOptions options);
  188. /// Create a new image and join perfectly matching existing images
  189. /// Remove joined images from the cache
  190. [[nodiscard]] ImageId JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VAddr cpu_addr);
  191. /// Return a blit image pair from the given guest blit parameters
  192. [[nodiscard]] BlitImages GetBlitImages(const Tegra::Engines::Fermi2D::Surface& dst,
  193. const Tegra::Engines::Fermi2D::Surface& src);
  194. /// Find or create a sampler from a guest descriptor sampler
  195. [[nodiscard]] SamplerId FindSampler(const TSCEntry& config);
  196. /// Find or create an image view for the given color buffer index
  197. [[nodiscard]] ImageViewId FindColorBuffer(size_t index, bool is_clear);
  198. /// Find or create an image view for the depth buffer
  199. [[nodiscard]] ImageViewId FindDepthBuffer(bool is_clear);
  200. /// Find or create a view for a render target with the given image parameters
  201. [[nodiscard]] ImageViewId FindRenderTargetView(const ImageInfo& info, GPUVAddr gpu_addr,
  202. bool is_clear);
  203. /// Iterates over all the images in a region calling func
  204. template <typename Func>
  205. void ForEachImageInRegion(VAddr cpu_addr, size_t size, Func&& func);
  206. /// Find or create an image view in the given image with the passed parameters
  207. [[nodiscard]] ImageViewId FindOrEmplaceImageView(ImageId image_id, const ImageViewInfo& info);
  208. /// Register image in the page table
  209. void RegisterImage(ImageId image);
  210. /// Unregister image from the page table
  211. void UnregisterImage(ImageId image);
  212. /// Track CPU reads and writes for image
  213. void TrackImage(ImageBase& image);
  214. /// Stop tracking CPU reads and writes for image
  215. void UntrackImage(ImageBase& image);
  216. /// Delete image from the cache
  217. void DeleteImage(ImageId image);
  218. /// Remove image views references from the cache
  219. void RemoveImageViewReferences(std::span<const ImageViewId> removed_views);
  220. /// Remove framebuffers using the given image views from the cache
  221. void RemoveFramebuffers(std::span<const ImageViewId> removed_views);
  222. /// Mark an image as modified from the GPU
  223. void MarkModification(ImageBase& image) noexcept;
  224. /// Synchronize image aliases, copying data if needed
  225. void SynchronizeAliases(ImageId image_id);
  226. /// Prepare an image to be used
  227. void PrepareImage(ImageId image_id, bool is_modification, bool invalidate);
  228. /// Prepare an image view to be used
  229. void PrepareImageView(ImageViewId image_view_id, bool is_modification, bool invalidate);
  230. /// Execute copies from one image to the other, even if they are incompatible
  231. void CopyImage(ImageId dst_id, ImageId src_id, std::span<const ImageCopy> copies);
  232. /// Bind an image view as render target, downloading resources preemtively if needed
  233. void BindRenderTarget(ImageViewId* old_id, ImageViewId new_id);
  234. /// Create a render target from a given image and image view parameters
  235. [[nodiscard]] std::pair<FramebufferId, ImageViewId> RenderTargetFromImage(
  236. ImageId, const ImageViewInfo& view_info);
  237. /// Returns true if the current clear parameters clear the whole image of a given image view
  238. [[nodiscard]] bool IsFullClear(ImageViewId id);
  239. Runtime& runtime;
  240. VideoCore::RasterizerInterface& rasterizer;
  241. Tegra::Engines::Maxwell3D& maxwell3d;
  242. Tegra::Engines::KeplerCompute& kepler_compute;
  243. Tegra::MemoryManager& gpu_memory;
  244. DescriptorTable<TICEntry> graphics_image_table{gpu_memory};
  245. DescriptorTable<TSCEntry> graphics_sampler_table{gpu_memory};
  246. std::vector<SamplerId> graphics_sampler_ids;
  247. std::vector<ImageViewId> graphics_image_view_ids;
  248. DescriptorTable<TICEntry> compute_image_table{gpu_memory};
  249. DescriptorTable<TSCEntry> compute_sampler_table{gpu_memory};
  250. std::vector<SamplerId> compute_sampler_ids;
  251. std::vector<ImageViewId> compute_image_view_ids;
  252. RenderTargets render_targets;
  253. std::unordered_map<TICEntry, ImageViewId> image_views;
  254. std::unordered_map<TSCEntry, SamplerId> samplers;
  255. std::unordered_map<RenderTargets, FramebufferId> framebuffers;
  256. std::unordered_map<u64, std::vector<ImageId>, IdentityHash<u64>> page_table;
  257. bool has_deleted_images = false;
  258. SlotVector<Image> slot_images;
  259. SlotVector<ImageView> slot_image_views;
  260. SlotVector<ImageAlloc> slot_image_allocs;
  261. SlotVector<Sampler> slot_samplers;
  262. SlotVector<Framebuffer> slot_framebuffers;
  263. // TODO: This data structure is not optimal and it should be reworked
  264. std::vector<ImageId> uncommitted_downloads;
  265. std::queue<std::vector<ImageId>> committed_downloads;
  266. static constexpr size_t TICKS_TO_DESTROY = 6;
  267. DelayedDestructionRing<Image, TICKS_TO_DESTROY> sentenced_images;
  268. DelayedDestructionRing<ImageView, TICKS_TO_DESTROY> sentenced_image_view;
  269. DelayedDestructionRing<Framebuffer, TICKS_TO_DESTROY> sentenced_framebuffers;
  270. std::unordered_map<GPUVAddr, ImageAllocId> image_allocs_table;
  271. u64 modification_tick = 0;
  272. u64 frame_tick = 0;
  273. };
  274. template <class P>
  275. TextureCache<P>::TextureCache(Runtime& runtime_, VideoCore::RasterizerInterface& rasterizer_,
  276. Tegra::Engines::Maxwell3D& maxwell3d_,
  277. Tegra::Engines::KeplerCompute& kepler_compute_,
  278. Tegra::MemoryManager& gpu_memory_)
  279. : runtime{runtime_}, rasterizer{rasterizer_}, maxwell3d{maxwell3d_},
  280. kepler_compute{kepler_compute_}, gpu_memory{gpu_memory_} {
  281. // Configure null sampler
  282. TSCEntry sampler_descriptor{};
  283. sampler_descriptor.min_filter.Assign(Tegra::Texture::TextureFilter::Linear);
  284. sampler_descriptor.mag_filter.Assign(Tegra::Texture::TextureFilter::Linear);
  285. sampler_descriptor.mipmap_filter.Assign(Tegra::Texture::TextureMipmapFilter::Linear);
  286. sampler_descriptor.cubemap_anisotropy.Assign(1);
  287. // Make sure the first index is reserved for the null resources
  288. // This way the null resource becomes a compile time constant
  289. void(slot_image_views.insert(runtime, NullImageParams{}));
  290. void(slot_samplers.insert(runtime, sampler_descriptor));
  291. }
  292. template <class P>
  293. void TextureCache<P>::TickFrame() {
  294. // Tick sentenced resources in this order to ensure they are destroyed in the right order
  295. sentenced_images.Tick();
  296. sentenced_framebuffers.Tick();
  297. sentenced_image_view.Tick();
  298. ++frame_tick;
  299. }
  300. template <class P>
  301. const typename P::ImageView& TextureCache<P>::GetImageView(ImageViewId id) const noexcept {
  302. return slot_image_views[id];
  303. }
  304. template <class P>
  305. typename P::ImageView& TextureCache<P>::GetImageView(ImageViewId id) noexcept {
  306. return slot_image_views[id];
  307. }
  308. template <class P>
  309. void TextureCache<P>::FillGraphicsImageViews(std::span<const u32> indices,
  310. std::span<ImageViewId> image_view_ids) {
  311. FillImageViews(graphics_image_table, graphics_image_view_ids, indices, image_view_ids);
  312. }
  313. template <class P>
  314. void TextureCache<P>::FillComputeImageViews(std::span<const u32> indices,
  315. std::span<ImageViewId> image_view_ids) {
  316. FillImageViews(compute_image_table, compute_image_view_ids, indices, image_view_ids);
  317. }
  318. template <class P>
  319. typename P::Sampler* TextureCache<P>::GetGraphicsSampler(u32 index) {
  320. [[unlikely]] if (index > graphics_sampler_table.Limit()) {
  321. LOG_ERROR(HW_GPU, "Invalid sampler index={}", index);
  322. return &slot_samplers[NULL_SAMPLER_ID];
  323. }
  324. const auto [descriptor, is_new] = graphics_sampler_table.Read(index);
  325. SamplerId& id = graphics_sampler_ids[index];
  326. [[unlikely]] if (is_new) {
  327. id = FindSampler(descriptor);
  328. }
  329. return &slot_samplers[id];
  330. }
  331. template <class P>
  332. typename P::Sampler* TextureCache<P>::GetComputeSampler(u32 index) {
  333. [[unlikely]] if (index > compute_sampler_table.Limit()) {
  334. LOG_ERROR(HW_GPU, "Invalid sampler index={}", index);
  335. return &slot_samplers[NULL_SAMPLER_ID];
  336. }
  337. const auto [descriptor, is_new] = compute_sampler_table.Read(index);
  338. SamplerId& id = compute_sampler_ids[index];
  339. [[unlikely]] if (is_new) {
  340. id = FindSampler(descriptor);
  341. }
  342. return &slot_samplers[id];
  343. }
  344. template <class P>
  345. void TextureCache<P>::SynchronizeGraphicsDescriptors() {
  346. using SamplerIndex = Tegra::Engines::Maxwell3D::Regs::SamplerIndex;
  347. const bool linked_tsc = maxwell3d.regs.sampler_index == SamplerIndex::ViaHeaderIndex;
  348. const u32 tic_limit = maxwell3d.regs.tic.limit;
  349. const u32 tsc_limit = linked_tsc ? tic_limit : maxwell3d.regs.tsc.limit;
  350. if (graphics_sampler_table.Synchornize(maxwell3d.regs.tsc.Address(), tsc_limit)) {
  351. graphics_sampler_ids.resize(tsc_limit + 1, CORRUPT_ID);
  352. }
  353. if (graphics_image_table.Synchornize(maxwell3d.regs.tic.Address(), tic_limit)) {
  354. graphics_image_view_ids.resize(tic_limit + 1, CORRUPT_ID);
  355. }
  356. }
  357. template <class P>
  358. void TextureCache<P>::SynchronizeComputeDescriptors() {
  359. const bool linked_tsc = kepler_compute.launch_description.linked_tsc;
  360. const u32 tic_limit = kepler_compute.regs.tic.limit;
  361. const u32 tsc_limit = linked_tsc ? tic_limit : kepler_compute.regs.tsc.limit;
  362. const GPUVAddr tsc_gpu_addr = kepler_compute.regs.tsc.Address();
  363. if (compute_sampler_table.Synchornize(tsc_gpu_addr, tsc_limit)) {
  364. compute_sampler_ids.resize(tsc_limit + 1, CORRUPT_ID);
  365. }
  366. if (compute_image_table.Synchornize(kepler_compute.regs.tic.Address(), tic_limit)) {
  367. compute_image_view_ids.resize(tic_limit + 1, CORRUPT_ID);
  368. }
  369. }
  370. template <class P>
  371. void TextureCache<P>::UpdateRenderTargets(bool is_clear) {
  372. using namespace VideoCommon::Dirty;
  373. auto& flags = maxwell3d.dirty.flags;
  374. if (!flags[Dirty::RenderTargets]) {
  375. return;
  376. }
  377. flags[Dirty::RenderTargets] = false;
  378. // Render target control is used on all render targets, so force look ups when this one is up
  379. const bool force = flags[Dirty::RenderTargetControl];
  380. flags[Dirty::RenderTargetControl] = false;
  381. for (size_t index = 0; index < NUM_RT; ++index) {
  382. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  383. if (flags[Dirty::ColorBuffer0 + index] || force) {
  384. flags[Dirty::ColorBuffer0 + index] = false;
  385. BindRenderTarget(&color_buffer_id, FindColorBuffer(index, is_clear));
  386. }
  387. PrepareImageView(color_buffer_id, true, is_clear && IsFullClear(color_buffer_id));
  388. }
  389. if (flags[Dirty::ZetaBuffer] || force) {
  390. flags[Dirty::ZetaBuffer] = false;
  391. BindRenderTarget(&render_targets.depth_buffer_id, FindDepthBuffer(is_clear));
  392. }
  393. const ImageViewId depth_buffer_id = render_targets.depth_buffer_id;
  394. PrepareImageView(depth_buffer_id, true, is_clear && IsFullClear(depth_buffer_id));
  395. for (size_t index = 0; index < NUM_RT; ++index) {
  396. render_targets.draw_buffers[index] = static_cast<u8>(maxwell3d.regs.rt_control.Map(index));
  397. }
  398. render_targets.size = Extent2D{
  399. maxwell3d.regs.render_area.width,
  400. maxwell3d.regs.render_area.height,
  401. };
  402. }
  403. template <class P>
  404. typename P::Framebuffer* TextureCache<P>::GetFramebuffer() {
  405. return &slot_framebuffers[GetFramebufferId(render_targets)];
  406. }
  407. template <class P>
  408. void TextureCache<P>::FillImageViews(DescriptorTable<TICEntry>& table,
  409. std::span<ImageViewId> cached_image_view_ids,
  410. std::span<const u32> indices,
  411. std::span<ImageViewId> image_view_ids) {
  412. ASSERT(indices.size() <= image_view_ids.size());
  413. do {
  414. has_deleted_images = false;
  415. std::ranges::transform(indices, image_view_ids.begin(), [&](u32 index) {
  416. return VisitImageView(table, cached_image_view_ids, index);
  417. });
  418. } while (has_deleted_images);
  419. }
  420. template <class P>
  421. ImageViewId TextureCache<P>::VisitImageView(DescriptorTable<TICEntry>& table,
  422. std::span<ImageViewId> cached_image_view_ids,
  423. u32 index) {
  424. if (index > table.Limit()) {
  425. LOG_ERROR(HW_GPU, "Invalid image view index={}", index);
  426. return NULL_IMAGE_VIEW_ID;
  427. }
  428. const auto [descriptor, is_new] = table.Read(index);
  429. ImageViewId& image_view_id = cached_image_view_ids[index];
  430. if (is_new) {
  431. image_view_id = FindImageView(descriptor);
  432. }
  433. if (image_view_id != NULL_IMAGE_VIEW_ID) {
  434. PrepareImageView(image_view_id, false, false);
  435. }
  436. return image_view_id;
  437. }
  438. template <class P>
  439. FramebufferId TextureCache<P>::GetFramebufferId(const RenderTargets& key) {
  440. const auto [pair, is_new] = framebuffers.try_emplace(key);
  441. FramebufferId& framebuffer_id = pair->second;
  442. if (!is_new) {
  443. return framebuffer_id;
  444. }
  445. std::array<ImageView*, NUM_RT> color_buffers;
  446. std::ranges::transform(key.color_buffer_ids, color_buffers.begin(),
  447. [this](ImageViewId id) { return id ? &slot_image_views[id] : nullptr; });
  448. ImageView* const depth_buffer =
  449. key.depth_buffer_id ? &slot_image_views[key.depth_buffer_id] : nullptr;
  450. framebuffer_id = slot_framebuffers.insert(runtime, color_buffers, depth_buffer, key);
  451. return framebuffer_id;
  452. }
  453. template <class P>
  454. void TextureCache<P>::WriteMemory(VAddr cpu_addr, size_t size) {
  455. ForEachImageInRegion(cpu_addr, size, [this](ImageId image_id, Image& image) {
  456. if (True(image.flags & ImageFlagBits::CpuModified)) {
  457. return;
  458. }
  459. image.flags |= ImageFlagBits::CpuModified;
  460. UntrackImage(image);
  461. });
  462. }
  463. template <class P>
  464. void TextureCache<P>::DownloadMemory(VAddr cpu_addr, size_t size) {
  465. std::vector<ImageId> images;
  466. ForEachImageInRegion(cpu_addr, size, [this, &images](ImageId image_id, ImageBase& image) {
  467. // Skip images that were not modified from the GPU
  468. if (False(image.flags & ImageFlagBits::GpuModified)) {
  469. return;
  470. }
  471. // Skip images that .are. modified from the CPU
  472. // We don't want to write sensitive data from the guest
  473. if (True(image.flags & ImageFlagBits::CpuModified)) {
  474. return;
  475. }
  476. if (image.info.num_samples > 1) {
  477. LOG_WARNING(HW_GPU, "MSAA image downloads are not implemented");
  478. return;
  479. }
  480. image.flags &= ~ImageFlagBits::GpuModified;
  481. images.push_back(image_id);
  482. });
  483. if (images.empty()) {
  484. return;
  485. }
  486. std::ranges::sort(images, [this](ImageId lhs, ImageId rhs) {
  487. return slot_images[lhs].modification_tick < slot_images[rhs].modification_tick;
  488. });
  489. for (const ImageId image_id : images) {
  490. Image& image = slot_images[image_id];
  491. auto map = runtime.DownloadStagingBuffer(image.unswizzled_size_bytes);
  492. const auto copies = FullDownloadCopies(image.info);
  493. image.DownloadMemory(map, copies);
  494. runtime.Finish();
  495. SwizzleImage(gpu_memory, image.gpu_addr, image.info, copies, map.mapped_span);
  496. }
  497. }
  498. template <class P>
  499. void TextureCache<P>::UnmapMemory(VAddr cpu_addr, size_t size) {
  500. std::vector<ImageId> deleted_images;
  501. ForEachImageInRegion(cpu_addr, size, [&](ImageId id, Image&) { deleted_images.push_back(id); });
  502. for (const ImageId id : deleted_images) {
  503. Image& image = slot_images[id];
  504. if (True(image.flags & ImageFlagBits::Tracked)) {
  505. UntrackImage(image);
  506. }
  507. UnregisterImage(id);
  508. DeleteImage(id);
  509. }
  510. }
  511. template <class P>
  512. void TextureCache<P>::BlitImage(const Tegra::Engines::Fermi2D::Surface& dst,
  513. const Tegra::Engines::Fermi2D::Surface& src,
  514. const Tegra::Engines::Fermi2D::Config& copy,
  515. std::optional<Region2D> src_override,
  516. std::optional<Region2D> dst_override) {
  517. const BlitImages images = GetBlitImages(dst, src);
  518. const ImageId dst_id = images.dst_id;
  519. const ImageId src_id = images.src_id;
  520. PrepareImage(src_id, false, false);
  521. PrepareImage(dst_id, true, false);
  522. ImageBase& dst_image = slot_images[dst_id];
  523. const ImageBase& src_image = slot_images[src_id];
  524. // TODO: Deduplicate
  525. const std::optional dst_base = dst_image.TryFindBase(dst.Address());
  526. const SubresourceRange dst_range{.base = dst_base.value(), .extent = {1, 1}};
  527. const ImageViewInfo dst_view_info(ImageViewType::e2D, images.dst_format, dst_range);
  528. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  529. const auto [src_samples_x, src_samples_y] = SamplesLog2(src_image.info.num_samples);
  530. // out of bounds texture blit checking
  531. const bool use_override = src_override.has_value();
  532. const s32 src_x0 = copy.src_x0 >> src_samples_x;
  533. s32 src_x1 = use_override ? src_override->end.x : copy.src_x1 >> src_samples_x;
  534. const s32 src_y0 = copy.src_y0 >> src_samples_y;
  535. const s32 src_y1 = copy.src_y1 >> src_samples_y;
  536. const auto src_width = static_cast<s32>(src_image.info.size.width);
  537. const bool width_oob = src_x1 > src_width;
  538. const auto width_diff = width_oob ? src_x1 - src_width : 0;
  539. if (width_oob) {
  540. src_x1 = src_width;
  541. }
  542. const Region2D src_dimensions{
  543. Offset2D{.x = src_x0, .y = src_y0},
  544. Offset2D{.x = src_x1, .y = src_y1},
  545. };
  546. const auto src_region = use_override ? *src_override : src_dimensions;
  547. const std::optional src_base = src_image.TryFindBase(src.Address());
  548. const SubresourceRange src_range{.base = src_base.value(), .extent = {1, 1}};
  549. const ImageViewInfo src_view_info(ImageViewType::e2D, images.src_format, src_range);
  550. const auto [src_framebuffer_id, src_view_id] = RenderTargetFromImage(src_id, src_view_info);
  551. const auto [dst_samples_x, dst_samples_y] = SamplesLog2(dst_image.info.num_samples);
  552. const s32 dst_x0 = copy.dst_x0 >> dst_samples_x;
  553. const s32 dst_x1 = copy.dst_x1 >> dst_samples_x;
  554. const s32 dst_y0 = copy.dst_y0 >> dst_samples_y;
  555. const s32 dst_y1 = copy.dst_y1 >> dst_samples_y;
  556. const Region2D dst_dimensions{
  557. Offset2D{.x = dst_x0, .y = dst_y0},
  558. Offset2D{.x = dst_x1 - width_diff, .y = dst_y1},
  559. };
  560. const auto dst_region = use_override ? *dst_override : dst_dimensions;
  561. // Always call this after src_framebuffer_id was queried, as the address might be invalidated.
  562. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  563. if constexpr (FRAMEBUFFER_BLITS) {
  564. // OpenGL blits from framebuffers, not images
  565. Framebuffer* const src_framebuffer = &slot_framebuffers[src_framebuffer_id];
  566. runtime.BlitFramebuffer(dst_framebuffer, src_framebuffer, dst_region, src_region,
  567. copy.filter, copy.operation);
  568. } else {
  569. // Vulkan can blit images, but it lacks format reinterpretations
  570. // Provide a framebuffer in case it's necessary
  571. ImageView& dst_view = slot_image_views[dst_view_id];
  572. ImageView& src_view = slot_image_views[src_view_id];
  573. runtime.BlitImage(dst_framebuffer, dst_view, src_view, dst_region, src_region, copy.filter,
  574. copy.operation);
  575. }
  576. if (width_oob) {
  577. // Continue copy of the oob region of the texture on the next row
  578. auto oob_src = src;
  579. oob_src.height++;
  580. const Region2D src_region_override{
  581. Offset2D{.x = 0, .y = src_y0 + 1},
  582. Offset2D{.x = width_diff, .y = src_y1 + 1},
  583. };
  584. const Region2D dst_region_override{
  585. Offset2D{.x = dst_x1 - width_diff, .y = dst_y0},
  586. Offset2D{.x = dst_x1, .y = dst_y1},
  587. };
  588. BlitImage(dst, oob_src, copy, src_region_override, dst_region_override);
  589. }
  590. }
  591. template <class P>
  592. void TextureCache<P>::InvalidateColorBuffer(size_t index) {
  593. ImageViewId& color_buffer_id = render_targets.color_buffer_ids[index];
  594. color_buffer_id = FindColorBuffer(index, false);
  595. if (!color_buffer_id) {
  596. LOG_ERROR(HW_GPU, "Invalidating invalid color buffer in index={}", index);
  597. return;
  598. }
  599. // When invalidating a color buffer, the old contents are no longer relevant
  600. ImageView& color_buffer = slot_image_views[color_buffer_id];
  601. Image& image = slot_images[color_buffer.image_id];
  602. image.flags &= ~ImageFlagBits::CpuModified;
  603. image.flags &= ~ImageFlagBits::GpuModified;
  604. runtime.InvalidateColorBuffer(color_buffer, index);
  605. }
  606. template <class P>
  607. void TextureCache<P>::InvalidateDepthBuffer() {
  608. ImageViewId& depth_buffer_id = render_targets.depth_buffer_id;
  609. depth_buffer_id = FindDepthBuffer(false);
  610. if (!depth_buffer_id) {
  611. LOG_ERROR(HW_GPU, "Invalidating invalid depth buffer");
  612. return;
  613. }
  614. // When invalidating the depth buffer, the old contents are no longer relevant
  615. ImageBase& image = slot_images[slot_image_views[depth_buffer_id].image_id];
  616. image.flags &= ~ImageFlagBits::CpuModified;
  617. image.flags &= ~ImageFlagBits::GpuModified;
  618. ImageView& depth_buffer = slot_image_views[depth_buffer_id];
  619. runtime.InvalidateDepthBuffer(depth_buffer);
  620. }
  621. template <class P>
  622. typename P::ImageView* TextureCache<P>::TryFindFramebufferImageView(VAddr cpu_addr) {
  623. // TODO: Properly implement this
  624. const auto it = page_table.find(cpu_addr >> PAGE_BITS);
  625. if (it == page_table.end()) {
  626. return nullptr;
  627. }
  628. const auto& image_ids = it->second;
  629. for (const ImageId image_id : image_ids) {
  630. const ImageBase& image = slot_images[image_id];
  631. if (image.cpu_addr != cpu_addr) {
  632. continue;
  633. }
  634. if (image.image_view_ids.empty()) {
  635. continue;
  636. }
  637. return &slot_image_views[image.image_view_ids.at(0)];
  638. }
  639. return nullptr;
  640. }
  641. template <class P>
  642. bool TextureCache<P>::HasUncommittedFlushes() const noexcept {
  643. return !uncommitted_downloads.empty();
  644. }
  645. template <class P>
  646. bool TextureCache<P>::ShouldWaitAsyncFlushes() const noexcept {
  647. return !committed_downloads.empty() && !committed_downloads.front().empty();
  648. }
  649. template <class P>
  650. void TextureCache<P>::CommitAsyncFlushes() {
  651. // This is intentionally passing the value by copy
  652. committed_downloads.push(uncommitted_downloads);
  653. uncommitted_downloads.clear();
  654. }
  655. template <class P>
  656. void TextureCache<P>::PopAsyncFlushes() {
  657. if (committed_downloads.empty()) {
  658. return;
  659. }
  660. const std::span<const ImageId> download_ids = committed_downloads.front();
  661. if (download_ids.empty()) {
  662. committed_downloads.pop();
  663. return;
  664. }
  665. size_t total_size_bytes = 0;
  666. for (const ImageId image_id : download_ids) {
  667. total_size_bytes += slot_images[image_id].unswizzled_size_bytes;
  668. }
  669. auto download_map = runtime.DownloadStagingBuffer(total_size_bytes);
  670. const size_t original_offset = download_map.offset;
  671. for (const ImageId image_id : download_ids) {
  672. Image& image = slot_images[image_id];
  673. const auto copies = FullDownloadCopies(image.info);
  674. image.DownloadMemory(download_map, copies);
  675. download_map.offset += image.unswizzled_size_bytes;
  676. }
  677. // Wait for downloads to finish
  678. runtime.Finish();
  679. download_map.offset = original_offset;
  680. std::span<u8> download_span = download_map.mapped_span;
  681. for (const ImageId image_id : download_ids) {
  682. const ImageBase& image = slot_images[image_id];
  683. const auto copies = FullDownloadCopies(image.info);
  684. SwizzleImage(gpu_memory, image.gpu_addr, image.info, copies, download_span);
  685. download_map.offset += image.unswizzled_size_bytes;
  686. download_span = download_span.subspan(image.unswizzled_size_bytes);
  687. }
  688. committed_downloads.pop();
  689. }
  690. template <class P>
  691. bool TextureCache<P>::IsRegionGpuModified(VAddr addr, size_t size) {
  692. bool is_modified = false;
  693. ForEachImageInRegion(addr, size, [&is_modified](ImageId, ImageBase& image) {
  694. if (False(image.flags & ImageFlagBits::GpuModified)) {
  695. return false;
  696. }
  697. is_modified = true;
  698. return true;
  699. });
  700. return is_modified;
  701. }
  702. template <class P>
  703. void TextureCache<P>::RefreshContents(Image& image) {
  704. if (False(image.flags & ImageFlagBits::CpuModified)) {
  705. // Only upload modified images
  706. return;
  707. }
  708. image.flags &= ~ImageFlagBits::CpuModified;
  709. TrackImage(image);
  710. if (image.info.num_samples > 1) {
  711. LOG_WARNING(HW_GPU, "MSAA image uploads are not implemented");
  712. return;
  713. }
  714. auto staging = runtime.UploadStagingBuffer(MapSizeBytes(image));
  715. UploadImageContents(image, staging);
  716. runtime.InsertUploadMemoryBarrier();
  717. }
  718. template <class P>
  719. template <typename StagingBuffer>
  720. void TextureCache<P>::UploadImageContents(Image& image, StagingBuffer& staging) {
  721. const std::span<u8> mapped_span = staging.mapped_span;
  722. const GPUVAddr gpu_addr = image.gpu_addr;
  723. if (True(image.flags & ImageFlagBits::AcceleratedUpload)) {
  724. gpu_memory.ReadBlockUnsafe(gpu_addr, mapped_span.data(), mapped_span.size_bytes());
  725. const auto uploads = FullUploadSwizzles(image.info);
  726. runtime.AccelerateImageUpload(image, staging, uploads);
  727. } else if (True(image.flags & ImageFlagBits::Converted)) {
  728. std::vector<u8> unswizzled_data(image.unswizzled_size_bytes);
  729. auto copies = UnswizzleImage(gpu_memory, gpu_addr, image.info, unswizzled_data);
  730. ConvertImage(unswizzled_data, image.info, mapped_span, copies);
  731. image.UploadMemory(staging, copies);
  732. } else if (image.info.type == ImageType::Buffer) {
  733. const std::array copies{UploadBufferCopy(gpu_memory, gpu_addr, image, mapped_span)};
  734. image.UploadMemory(staging, copies);
  735. } else {
  736. const auto copies = UnswizzleImage(gpu_memory, gpu_addr, image.info, mapped_span);
  737. image.UploadMemory(staging, copies);
  738. }
  739. }
  740. template <class P>
  741. ImageViewId TextureCache<P>::FindImageView(const TICEntry& config) {
  742. if (!IsValidAddress(gpu_memory, config)) {
  743. return NULL_IMAGE_VIEW_ID;
  744. }
  745. const auto [pair, is_new] = image_views.try_emplace(config);
  746. ImageViewId& image_view_id = pair->second;
  747. if (is_new) {
  748. image_view_id = CreateImageView(config);
  749. }
  750. return image_view_id;
  751. }
  752. template <class P>
  753. ImageViewId TextureCache<P>::CreateImageView(const TICEntry& config) {
  754. const ImageInfo info(config);
  755. const GPUVAddr image_gpu_addr = config.Address() - config.BaseLayer() * info.layer_stride;
  756. const ImageId image_id = FindOrInsertImage(info, image_gpu_addr);
  757. if (!image_id) {
  758. return NULL_IMAGE_VIEW_ID;
  759. }
  760. ImageBase& image = slot_images[image_id];
  761. const SubresourceBase base = image.TryFindBase(config.Address()).value();
  762. ASSERT(base.level == 0);
  763. const ImageViewInfo view_info(config, base.layer);
  764. const ImageViewId image_view_id = FindOrEmplaceImageView(image_id, view_info);
  765. ImageViewBase& image_view = slot_image_views[image_view_id];
  766. image_view.flags |= ImageViewFlagBits::Strong;
  767. image.flags |= ImageFlagBits::Strong;
  768. return image_view_id;
  769. }
  770. template <class P>
  771. ImageId TextureCache<P>::FindOrInsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  772. RelaxedOptions options) {
  773. if (const ImageId image_id = FindImage(info, gpu_addr, options); image_id) {
  774. return image_id;
  775. }
  776. return InsertImage(info, gpu_addr, options);
  777. }
  778. template <class P>
  779. ImageId TextureCache<P>::FindImage(const ImageInfo& info, GPUVAddr gpu_addr,
  780. RelaxedOptions options) {
  781. const std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr);
  782. if (!cpu_addr) {
  783. return ImageId{};
  784. }
  785. const bool broken_views = runtime.HasBrokenTextureViewFormats();
  786. const bool native_bgr = runtime.HasNativeBgr();
  787. ImageId image_id;
  788. const auto lambda = [&](ImageId existing_image_id, ImageBase& existing_image) {
  789. if (info.type == ImageType::Linear || existing_image.info.type == ImageType::Linear) {
  790. const bool strict_size = False(options & RelaxedOptions::Size) &&
  791. True(existing_image.flags & ImageFlagBits::Strong);
  792. const ImageInfo& existing = existing_image.info;
  793. if (existing_image.gpu_addr == gpu_addr && existing.type == info.type &&
  794. existing.pitch == info.pitch &&
  795. IsPitchLinearSameSize(existing, info, strict_size) &&
  796. IsViewCompatible(existing.format, info.format, broken_views, native_bgr)) {
  797. image_id = existing_image_id;
  798. return true;
  799. }
  800. } else if (IsSubresource(info, existing_image, gpu_addr, options, broken_views,
  801. native_bgr)) {
  802. image_id = existing_image_id;
  803. return true;
  804. }
  805. return false;
  806. };
  807. ForEachImageInRegion(*cpu_addr, CalculateGuestSizeInBytes(info), lambda);
  808. return image_id;
  809. }
  810. template <class P>
  811. ImageId TextureCache<P>::InsertImage(const ImageInfo& info, GPUVAddr gpu_addr,
  812. RelaxedOptions options) {
  813. const std::optional<VAddr> cpu_addr = gpu_memory.GpuToCpuAddress(gpu_addr);
  814. ASSERT_MSG(cpu_addr, "Tried to insert an image to an invalid gpu_addr=0x{:x}", gpu_addr);
  815. const ImageId image_id = JoinImages(info, gpu_addr, *cpu_addr);
  816. const Image& image = slot_images[image_id];
  817. // Using "image.gpu_addr" instead of "gpu_addr" is important because it might be different
  818. const auto [it, is_new] = image_allocs_table.try_emplace(image.gpu_addr);
  819. if (is_new) {
  820. it->second = slot_image_allocs.insert();
  821. }
  822. slot_image_allocs[it->second].images.push_back(image_id);
  823. return image_id;
  824. }
  825. template <class P>
  826. ImageId TextureCache<P>::JoinImages(const ImageInfo& info, GPUVAddr gpu_addr, VAddr cpu_addr) {
  827. ImageInfo new_info = info;
  828. const size_t size_bytes = CalculateGuestSizeInBytes(new_info);
  829. const bool broken_views = runtime.HasBrokenTextureViewFormats();
  830. const bool native_bgr = runtime.HasNativeBgr();
  831. std::vector<ImageId> overlap_ids;
  832. std::vector<ImageId> left_aliased_ids;
  833. std::vector<ImageId> right_aliased_ids;
  834. ForEachImageInRegion(cpu_addr, size_bytes, [&](ImageId overlap_id, ImageBase& overlap) {
  835. if (info.type != overlap.info.type) {
  836. return;
  837. }
  838. if (info.type == ImageType::Linear) {
  839. if (info.pitch == overlap.info.pitch && gpu_addr == overlap.gpu_addr) {
  840. // Alias linear images with the same pitch
  841. left_aliased_ids.push_back(overlap_id);
  842. }
  843. return;
  844. }
  845. static constexpr bool strict_size = true;
  846. const std::optional<OverlapResult> solution = ResolveOverlap(
  847. new_info, gpu_addr, cpu_addr, overlap, strict_size, broken_views, native_bgr);
  848. if (solution) {
  849. gpu_addr = solution->gpu_addr;
  850. cpu_addr = solution->cpu_addr;
  851. new_info.resources = solution->resources;
  852. overlap_ids.push_back(overlap_id);
  853. return;
  854. }
  855. static constexpr auto options = RelaxedOptions::Size | RelaxedOptions::Format;
  856. const ImageBase new_image_base(new_info, gpu_addr, cpu_addr);
  857. if (IsSubresource(new_info, overlap, gpu_addr, options, broken_views, native_bgr)) {
  858. left_aliased_ids.push_back(overlap_id);
  859. } else if (IsSubresource(overlap.info, new_image_base, overlap.gpu_addr, options,
  860. broken_views, native_bgr)) {
  861. right_aliased_ids.push_back(overlap_id);
  862. }
  863. });
  864. const ImageId new_image_id = slot_images.insert(runtime, new_info, gpu_addr, cpu_addr);
  865. Image& new_image = slot_images[new_image_id];
  866. // TODO: Only upload what we need
  867. RefreshContents(new_image);
  868. for (const ImageId overlap_id : overlap_ids) {
  869. Image& overlap = slot_images[overlap_id];
  870. if (overlap.info.num_samples != new_image.info.num_samples) {
  871. LOG_WARNING(HW_GPU, "Copying between images with different samples is not implemented");
  872. } else {
  873. const SubresourceBase base = new_image.TryFindBase(overlap.gpu_addr).value();
  874. const auto copies = MakeShrinkImageCopies(new_info, overlap.info, base);
  875. runtime.CopyImage(new_image, overlap, copies);
  876. }
  877. if (True(overlap.flags & ImageFlagBits::Tracked)) {
  878. UntrackImage(overlap);
  879. }
  880. UnregisterImage(overlap_id);
  881. DeleteImage(overlap_id);
  882. }
  883. ImageBase& new_image_base = new_image;
  884. for (const ImageId aliased_id : right_aliased_ids) {
  885. ImageBase& aliased = slot_images[aliased_id];
  886. AddImageAlias(new_image_base, aliased, new_image_id, aliased_id);
  887. }
  888. for (const ImageId aliased_id : left_aliased_ids) {
  889. ImageBase& aliased = slot_images[aliased_id];
  890. AddImageAlias(aliased, new_image_base, aliased_id, new_image_id);
  891. }
  892. RegisterImage(new_image_id);
  893. return new_image_id;
  894. }
  895. template <class P>
  896. typename TextureCache<P>::BlitImages TextureCache<P>::GetBlitImages(
  897. const Tegra::Engines::Fermi2D::Surface& dst, const Tegra::Engines::Fermi2D::Surface& src) {
  898. static constexpr auto FIND_OPTIONS = RelaxedOptions::Format | RelaxedOptions::Samples;
  899. const GPUVAddr dst_addr = dst.Address();
  900. const GPUVAddr src_addr = src.Address();
  901. ImageInfo dst_info(dst);
  902. ImageInfo src_info(src);
  903. ImageId dst_id;
  904. ImageId src_id;
  905. do {
  906. has_deleted_images = false;
  907. dst_id = FindImage(dst_info, dst_addr, FIND_OPTIONS);
  908. src_id = FindImage(src_info, src_addr, FIND_OPTIONS);
  909. const ImageBase* const dst_image = dst_id ? &slot_images[dst_id] : nullptr;
  910. const ImageBase* const src_image = src_id ? &slot_images[src_id] : nullptr;
  911. DeduceBlitImages(dst_info, src_info, dst_image, src_image);
  912. if (GetFormatType(dst_info.format) != GetFormatType(src_info.format)) {
  913. continue;
  914. }
  915. if (!dst_id) {
  916. dst_id = InsertImage(dst_info, dst_addr, RelaxedOptions{});
  917. }
  918. if (!src_id) {
  919. src_id = InsertImage(src_info, src_addr, RelaxedOptions{});
  920. }
  921. } while (has_deleted_images);
  922. return BlitImages{
  923. .dst_id = dst_id,
  924. .src_id = src_id,
  925. .dst_format = dst_info.format,
  926. .src_format = src_info.format,
  927. };
  928. }
  929. template <class P>
  930. SamplerId TextureCache<P>::FindSampler(const TSCEntry& config) {
  931. if (std::ranges::all_of(config.raw, [](u64 value) { return value == 0; })) {
  932. return NULL_SAMPLER_ID;
  933. }
  934. const auto [pair, is_new] = samplers.try_emplace(config);
  935. if (is_new) {
  936. pair->second = slot_samplers.insert(runtime, config);
  937. }
  938. return pair->second;
  939. }
  940. template <class P>
  941. ImageViewId TextureCache<P>::FindColorBuffer(size_t index, bool is_clear) {
  942. const auto& regs = maxwell3d.regs;
  943. if (index >= regs.rt_control.count) {
  944. return ImageViewId{};
  945. }
  946. const auto& rt = regs.rt[index];
  947. const GPUVAddr gpu_addr = rt.Address();
  948. if (gpu_addr == 0) {
  949. return ImageViewId{};
  950. }
  951. if (rt.format == Tegra::RenderTargetFormat::NONE) {
  952. return ImageViewId{};
  953. }
  954. const ImageInfo info(regs, index);
  955. return FindRenderTargetView(info, gpu_addr, is_clear);
  956. }
  957. template <class P>
  958. ImageViewId TextureCache<P>::FindDepthBuffer(bool is_clear) {
  959. const auto& regs = maxwell3d.regs;
  960. if (!regs.zeta_enable) {
  961. return ImageViewId{};
  962. }
  963. const GPUVAddr gpu_addr = regs.zeta.Address();
  964. if (gpu_addr == 0) {
  965. return ImageViewId{};
  966. }
  967. const ImageInfo info(regs);
  968. return FindRenderTargetView(info, gpu_addr, is_clear);
  969. }
  970. template <class P>
  971. ImageViewId TextureCache<P>::FindRenderTargetView(const ImageInfo& info, GPUVAddr gpu_addr,
  972. bool is_clear) {
  973. const auto options = is_clear ? RelaxedOptions::Samples : RelaxedOptions{};
  974. const ImageId image_id = FindOrInsertImage(info, gpu_addr, options);
  975. if (!image_id) {
  976. return NULL_IMAGE_VIEW_ID;
  977. }
  978. Image& image = slot_images[image_id];
  979. const ImageViewType view_type = RenderTargetImageViewType(info);
  980. SubresourceBase base;
  981. if (image.info.type == ImageType::Linear) {
  982. base = SubresourceBase{.level = 0, .layer = 0};
  983. } else {
  984. base = image.TryFindBase(gpu_addr).value();
  985. }
  986. const s32 layers = image.info.type == ImageType::e3D ? info.size.depth : info.resources.layers;
  987. const SubresourceRange range{
  988. .base = base,
  989. .extent = {.levels = 1, .layers = layers},
  990. };
  991. return FindOrEmplaceImageView(image_id, ImageViewInfo(view_type, info.format, range));
  992. }
  993. template <class P>
  994. template <typename Func>
  995. void TextureCache<P>::ForEachImageInRegion(VAddr cpu_addr, size_t size, Func&& func) {
  996. using FuncReturn = typename std::invoke_result<Func, ImageId, Image&>::type;
  997. static constexpr bool BOOL_BREAK = std::is_same_v<FuncReturn, bool>;
  998. boost::container::small_vector<ImageId, 32> images;
  999. ForEachPage(cpu_addr, size, [this, &images, cpu_addr, size, func](u64 page) {
  1000. const auto it = page_table.find(page);
  1001. if (it == page_table.end()) {
  1002. if constexpr (BOOL_BREAK) {
  1003. return false;
  1004. } else {
  1005. return;
  1006. }
  1007. }
  1008. for (const ImageId image_id : it->second) {
  1009. Image& image = slot_images[image_id];
  1010. if (True(image.flags & ImageFlagBits::Picked)) {
  1011. continue;
  1012. }
  1013. if (!image.Overlaps(cpu_addr, size)) {
  1014. continue;
  1015. }
  1016. image.flags |= ImageFlagBits::Picked;
  1017. images.push_back(image_id);
  1018. if constexpr (BOOL_BREAK) {
  1019. if (func(image_id, image)) {
  1020. return true;
  1021. }
  1022. } else {
  1023. func(image_id, image);
  1024. }
  1025. }
  1026. if constexpr (BOOL_BREAK) {
  1027. return false;
  1028. }
  1029. });
  1030. for (const ImageId image_id : images) {
  1031. slot_images[image_id].flags &= ~ImageFlagBits::Picked;
  1032. }
  1033. }
  1034. template <class P>
  1035. ImageViewId TextureCache<P>::FindOrEmplaceImageView(ImageId image_id, const ImageViewInfo& info) {
  1036. Image& image = slot_images[image_id];
  1037. if (const ImageViewId image_view_id = image.FindView(info); image_view_id) {
  1038. return image_view_id;
  1039. }
  1040. const ImageViewId image_view_id = slot_image_views.insert(runtime, info, image_id, image);
  1041. image.InsertView(info, image_view_id);
  1042. return image_view_id;
  1043. }
  1044. template <class P>
  1045. void TextureCache<P>::RegisterImage(ImageId image_id) {
  1046. ImageBase& image = slot_images[image_id];
  1047. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered),
  1048. "Trying to register an already registered image");
  1049. image.flags |= ImageFlagBits::Registered;
  1050. ForEachPage(image.cpu_addr, image.guest_size_bytes,
  1051. [this, image_id](u64 page) { page_table[page].push_back(image_id); });
  1052. }
  1053. template <class P>
  1054. void TextureCache<P>::UnregisterImage(ImageId image_id) {
  1055. Image& image = slot_images[image_id];
  1056. ASSERT_MSG(True(image.flags & ImageFlagBits::Registered),
  1057. "Trying to unregister an already registered image");
  1058. image.flags &= ~ImageFlagBits::Registered;
  1059. ForEachPage(image.cpu_addr, image.guest_size_bytes, [this, image_id](u64 page) {
  1060. const auto page_it = page_table.find(page);
  1061. if (page_it == page_table.end()) {
  1062. UNREACHABLE_MSG("Unregistering unregistered page=0x{:x}", page << PAGE_BITS);
  1063. return;
  1064. }
  1065. std::vector<ImageId>& image_ids = page_it->second;
  1066. const auto vector_it = std::ranges::find(image_ids, image_id);
  1067. if (vector_it == image_ids.end()) {
  1068. UNREACHABLE_MSG("Unregistering unregistered image in page=0x{:x}", page << PAGE_BITS);
  1069. return;
  1070. }
  1071. image_ids.erase(vector_it);
  1072. });
  1073. }
  1074. template <class P>
  1075. void TextureCache<P>::TrackImage(ImageBase& image) {
  1076. ASSERT(False(image.flags & ImageFlagBits::Tracked));
  1077. image.flags |= ImageFlagBits::Tracked;
  1078. rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, 1);
  1079. }
  1080. template <class P>
  1081. void TextureCache<P>::UntrackImage(ImageBase& image) {
  1082. ASSERT(True(image.flags & ImageFlagBits::Tracked));
  1083. image.flags &= ~ImageFlagBits::Tracked;
  1084. rasterizer.UpdatePagesCachedCount(image.cpu_addr, image.guest_size_bytes, -1);
  1085. }
  1086. template <class P>
  1087. void TextureCache<P>::DeleteImage(ImageId image_id) {
  1088. ImageBase& image = slot_images[image_id];
  1089. const GPUVAddr gpu_addr = image.gpu_addr;
  1090. const auto alloc_it = image_allocs_table.find(gpu_addr);
  1091. if (alloc_it == image_allocs_table.end()) {
  1092. UNREACHABLE_MSG("Trying to delete an image alloc that does not exist in address 0x{:x}",
  1093. gpu_addr);
  1094. return;
  1095. }
  1096. const ImageAllocId alloc_id = alloc_it->second;
  1097. std::vector<ImageId>& alloc_images = slot_image_allocs[alloc_id].images;
  1098. const auto alloc_image_it = std::ranges::find(alloc_images, image_id);
  1099. if (alloc_image_it == alloc_images.end()) {
  1100. UNREACHABLE_MSG("Trying to delete an image that does not exist");
  1101. return;
  1102. }
  1103. ASSERT_MSG(False(image.flags & ImageFlagBits::Tracked), "Image was not untracked");
  1104. ASSERT_MSG(False(image.flags & ImageFlagBits::Registered), "Image was not unregistered");
  1105. // Mark render targets as dirty
  1106. auto& dirty = maxwell3d.dirty.flags;
  1107. dirty[Dirty::RenderTargets] = true;
  1108. dirty[Dirty::ZetaBuffer] = true;
  1109. for (size_t rt = 0; rt < NUM_RT; ++rt) {
  1110. dirty[Dirty::ColorBuffer0 + rt] = true;
  1111. }
  1112. const std::span<const ImageViewId> image_view_ids = image.image_view_ids;
  1113. for (const ImageViewId image_view_id : image_view_ids) {
  1114. std::ranges::replace(render_targets.color_buffer_ids, image_view_id, ImageViewId{});
  1115. if (render_targets.depth_buffer_id == image_view_id) {
  1116. render_targets.depth_buffer_id = ImageViewId{};
  1117. }
  1118. }
  1119. RemoveImageViewReferences(image_view_ids);
  1120. RemoveFramebuffers(image_view_ids);
  1121. for (const AliasedImage& alias : image.aliased_images) {
  1122. ImageBase& other_image = slot_images[alias.id];
  1123. [[maybe_unused]] const size_t num_removed_aliases =
  1124. std::erase_if(other_image.aliased_images, [image_id](const AliasedImage& other_alias) {
  1125. return other_alias.id == image_id;
  1126. });
  1127. ASSERT_MSG(num_removed_aliases == 1, "Invalid number of removed aliases: {}",
  1128. num_removed_aliases);
  1129. }
  1130. for (const ImageViewId image_view_id : image_view_ids) {
  1131. sentenced_image_view.Push(std::move(slot_image_views[image_view_id]));
  1132. slot_image_views.erase(image_view_id);
  1133. }
  1134. sentenced_images.Push(std::move(slot_images[image_id]));
  1135. slot_images.erase(image_id);
  1136. alloc_images.erase(alloc_image_it);
  1137. if (alloc_images.empty()) {
  1138. image_allocs_table.erase(alloc_it);
  1139. }
  1140. if constexpr (ENABLE_VALIDATION) {
  1141. std::ranges::fill(graphics_image_view_ids, CORRUPT_ID);
  1142. std::ranges::fill(compute_image_view_ids, CORRUPT_ID);
  1143. }
  1144. graphics_image_table.Invalidate();
  1145. compute_image_table.Invalidate();
  1146. has_deleted_images = true;
  1147. }
  1148. template <class P>
  1149. void TextureCache<P>::RemoveImageViewReferences(std::span<const ImageViewId> removed_views) {
  1150. auto it = image_views.begin();
  1151. while (it != image_views.end()) {
  1152. const auto found = std::ranges::find(removed_views, it->second);
  1153. if (found != removed_views.end()) {
  1154. it = image_views.erase(it);
  1155. } else {
  1156. ++it;
  1157. }
  1158. }
  1159. }
  1160. template <class P>
  1161. void TextureCache<P>::RemoveFramebuffers(std::span<const ImageViewId> removed_views) {
  1162. auto it = framebuffers.begin();
  1163. while (it != framebuffers.end()) {
  1164. if (it->first.Contains(removed_views)) {
  1165. it = framebuffers.erase(it);
  1166. } else {
  1167. ++it;
  1168. }
  1169. }
  1170. }
  1171. template <class P>
  1172. void TextureCache<P>::MarkModification(ImageBase& image) noexcept {
  1173. image.flags |= ImageFlagBits::GpuModified;
  1174. image.modification_tick = ++modification_tick;
  1175. }
  1176. template <class P>
  1177. void TextureCache<P>::SynchronizeAliases(ImageId image_id) {
  1178. boost::container::small_vector<const AliasedImage*, 1> aliased_images;
  1179. ImageBase& image = slot_images[image_id];
  1180. u64 most_recent_tick = image.modification_tick;
  1181. for (const AliasedImage& aliased : image.aliased_images) {
  1182. ImageBase& aliased_image = slot_images[aliased.id];
  1183. if (image.modification_tick < aliased_image.modification_tick) {
  1184. most_recent_tick = std::max(most_recent_tick, aliased_image.modification_tick);
  1185. aliased_images.push_back(&aliased);
  1186. }
  1187. }
  1188. if (aliased_images.empty()) {
  1189. return;
  1190. }
  1191. image.modification_tick = most_recent_tick;
  1192. std::ranges::sort(aliased_images, [this](const AliasedImage* lhs, const AliasedImage* rhs) {
  1193. const ImageBase& lhs_image = slot_images[lhs->id];
  1194. const ImageBase& rhs_image = slot_images[rhs->id];
  1195. return lhs_image.modification_tick < rhs_image.modification_tick;
  1196. });
  1197. for (const AliasedImage* const aliased : aliased_images) {
  1198. CopyImage(image_id, aliased->id, aliased->copies);
  1199. }
  1200. }
  1201. template <class P>
  1202. void TextureCache<P>::PrepareImage(ImageId image_id, bool is_modification, bool invalidate) {
  1203. Image& image = slot_images[image_id];
  1204. if (invalidate) {
  1205. image.flags &= ~(ImageFlagBits::CpuModified | ImageFlagBits::GpuModified);
  1206. if (False(image.flags & ImageFlagBits::Tracked)) {
  1207. TrackImage(image);
  1208. }
  1209. } else {
  1210. RefreshContents(image);
  1211. SynchronizeAliases(image_id);
  1212. }
  1213. if (is_modification) {
  1214. MarkModification(image);
  1215. }
  1216. image.frame_tick = frame_tick;
  1217. }
  1218. template <class P>
  1219. void TextureCache<P>::PrepareImageView(ImageViewId image_view_id, bool is_modification,
  1220. bool invalidate) {
  1221. if (!image_view_id) {
  1222. return;
  1223. }
  1224. const ImageViewBase& image_view = slot_image_views[image_view_id];
  1225. PrepareImage(image_view.image_id, is_modification, invalidate);
  1226. }
  1227. template <class P>
  1228. void TextureCache<P>::CopyImage(ImageId dst_id, ImageId src_id, std::span<const ImageCopy> copies) {
  1229. Image& dst = slot_images[dst_id];
  1230. Image& src = slot_images[src_id];
  1231. const auto dst_format_type = GetFormatType(dst.info.format);
  1232. const auto src_format_type = GetFormatType(src.info.format);
  1233. if (src_format_type == dst_format_type) {
  1234. if constexpr (HAS_EMULATED_COPIES) {
  1235. if (!runtime.CanImageBeCopied(dst, src)) {
  1236. return runtime.EmulateCopyImage(dst, src, copies);
  1237. }
  1238. }
  1239. return runtime.CopyImage(dst, src, copies);
  1240. }
  1241. UNIMPLEMENTED_IF(dst.info.type != ImageType::e2D);
  1242. UNIMPLEMENTED_IF(src.info.type != ImageType::e2D);
  1243. for (const ImageCopy& copy : copies) {
  1244. UNIMPLEMENTED_IF(copy.dst_subresource.num_layers != 1);
  1245. UNIMPLEMENTED_IF(copy.src_subresource.num_layers != 1);
  1246. UNIMPLEMENTED_IF(copy.src_offset != Offset3D{});
  1247. UNIMPLEMENTED_IF(copy.dst_offset != Offset3D{});
  1248. const SubresourceBase dst_base{
  1249. .level = copy.dst_subresource.base_level,
  1250. .layer = copy.dst_subresource.base_layer,
  1251. };
  1252. const SubresourceBase src_base{
  1253. .level = copy.src_subresource.base_level,
  1254. .layer = copy.src_subresource.base_layer,
  1255. };
  1256. const SubresourceExtent dst_extent{.levels = 1, .layers = 1};
  1257. const SubresourceExtent src_extent{.levels = 1, .layers = 1};
  1258. const SubresourceRange dst_range{.base = dst_base, .extent = dst_extent};
  1259. const SubresourceRange src_range{.base = src_base, .extent = src_extent};
  1260. const ImageViewInfo dst_view_info(ImageViewType::e2D, dst.info.format, dst_range);
  1261. const ImageViewInfo src_view_info(ImageViewType::e2D, src.info.format, src_range);
  1262. const auto [dst_framebuffer_id, dst_view_id] = RenderTargetFromImage(dst_id, dst_view_info);
  1263. Framebuffer* const dst_framebuffer = &slot_framebuffers[dst_framebuffer_id];
  1264. const ImageViewId src_view_id = FindOrEmplaceImageView(src_id, src_view_info);
  1265. ImageView& dst_view = slot_image_views[dst_view_id];
  1266. ImageView& src_view = slot_image_views[src_view_id];
  1267. [[maybe_unused]] const Extent3D expected_size{
  1268. .width = std::min(dst_view.size.width, src_view.size.width),
  1269. .height = std::min(dst_view.size.height, src_view.size.height),
  1270. .depth = std::min(dst_view.size.depth, src_view.size.depth),
  1271. };
  1272. UNIMPLEMENTED_IF(copy.extent != expected_size);
  1273. runtime.ConvertImage(dst_framebuffer, dst_view, src_view);
  1274. }
  1275. }
  1276. template <class P>
  1277. void TextureCache<P>::BindRenderTarget(ImageViewId* old_id, ImageViewId new_id) {
  1278. if (*old_id == new_id) {
  1279. return;
  1280. }
  1281. if (*old_id) {
  1282. const ImageViewBase& old_view = slot_image_views[*old_id];
  1283. if (True(old_view.flags & ImageViewFlagBits::PreemtiveDownload)) {
  1284. uncommitted_downloads.push_back(old_view.image_id);
  1285. }
  1286. }
  1287. *old_id = new_id;
  1288. }
  1289. template <class P>
  1290. std::pair<FramebufferId, ImageViewId> TextureCache<P>::RenderTargetFromImage(
  1291. ImageId image_id, const ImageViewInfo& view_info) {
  1292. const ImageViewId view_id = FindOrEmplaceImageView(image_id, view_info);
  1293. const ImageBase& image = slot_images[image_id];
  1294. const bool is_color = GetFormatType(image.info.format) == SurfaceType::ColorTexture;
  1295. const ImageViewId color_view_id = is_color ? view_id : ImageViewId{};
  1296. const ImageViewId depth_view_id = is_color ? ImageViewId{} : view_id;
  1297. const Extent3D extent = MipSize(image.info.size, view_info.range.base.level);
  1298. const u32 num_samples = image.info.num_samples;
  1299. const auto [samples_x, samples_y] = SamplesLog2(num_samples);
  1300. const FramebufferId framebuffer_id = GetFramebufferId(RenderTargets{
  1301. .color_buffer_ids = {color_view_id},
  1302. .depth_buffer_id = depth_view_id,
  1303. .size = {extent.width >> samples_x, extent.height >> samples_y},
  1304. });
  1305. return {framebuffer_id, view_id};
  1306. }
  1307. template <class P>
  1308. bool TextureCache<P>::IsFullClear(ImageViewId id) {
  1309. if (!id) {
  1310. return true;
  1311. }
  1312. const ImageViewBase& image_view = slot_image_views[id];
  1313. const ImageBase& image = slot_images[image_view.image_id];
  1314. const Extent3D size = image_view.size;
  1315. const auto& regs = maxwell3d.regs;
  1316. const auto& scissor = regs.scissor_test[0];
  1317. if (image.info.resources.levels > 1 || image.info.resources.layers > 1) {
  1318. // Images with multiple resources can't be cleared in a single call
  1319. return false;
  1320. }
  1321. if (regs.clear_flags.scissor == 0) {
  1322. // If scissor testing is disabled, the clear is always full
  1323. return true;
  1324. }
  1325. // Make sure the clear covers all texels in the subresource
  1326. return scissor.min_x == 0 && scissor.min_y == 0 && scissor.max_x >= size.width &&
  1327. scissor.max_y >= size.height;
  1328. }
  1329. } // namespace VideoCommon