game_launcher 1.1.0
Modern Linux game launcher with Steam / Proton / Wine integration
Loading...
Searching...
No Matches
shader_cache_manager.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// ==============================================================================
3// shader_cache_manager.cpp
4// ==============================================================================
5// Shader cache management implementation
6// ==============================================================================
7
9#include "logger.h"
10
11#include <algorithm>
12#include <cstdlib>
13#include <fstream>
14#include <mutex>
15
16// ==============================================================================
17// Helper Functions
18// ==============================================================================
19
20namespace
21{
22
23bool fileExists(const std::filesystem::path& path)
24{
25 std::error_code ec;
26 return std::filesystem::exists(path, ec);
27}
28
29bool isDirectory(const std::filesystem::path& path)
30{
31 std::error_code ec;
32 return std::filesystem::is_directory(path, ec);
33}
34
35bool createDirectories(const std::filesystem::path& path)
36{
37 std::error_code ec;
38 std::filesystem::create_directories(path, ec);
39 return !ec;
40}
41
42std::filesystem::path getHomeDir()
43{
44 const char* home = std::getenv("HOME");
45 if (home)
46 {
47 return std::filesystem::path(home);
48 }
49 return {};
50}
51
52std::filesystem::path getXDGCacheHome()
53{
54 const char* xdgCache = std::getenv("XDG_CACHE_HOME");
55 if (xdgCache)
56 {
57 return std::filesystem::path(xdgCache);
58 }
59 return getHomeDir() / ".cache";
60}
61
62std::filesystem::path getXDGDataHome()
63{
64 const char* xdgData = std::getenv("XDG_DATA_HOME");
65 if (xdgData)
66 {
67 return std::filesystem::path(xdgData);
68 }
69 return getHomeDir() / ".local" / "share";
70}
71
72std::string formatBytes(int64_t bytes)
73{
74 const char* units[] = {"B", "KB", "MB", "GB"};
75 int unitIndex = 0;
76 double size = static_cast<double>(bytes);
77
78 while (size >= 1024 && unitIndex < 3)
79 {
80 size /= 1024;
81 unitIndex++;
82 }
83
84 char buffer[64];
85 snprintf(buffer, sizeof(buffer), "%.1f %s", size, units[unitIndex]);
86 return buffer;
87}
88
89std::chrono::system_clock::time_point getModTime(const std::filesystem::path& path)
90{
91 std::error_code ec;
92 auto ftime = std::filesystem::last_write_time(path, ec);
93 if (ec)
94 {
95 return std::chrono::system_clock::now();
96 }
97 auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
98 ftime - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now());
99 return sctp;
100}
101
102} // namespace
103
104// ==============================================================================
105// ShaderCacheInfo Methods
106// ==============================================================================
107
109{
110 return formatBytes(size);
111}
112
114{
116}
117
118// ==============================================================================
119// GameShaderCache Methods
120// ==============================================================================
121
123{
124 return formatBytes(totalSize);
125}
126
127// ==============================================================================
128// ShaderCacheStats Methods
129// ==============================================================================
130
132{
133 return formatBytes(totalSize);
134}
135
136// ==============================================================================
137// CacheClearResult Methods
138// ==============================================================================
139
141{
142 return formatBytes(bytesCleared);
143}
144
145// ==============================================================================
146// Helper Function
147// ==============================================================================
148
150{
151 switch (type)
152 {
154 return "Mesa (AMD/Intel)";
156 return "NVIDIA";
158 return "DXVK";
160 return "VKD3D-Proton";
162 return "Steam Shader Cache";
164 return "Fossilize";
166 return "Wine State";
168 return "All";
169 default:
170 return "Unknown";
171 }
172}
173
174// ==============================================================================
175// ShaderCacheManager Implementation
176// ==============================================================================
177
179{
180 std::vector<ShaderCacheInfo> caches;
181 std::vector<std::filesystem::path> steamLibraryPaths;
182 std::vector<std::pair<std::filesystem::path, ShaderCacheType>> customLocations;
183 std::filesystem::path backupDir;
184 mutable std::mutex mutex;
185
187 {
188 backupDir = getXDGDataHome() / "gamelauncher" / "shader_cache_backups";
189 createDirectories(backupDir);
190
191 // Default Steam library paths
192 auto home = getHomeDir();
193 if (!home.empty())
194 {
195 steamLibraryPaths.push_back(home / ".steam" / "steam");
196 steamLibraryPaths.push_back(home / ".local" / "share" / "Steam");
197 }
198 }
199};
200
201ShaderCacheManager::ShaderCacheManager() : impl_(std::make_unique<Impl>())
202{
203 scanCaches();
204}
205
207
208// ==============================================================================
209// Cache Discovery
210// ==============================================================================
211
212std::vector<ShaderCacheInfo> ShaderCacheManager::getAllCaches() const
213{
214 std::lock_guard<std::mutex> lock(impl_->mutex);
215 return impl_->caches;
216}
217
218std::vector<ShaderCacheInfo> ShaderCacheManager::getCachesByType(ShaderCacheType type) const
219{
220 std::lock_guard<std::mutex> lock(impl_->mutex);
221 std::vector<ShaderCacheInfo> result;
222
223 for (const auto& cache : impl_->caches)
224 {
225 if (cache.type == type || type == ShaderCacheType::All)
226 {
227 result.push_back(cache);
228 }
229 }
230
231 return result;
232}
233
234std::optional<ShaderCacheInfo>
235ShaderCacheManager::getCacheInfo(const std::filesystem::path& path) const
236{
237 if (!fileExists(path))
238 {
239 return std::nullopt;
240 }
241
242 auto cacheType = identifyCacheType(path);
243 if (!cacheType)
244 {
245 return std::nullopt;
246 }
247
248 ShaderCacheInfo info;
249 info.type = *cacheType;
250 info.name = shaderCacheTypeName(*cacheType);
251 info.path = path;
252 info.size = calculateDirectorySize(path);
253 info.fileCount = countFiles(path);
254 info.lastModified = getModTime(path);
255 info.exists = true;
256
257 return info;
258}
259
261{
262 std::lock_guard<std::mutex> lock(impl_->mutex);
263 impl_->caches.clear();
264
265 int step = 0;
266 int totalSteps = 7;
267
268 if (progressCallback)
269 progressCallback((step * 100) / totalSteps, "Scanning Mesa caches...");
270 scanMesaCaches();
271 step++;
272
273 if (progressCallback)
274 progressCallback((step * 100) / totalSteps, "Scanning NVIDIA caches...");
275 scanNVIDIACaches();
276 step++;
277
278 if (progressCallback)
279 progressCallback((step * 100) / totalSteps, "Scanning DXVK caches...");
280 scanDXVKCaches();
281 step++;
282
283 if (progressCallback)
284 progressCallback((step * 100) / totalSteps, "Scanning VKD3D caches...");
285 scanVKD3DCaches();
286 step++;
287
288 if (progressCallback)
289 progressCallback((step * 100) / totalSteps, "Scanning Steam shader caches...");
290 scanSteamCaches();
291 step++;
292
293 if (progressCallback)
294 progressCallback((step * 100) / totalSteps, "Scanning Fossilize caches...");
295 scanFossilizeCaches();
296 step++;
297
298 if (progressCallback)
299 progressCallback((step * 100) / totalSteps, "Scanning Wine state caches...");
300 scanWineStateCaches();
301
302 if (progressCallback)
303 progressCallback(100, "Scan complete");
304
305 return static_cast<int>(impl_->caches.size());
306}
307
308// ==============================================================================
309// Game-Specific Caches
310// ==============================================================================
311
313 const std::filesystem::path& winePrefix,
314 uint32_t steamAppId) const
315{
316 GameShaderCache result;
317 result.gameId = gameId;
318
319 // Find DXVK cache
320 if (!winePrefix.empty())
321 {
322 auto dxvk = findDXVKCache(winePrefix);
323 if (dxvk)
324 {
325 result.caches.push_back(*dxvk);
326 result.totalSize += dxvk->size;
327 result.hasDXVK = true;
328 }
329
330 auto vkd3d = findVKD3DCache(winePrefix);
331 if (vkd3d)
332 {
333 result.caches.push_back(*vkd3d);
334 result.totalSize += vkd3d->size;
335 result.hasVKD3D = true;
336 }
337 }
338
339 // Find Steam shader cache
340 if (steamAppId > 0)
341 {
342 auto steam = findSteamShaderCache(steamAppId);
343 if (steam)
344 {
345 result.caches.push_back(*steam);
346 result.totalSize += steam->size;
347 result.hasSteamCache = true;
348 }
349 }
350
351 return result;
352}
353
354std::optional<ShaderCacheInfo>
355ShaderCacheManager::findDXVKCache(const std::filesystem::path& winePrefix) const
356{
357 // DXVK stores cache in the prefix
358 std::filesystem::path cachePath = winePrefix / "drive_c" / "dxvk_cache";
359
360 // Also check for .dxvk-cache files in common locations
361 std::vector<std::filesystem::path> searchPaths = {
362 cachePath,
363 winePrefix / "drive_c" / "users" / "steamuser" / "Local Settings" / "Application Data",
364 };
365
366 for (const auto& path : searchPaths)
367 {
368 if (fileExists(path))
369 {
370 return getCacheInfo(path);
371 }
372 }
373
374 // Look for .dxvk-cache files
375 std::error_code ec;
376 for (const auto& entry : std::filesystem::recursive_directory_iterator(winePrefix, ec))
377 {
378 if (entry.is_regular_file())
379 {
380 std::string filename = entry.path().filename().string();
381 if (filename.find(".dxvk-cache") != std::string::npos)
382 {
383 ShaderCacheInfo info;
385 info.name = "DXVK Cache";
386 info.path = entry.path().parent_path();
387 info.size = calculateDirectorySize(info.path);
388 info.fileCount = countFiles(info.path);
389 info.lastModified = getModTime(entry.path());
390 info.exists = true;
391 return info;
392 }
393 }
394 }
395 if (ec)
396 {
397 Logger::warn("ShaderCacheManager: error scanning {} for DXVK cache: {}",
398 winePrefix.string(), ec.message());
399 }
400
401 return std::nullopt;
402}
403
404std::optional<ShaderCacheInfo>
405ShaderCacheManager::findVKD3DCache(const std::filesystem::path& winePrefix) const
406{
407 // VKD3D-Proton stores cache in the prefix
408 std::filesystem::path cachePath = winePrefix / "vkd3d-proton";
409
410 if (fileExists(cachePath))
411 {
412 return getCacheInfo(cachePath);
413 }
414
415 // Also check XDG cache
416 std::filesystem::path xdgPath = getXDGCacheHome() / "vkd3d-proton";
417 if (fileExists(xdgPath))
418 {
419 return getCacheInfo(xdgPath);
420 }
421
422 return std::nullopt;
423}
424
425std::optional<ShaderCacheInfo> ShaderCacheManager::findSteamShaderCache(uint32_t steamAppId) const
426{
427 for (const auto& steamPath : impl_->steamLibraryPaths)
428 {
429 std::filesystem::path shaderPath =
430 steamPath / "steamapps" / "shadercache" / std::to_string(steamAppId);
431
432 if (fileExists(shaderPath))
433 {
434 ShaderCacheInfo info;
436 info.name = "Steam Shader Cache (" + std::to_string(steamAppId) + ")";
437 info.path = shaderPath;
438 info.size = calculateDirectorySize(shaderPath);
439 info.fileCount = countFiles(shaderPath);
440 info.lastModified = getModTime(shaderPath);
441 info.exists = true;
442 return info;
443 }
444 }
445
446 return std::nullopt;
447}
448
449// ==============================================================================
450// Statistics
451// ==============================================================================
452
454{
455 std::lock_guard<std::mutex> lock(impl_->mutex);
456 ShaderCacheStats stats;
457
458 for (const auto& cache : impl_->caches)
459 {
460 stats.totalSize += cache.size;
461 stats.totalFiles += cache.fileCount;
462 stats.cacheDirectories++;
463
464 switch (cache.type)
465 {
467 stats.mesaSize += cache.size;
468 break;
470 stats.nvidiaSize += cache.size;
471 break;
473 stats.dxvkSize += cache.size;
474 break;
476 stats.vkd3dSize += cache.size;
477 break;
479 stats.steamSize += cache.size;
480 break;
482 stats.fossilizeSize += cache.size;
483 break;
485 stats.wineStateSize += cache.size;
486 break;
487 default:
488 break;
489 }
490 }
491
492 return stats;
493}
494
496{
497 return getStats().totalSize;
498}
499
501{
502 auto caches = getCachesByType(type);
503 int64_t total = 0;
504 for (const auto& cache : caches)
505 {
506 total += cache.size;
507 }
508 return total;
509}
510
511// ==============================================================================
512// Cache Clearing
513// ==============================================================================
514
515CacheClearResult ShaderCacheManager::clearCache(const std::filesystem::path& cachePath)
516{
517 CacheClearResult result;
518
519 if (!fileExists(cachePath))
520 {
521 result.errors.push_back("Cache path does not exist: " + cachePath.string());
522 result.success = false;
523 return result;
524 }
525
526 // Calculate size before clearing
527 result.bytesCleared = calculateDirectorySize(cachePath);
528 result.filesCleared = countFiles(cachePath);
529
530 std::error_code ec;
531 if (isDirectory(cachePath))
532 {
533 // Clear contents but keep directory
534 for (const auto& entry : std::filesystem::directory_iterator(cachePath, ec))
535 {
536 std::filesystem::remove_all(entry.path(), ec);
537 if (ec)
538 {
539 result.errors.push_back("Failed to remove: " + entry.path().string());
540 }
541 }
542 result.directoriesCleared = 1;
543 }
544 else
545 {
546 std::filesystem::remove(cachePath, ec);
547 if (ec)
548 {
549 result.errors.push_back("Failed to remove: " + cachePath.string());
550 }
551 }
552
553 result.success = result.errors.empty();
554
555 // Update internal cache list
556 if (result.success)
557 {
558 std::lock_guard<std::mutex> lock(impl_->mutex);
559 impl_->caches.erase(std::remove_if(impl_->caches.begin(), impl_->caches.end(),
560 [&cachePath](const ShaderCacheInfo& c)
561 { return c.path == cachePath; }),
562 impl_->caches.end());
563 }
564
565 return result;
566}
567
569 const ProgressCallback& progressCallback)
570{
571 auto caches = getCachesByType(type);
572 CacheClearResult totalResult;
573
574 for (size_t i = 0; i < caches.size(); ++i)
575 {
576 if (progressCallback)
577 {
578 int percent = static_cast<int>(((i + 1) * 100) / caches.size());
579 progressCallback(percent, "Clearing: " + caches[i].path.string());
580 }
581
582 auto result = clearCache(caches[i].path);
583 totalResult.bytesCleared += result.bytesCleared;
584 totalResult.filesCleared += result.filesCleared;
585 totalResult.directoriesCleared += result.directoriesCleared;
586 totalResult.errors.insert(totalResult.errors.end(), result.errors.begin(),
587 result.errors.end());
588 }
589
590 totalResult.success = totalResult.errors.empty();
591
592 if (progressCallback)
593 {
594 progressCallback(100, "Complete");
595 }
596
597 return totalResult;
598}
599
601 const std::filesystem::path& winePrefix,
602 uint32_t steamAppId)
603{
604 auto gameCache = getGameCache(gameId, winePrefix, steamAppId);
605 CacheClearResult totalResult;
606
607 for (const auto& cache : gameCache.caches)
608 {
609 if (type != ShaderCacheType::All && cache.type != type)
610 {
611 continue;
612 }
613
614 auto result = clearCache(cache.path);
615 totalResult.bytesCleared += result.bytesCleared;
616 totalResult.filesCleared += result.filesCleared;
617 totalResult.directoriesCleared += result.directoriesCleared;
618 totalResult.errors.insert(totalResult.errors.end(), result.errors.begin(),
619 result.errors.end());
620 }
621
622 totalResult.success = totalResult.errors.empty();
623 return totalResult;
624}
625
627{
628 CacheClearResult totalResult;
629 auto caches = getAllCaches();
630
631 for (size_t i = 0; i < caches.size(); ++i)
632 {
633 if (progressCallback)
634 {
635 int percent = static_cast<int>(((i + 1) * 100) / caches.size());
636 progressCallback(percent, "Clearing: " + caches[i].path.string());
637 }
638
639 auto result = clearCache(caches[i].path);
640 totalResult.bytesCleared += result.bytesCleared;
641 totalResult.filesCleared += result.filesCleared;
642 totalResult.directoriesCleared += result.directoriesCleared;
643 totalResult.errors.insert(totalResult.errors.end(), result.errors.begin(),
644 result.errors.end());
645 }
646
647 totalResult.success = totalResult.errors.empty();
648
649 if (progressCallback)
650 {
651 progressCallback(100, "All caches cleared");
652 }
653
654 return totalResult;
655}
656
658 const ProgressCallback& progressCallback)
659{
660 CacheClearResult totalResult;
661 auto now = std::chrono::system_clock::now();
662 auto caches = getAllCaches();
663 size_t processed = 0;
664
665 for (const auto& cache : caches)
666 {
667 auto age = std::chrono::duration_cast<std::chrono::hours>(now - cache.lastModified);
668 if (age > olderThan)
669 {
670 if (progressCallback)
671 {
672 int percent = static_cast<int>((processed * 100) / caches.size());
673 progressCallback(percent, "Clearing stale: " + cache.path.string());
674 }
675
676 auto result = clearCache(cache.path);
677 totalResult.bytesCleared += result.bytesCleared;
678 totalResult.filesCleared += result.filesCleared;
679 totalResult.directoriesCleared += result.directoriesCleared;
680 totalResult.errors.insert(totalResult.errors.end(), result.errors.begin(),
681 result.errors.end());
682 }
683 processed++;
684 }
685
686 totalResult.success = totalResult.errors.empty();
687
688 if (progressCallback)
689 {
690 progressCallback(100, "Stale caches cleared");
691 }
692
693 return totalResult;
694}
695
696// ==============================================================================
697// Backup & Restore
698// ==============================================================================
699
700std::filesystem::path ShaderCacheManager::backupCache(const std::filesystem::path& cachePath,
701 const std::filesystem::path& backupDir)
702{
703 if (!fileExists(cachePath))
704 {
705 return {};
706 }
707
708 std::filesystem::path destDir = backupDir.empty() ? impl_->backupDir : backupDir;
709 createDirectories(destDir);
710
711 // Create timestamp-based backup name
712 auto now = std::chrono::system_clock::now();
713 auto time = std::chrono::system_clock::to_time_t(now);
714 char timestamp[32];
715 std::tm tm{};
716 localtime_r(&time, &tm);
717 std::strftime(timestamp, sizeof(timestamp), "%Y%m%d_%H%M%S", &tm);
718
719 std::string backupName = cachePath.filename().string() + "_" + timestamp;
720 std::filesystem::path backupPath = destDir / backupName;
721
722 std::error_code ec;
723 // SECURITY (CWE-59): skip_symlinks so a symlink inside the shader cache
724 // cannot be followed to copy data from / write data to outside the tree.
725 std::filesystem::copy(cachePath, backupPath,
726 std::filesystem::copy_options::recursive |
727 std::filesystem::copy_options::skip_symlinks,
728 ec);
729
730 if (ec)
731 {
732 return {};
733 }
734
735 return backupPath;
736}
737
738bool ShaderCacheManager::restoreCache(const std::filesystem::path& backupPath,
739 const std::filesystem::path& targetPath)
740{
741 if (!fileExists(backupPath))
742 {
743 return false;
744 }
745
746 // Clear target first
747 if (fileExists(targetPath))
748 {
749 clearCache(targetPath);
750 }
751
752 createDirectories(targetPath.parent_path());
753
754 std::error_code ec;
755 // SECURITY (CWE-59): skip_symlinks — never follow a symlink in the backup
756 // tree when restoring into the live cache location.
757 std::filesystem::copy(backupPath, targetPath,
758 std::filesystem::copy_options::recursive |
759 std::filesystem::copy_options::skip_symlinks,
760 ec);
761
762 return !ec;
763}
764
765std::vector<std::filesystem::path> ShaderCacheManager::getCacheBackups() const
766{
767 std::vector<std::filesystem::path> backups;
768
769 if (!fileExists(impl_->backupDir))
770 {
771 return backups;
772 }
773
774 std::error_code ec;
775 for (const auto& entry : std::filesystem::directory_iterator(impl_->backupDir, ec))
776 {
777 if (entry.is_directory())
778 {
779 backups.push_back(entry.path());
780 }
781 }
782 if (ec)
783 {
784 Logger::warn("ShaderCacheManager: error listing backups in {}: {}",
785 impl_->backupDir.string(), ec.message());
786 }
787
788 // Sort by modification time (newest first)
789 std::sort(backups.begin(), backups.end(),
790 [](const auto& a, const auto& b) { return getModTime(a) > getModTime(b); });
791
792 return backups;
793}
794
796{
797 auto backups = getCacheBackups();
798 int deleted = 0;
799
800 if (static_cast<int>(backups.size()) <= keepCount)
801 {
802 return 0;
803 }
804
805 // Delete oldest backups
806 for (size_t i = static_cast<size_t>(keepCount); i < backups.size(); ++i)
807 {
808 std::error_code ec;
809 std::filesystem::remove_all(backups[i], ec);
810 if (!ec)
811 {
812 deleted++;
813 }
814 }
815
816 return deleted;
817}
818
819// ==============================================================================
820// Configuration
821// ==============================================================================
822
823void ShaderCacheManager::setBackupDirectory(const std::filesystem::path& path)
824{
825 {
826 std::lock_guard<std::mutex> lock(impl_->mutex);
827 impl_->backupDir = path;
828 }
829 createDirectories(path);
830}
831
832std::filesystem::path ShaderCacheManager::getBackupDirectory() const
833{
834 return impl_->backupDir;
835}
836
837void ShaderCacheManager::addCustomCacheLocation(const std::filesystem::path& path,
838 ShaderCacheType type)
839{
840 std::lock_guard<std::mutex> lock(impl_->mutex);
841 impl_->customLocations.emplace_back(path, type);
842}
843
844void ShaderCacheManager::setSteamLibraryPaths(const std::vector<std::filesystem::path>& paths)
845{
846 std::lock_guard<std::mutex> lock(impl_->mutex);
847 impl_->steamLibraryPaths = paths;
848}
849
850// ==============================================================================
851// Utility
852// ==============================================================================
853
854std::optional<ShaderCacheType>
855ShaderCacheManager::identifyCacheType(const std::filesystem::path& path) const
856{
857 std::string pathStr = path.string();
858 std::string filename = path.filename().string();
859
860 // Check by path patterns
861 if (pathStr.find("mesa_shader_cache") != std::string::npos ||
862 pathStr.find("GLCache") != std::string::npos ||
863 pathStr.find("shader_cache") != std::string::npos)
864 {
866 }
867
868 if (pathStr.find("nvidia") != std::string::npos ||
869 pathStr.find("NVIDIA") != std::string::npos || pathStr.find("GLCache") != std::string::npos)
870 {
872 }
873
874 if (pathStr.find("dxvk") != std::string::npos ||
875 filename.find(".dxvk-cache") != std::string::npos)
876 {
878 }
879
880 if (pathStr.find("vkd3d") != std::string::npos)
881 {
883 }
884
885 if (pathStr.find("shadercache") != std::string::npos ||
886 pathStr.find("shader_cache") != std::string::npos)
887 {
888 // Check if it's Steam's shader cache
889 if (pathStr.find("Steam") != std::string::npos ||
890 pathStr.find("steam") != std::string::npos)
891 {
893 }
894 }
895
896 if (pathStr.find("fossilize") != std::string::npos)
897 {
899 }
900
901 if (pathStr.find("wine") != std::string::npos || pathStr.find("proton") != std::string::npos)
902 {
903 if (pathStr.find("state") != std::string::npos)
904 {
906 }
907 }
908
909 return std::nullopt;
910}
911
912std::vector<std::filesystem::path>
914{
915 std::vector<std::filesystem::path> paths;
916 auto home = getHomeDir();
917 auto cache = getXDGCacheHome();
918
919 switch (type)
920 {
922 paths.push_back(cache / "mesa_shader_cache");
923 paths.push_back(cache / "mesa_shader_cache_db");
924 paths.push_back(home / ".cache" / "mesa_shader_cache");
925 break;
926
928 paths.push_back(cache / "nvidia" / "GLCache");
929 paths.push_back(home / ".nv" / "GLCache");
930 break;
931
933 // DXVK caches are in Wine prefixes
934 break;
935
937 paths.push_back(cache / "vkd3d-proton");
938 break;
939
941 for (const auto& steamPath : impl_->steamLibraryPaths)
942 {
943 paths.push_back(steamPath / "steamapps" / "shadercache");
944 }
945 break;
946
948 paths.push_back(cache / "fossilize");
949 for (const auto& steamPath : impl_->steamLibraryPaths)
950 {
951 paths.push_back(steamPath / "steamapps" / "shadercache" / "fozpipelinesv6");
952 }
953 break;
954
956 // Wine state caches are in prefixes
957 break;
958
959 default:
960 break;
961 }
962
963 return paths;
964}
965
966// ==============================================================================
967// Private Scanning Methods
968// ==============================================================================
969
970void ShaderCacheManager::scanMesaCaches()
971{
973 for (const auto& path : locations)
974 {
975 if (fileExists(path))
976 {
977 ShaderCacheInfo info;
979 info.name = "Mesa Shader Cache";
980 info.path = path;
981 info.size = calculateDirectorySize(path);
982 info.fileCount = countFiles(path);
983 info.lastModified = getModTime(path);
984 info.exists = true;
985 impl_->caches.push_back(info);
986 }
987 }
988}
989
990void ShaderCacheManager::scanNVIDIACaches()
991{
993 for (const auto& path : locations)
994 {
995 if (fileExists(path))
996 {
997 ShaderCacheInfo info;
999 info.name = "NVIDIA GL Cache";
1000 info.path = path;
1001 info.size = calculateDirectorySize(path);
1002 info.fileCount = countFiles(path);
1003 info.lastModified = getModTime(path);
1004 info.exists = true;
1005 impl_->caches.push_back(info);
1006 }
1007 }
1008}
1009
1010void ShaderCacheManager::scanDXVKCaches()
1011{
1012 // Scan common prefix locations for DXVK caches
1013 auto home = getHomeDir();
1014 std::vector<std::filesystem::path> prefixLocations = {
1015 home / ".wine",
1016 home / "Games",
1017 home / ".local" / "share" / "Steam" / "steamapps" / "compatdata",
1018 home / ".steam" / "steam" / "steamapps" / "compatdata",
1019 };
1020
1021 for (const auto& prefixRoot : prefixLocations)
1022 {
1023 if (!fileExists(prefixRoot))
1024 continue;
1025
1026 std::error_code ec;
1027 for (const auto& entry : std::filesystem::directory_iterator(prefixRoot, ec))
1028 {
1029 if (!entry.is_directory())
1030 continue;
1031
1032 auto dxvk = findDXVKCache(entry.path());
1033 if (dxvk)
1034 {
1035 impl_->caches.push_back(*dxvk);
1036 }
1037 }
1038 }
1039}
1040
1041void ShaderCacheManager::scanVKD3DCaches()
1042{
1044 for (const auto& path : locations)
1045 {
1046 if (fileExists(path))
1047 {
1048 ShaderCacheInfo info;
1050 info.name = "VKD3D-Proton Cache";
1051 info.path = path;
1052 info.size = calculateDirectorySize(path);
1053 info.fileCount = countFiles(path);
1054 info.lastModified = getModTime(path);
1055 info.exists = true;
1056 impl_->caches.push_back(info);
1057 }
1058 }
1059}
1060
1061void ShaderCacheManager::scanSteamCaches()
1062{
1063 for (const auto& steamPath : impl_->steamLibraryPaths)
1064 {
1065 std::filesystem::path shaderDir = steamPath / "steamapps" / "shadercache";
1066 if (!fileExists(shaderDir))
1067 continue;
1068
1069 std::error_code ec;
1070 for (const auto& entry : std::filesystem::directory_iterator(shaderDir, ec))
1071 {
1072 if (!entry.is_directory())
1073 continue;
1074
1075 ShaderCacheInfo info;
1077 info.name = "Steam Shader Cache (" + entry.path().filename().string() + ")";
1078 info.path = entry.path();
1079 info.size = calculateDirectorySize(entry.path());
1080 info.fileCount = countFiles(entry.path());
1081 info.lastModified = getModTime(entry.path());
1082 info.exists = true;
1083 impl_->caches.push_back(info);
1084 }
1085 }
1086}
1087
1088void ShaderCacheManager::scanFossilizeCaches()
1089{
1091 for (const auto& path : locations)
1092 {
1093 if (fileExists(path))
1094 {
1095 ShaderCacheInfo info;
1097 info.name = "Fossilize Pipeline Cache";
1098 info.path = path;
1099 info.size = calculateDirectorySize(path);
1100 info.fileCount = countFiles(path);
1101 info.lastModified = getModTime(path);
1102 info.exists = true;
1103 impl_->caches.push_back(info);
1104 }
1105 }
1106}
1107
1108void ShaderCacheManager::scanWineStateCaches()
1109{
1110 // Similar to DXVK - scan prefix locations
1111 auto home = getHomeDir();
1112 std::vector<std::filesystem::path> prefixLocations = {
1113 home / ".wine",
1114 home / "Games",
1115 };
1116
1117 for (const auto& prefixRoot : prefixLocations)
1118 {
1119 if (!fileExists(prefixRoot))
1120 continue;
1121
1122 // Check for Wine state directories
1123 std::filesystem::path statePath = prefixRoot / "drive_c" / "windows" / "syswow64";
1124 if (fileExists(statePath))
1125 {
1126 // This is a simplification - Wine state is complex
1127 // For now, just note that this prefix has state
1128 }
1129 }
1130}
1131
1132int64_t ShaderCacheManager::calculateDirectorySize(const std::filesystem::path& path) const
1133{
1134 // Use a fresh error_code per filesystem call. Reusing one variable
1135 // across calls causes a later success to clear the bit set by an
1136 // earlier failure, masking the original error. We don't actually
1137 // surface failures to the caller (this is best-effort sizing) but the
1138 // separate locals make the intent explicit and reduce clang-tidy noise.
1139
1140 std::error_code typeEc;
1141 if (std::filesystem::is_regular_file(path, typeEc))
1142 {
1143 std::error_code sizeEc;
1144 return static_cast<int64_t>(std::filesystem::file_size(path, sizeEc));
1145 }
1146
1147 int64_t size = 0;
1148 std::error_code iterEc;
1149 for (const auto& entry : std::filesystem::recursive_directory_iterator(path, iterEc))
1150 {
1151 std::error_code fileTypeEc;
1152 if (entry.is_regular_file(fileTypeEc))
1153 {
1154 std::error_code fileSizeEc;
1155 const auto bytes = entry.file_size(fileSizeEc);
1156 if (!fileSizeEc)
1157 {
1158 size += static_cast<int64_t>(bytes);
1159 }
1160 }
1161 }
1162
1163 return size;
1164}
1165
1166int ShaderCacheManager::countFiles(const std::filesystem::path& path) const
1167{
1168 // Same per-call error_code policy as calculateDirectorySize.
1169 std::error_code typeEc;
1170 if (std::filesystem::is_regular_file(path, typeEc))
1171 {
1172 return 1;
1173 }
1174
1175 int count = 0;
1176 std::error_code iterEc;
1177 for (const auto& entry : std::filesystem::recursive_directory_iterator(path, iterEc))
1178 {
1179 std::error_code fileTypeEc;
1180 if (entry.is_regular_file(fileTypeEc))
1181 {
1182 count++;
1183 }
1184 }
1185
1186 return count;
1187}
static void warn(const std::string &message, Args &&... args)
Log warning message (non-critical issue).
Definition logger.h:116
std::optional< ShaderCacheInfo > findSteamShaderCache(uint32_t steamAppId) const
Find Steam shader cache for a game.
std::vector< ShaderCacheInfo > getCachesByType(ShaderCacheType type) const
Get caches by type.
std::filesystem::path backupCache(const std::filesystem::path &cachePath, const std::filesystem::path &backupDir={})
Backup a shader cache before clearing.
std::filesystem::path getBackupDirectory() const
Get the backup directory.
void setBackupDirectory(const std::filesystem::path &path)
Set the backup directory.
std::optional< ShaderCacheType > identifyCacheType(const std::filesystem::path &path) const
Check if a path is a valid shader cache.
CacheClearResult clearCache(const std::filesystem::path &cachePath)
Clear a specific cache.
int scanCaches(const ProgressCallback &progressCallback=nullptr)
Scan for all shader caches on the system.
int64_t getTotalCacheSize() const
Get total cache size.
void addCustomCacheLocation(const std::filesystem::path &path, ShaderCacheType type)
Add a custom cache location to scan.
std::vector< std::filesystem::path > getDefaultCacheLocations(ShaderCacheType type) const
Get the default cache location for a type.
void setSteamLibraryPaths(const std::vector< std::filesystem::path > &paths)
Set Steam library paths.
ShaderCacheStats getStats() const
Get overall shader cache statistics.
CacheClearResult clearCachesByType(ShaderCacheType type, const ProgressCallback &progressCallback=nullptr)
Clear all caches of a specific type.
CacheClearResult clearAllCaches(const ProgressCallback &progressCallback=nullptr)
Clear all shader caches (use with caution!).
std::optional< ShaderCacheInfo > findDXVKCache(const std::filesystem::path &winePrefix) const
Find DXVK cache for a game.
std::vector< std::filesystem::path > getCacheBackups() const
Get list of cache backups.
std::optional< ShaderCacheInfo > findVKD3DCache(const std::filesystem::path &winePrefix) const
Find VKD3D cache for a game.
GameShaderCache getGameCache(const std::string &gameId, const std::filesystem::path &winePrefix={}, uint32_t steamAppId=0) const
Get shader caches for a specific game.
int64_t getCacheSizeByType(ShaderCacheType type) const
Get cache size by type.
int pruneBackups(int keepCount=3)
Delete old cache backups.
std::function< void(int percent, const std::string &status)> ProgressCallback
std::optional< ShaderCacheInfo > getCacheInfo(const std::filesystem::path &path) const
Get cache info for a specific path.
std::vector< ShaderCacheInfo > getAllCaches() const
Get all detected shader caches.
CacheClearResult clearGameCache(const std::string &gameId, ShaderCacheType type=ShaderCacheType::All, const std::filesystem::path &winePrefix={}, uint32_t steamAppId=0)
Clear shader cache for a specific game.
bool restoreCache(const std::filesystem::path &backupPath, const std::filesystem::path &targetPath)
Restore a shader cache from backup.
CacheClearResult clearStaleCaches(std::chrono::hours olderThan=std::chrono::hours(720), const ProgressCallback &progressCallback=nullptr)
Clear old/stale caches.
std::chrono::system_clock::time_point getModTime(const std::filesystem::path &path)
bool isDirectory(const std::filesystem::path &path)
bool fileExists(const std::filesystem::path &path)
bool createDirectories(const std::filesystem::path &path)
bool fileExists(const std::filesystem::path &path)
std::string shaderCacheTypeName(ShaderCacheType type)
Get human-readable cache type name.
ShaderCacheType
Types of shader caches.
@ WineState
Wine/Proton state cache.
@ Fossilize
Fossilize pipeline cache.
@ Mesa
Mesa (AMD/Intel) GLCache and shader_cache.
@ NVIDIA
NVIDIA proprietary driver cache.
@ DXVK
DXVK Vulkan-based D3D implementation.
@ All
All cache types.
@ VKD3D
VKD3D-Proton D3D12 implementation.
@ SteamShader
Steam's shader pre-caching.
std::string shaderCacheTypeName(ShaderCacheType type)
Get human-readable cache type name.
Result of a cache clearing operation.
std::vector< std::string > errors
std::string getFormattedBytesCleared() const
Shader cache information for a specific game.
std::string getFormattedTotalSize() const
std::vector< ShaderCacheInfo > caches
Information about a shader cache.
bool exists
Whether the cache exists.
std::string name
Human-readable name.
int64_t size
Size in bytes.
int fileCount
Number of cache files.
std::string getTypeName() const
std::chrono::system_clock::time_point lastModified
std::string getFormattedSize() const
ShaderCacheType type
std::filesystem::path path
Path to cache directory/file.
std::vector< std::filesystem::path > steamLibraryPaths
std::filesystem::path backupDir
std::vector< std::pair< std::filesystem::path, ShaderCacheType > > customLocations
std::vector< ShaderCacheInfo > caches
Overall shader cache statistics.
std::string getFormattedTotalSize() const