ShaderCache.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. #include "ShaderCache.h"
  2. #include <algorithm>
  3. #include <chrono>
  4. #include <cstdlib>
  5. #include <cstring>
  6. #include <fstream>
  7. #include <unistd.h>
  8. #include <vector>
  9. #include "WallpaperEngine/Logging/Log.h"
  10. using namespace WallpaperEngine::Render::Shaders;
  11. namespace {
  12. constexpr char MAGIC[8] = { 'L', 'W', 'E', 'S', 'H', 'C', '0', '1' };
  13. // pruned to 3/4 of this on a run's first write and again every 1/16 of it written
  14. constexpr uint64_t SIZE_LIMIT = 256ull * 1024 * 1024;
  15. uint64_t fnv1a (const std::string& data) {
  16. uint64_t hash = 0xcbf29ce484222325ull;
  17. for (const unsigned char c : data) {
  18. hash = (hash ^ c) * 0x100000001b3ull;
  19. }
  20. return hash;
  21. }
  22. /** guards against file name collisions */
  23. uint64_t mix64 (const std::string& data) {
  24. uint64_t hash = 0x9e3779b97f4a7c15ull ^ data.size ();
  25. size_t i = 0;
  26. const auto round = [&hash] (uint64_t value) {
  27. value *= 0xbf58476d1ce4e5b9ull;
  28. value ^= value >> 31;
  29. hash = (hash ^ value) * 0x94d049bb133111ebull;
  30. hash ^= hash >> 29;
  31. };
  32. for (; i + 8 <= data.size (); i += 8) {
  33. uint64_t value;
  34. memcpy (&value, data.data () + i, 8);
  35. round (value);
  36. }
  37. uint64_t tail = 0;
  38. memcpy (&tail, data.data () + i, data.size () - i);
  39. round (tail);
  40. return hash;
  41. }
  42. void appendU32 (std::string& out, uint32_t value) { out.append (reinterpret_cast<const char*> (&value), 4); }
  43. void appendString (std::string& out, const std::string& value) {
  44. appendU32 (out, static_cast<uint32_t> (value.size ()));
  45. out += value;
  46. }
  47. bool readU32 (const std::string& in, size_t& offset, uint32_t& value) {
  48. if (offset + 4 > in.size ()) {
  49. return false;
  50. }
  51. memcpy (&value, in.data () + offset, 4);
  52. offset += 4;
  53. return true;
  54. }
  55. bool readString (const std::string& in, size_t& offset, std::string& value) {
  56. uint32_t size;
  57. if (!readU32 (in, offset, size) || offset + size > in.size ()) {
  58. return false;
  59. }
  60. value.assign (in, offset, size);
  61. offset += size;
  62. return true;
  63. }
  64. std::filesystem::path cacheDirectory () {
  65. if (const char* home = std::getenv ("XDG_CACHE_HOME"); home != nullptr && home[0] == '/') {
  66. return std::filesystem::path (home) / "linux-wallpaperengine" / "shaders";
  67. }
  68. if (const char* home = std::getenv ("HOME"); home != nullptr && home[0] != '\0') {
  69. return std::filesystem::path (home) / ".cache" / "linux-wallpaperengine" / "shaders";
  70. }
  71. return {};
  72. }
  73. } // namespace
  74. ShaderCache& ShaderCache::get () {
  75. static ShaderCache instance;
  76. return instance;
  77. }
  78. ShaderCache::ShaderCache () : m_directory (cacheDirectory ()) { this->m_enabled = !this->m_directory.empty (); }
  79. void ShaderCache::setEnabled (bool enabled) {
  80. std::lock_guard lock (this->m_mutex);
  81. this->m_enabled = enabled && !this->m_directory.empty ();
  82. }
  83. std::optional<ShaderCache::Entry> ShaderCache::entry (const std::string& kind, const std::string& key) const {
  84. if (!this->m_enabled) {
  85. return std::nullopt;
  86. }
  87. char name[17];
  88. snprintf (name, sizeof (name), "%016llx", static_cast<unsigned long long> (fnv1a (key)));
  89. return Entry { .path = this->m_directory / kind / name, .check = mix64 (key) };
  90. }
  91. std::optional<std::string> ShaderCache::read (const Entry& entry) const {
  92. std::ifstream file (entry.path, std::ios::binary);
  93. if (!file) {
  94. return std::nullopt;
  95. }
  96. std::string data ((std::istreambuf_iterator<char> (file)), std::istreambuf_iterator<char> ());
  97. uint64_t check;
  98. if (data.size () < sizeof (MAGIC) + 8 || memcmp (data.data (), MAGIC, sizeof (MAGIC)) != 0) {
  99. return std::nullopt;
  100. }
  101. memcpy (&check, data.data () + sizeof (MAGIC), 8);
  102. if (check != entry.check) {
  103. return std::nullopt;
  104. }
  105. std::error_code error;
  106. std::filesystem::last_write_time (entry.path, std::filesystem::file_time_type::clock::now (), error);
  107. return data.substr (sizeof (MAGIC) + 8);
  108. }
  109. void ShaderCache::write (const Entry& entry, const std::string& payload) {
  110. std::error_code error;
  111. std::filesystem::create_directories (entry.path.parent_path (), error);
  112. if (error) {
  113. return;
  114. }
  115. const auto temporary = entry.path.string () + "." + std::to_string (getpid ()) + ".tmp";
  116. {
  117. std::ofstream file (temporary, std::ios::binary | std::ios::trunc);
  118. if (!file) {
  119. return;
  120. }
  121. file.write (MAGIC, sizeof (MAGIC));
  122. file.write (reinterpret_cast<const char*> (&entry.check), 8);
  123. file.write (payload.data (), static_cast<std::streamsize> (payload.size ()));
  124. if (!file) {
  125. file.close ();
  126. std::filesystem::remove (temporary, error);
  127. return;
  128. }
  129. }
  130. std::filesystem::rename (temporary, entry.path, error);
  131. if (error) {
  132. std::filesystem::remove (temporary, error);
  133. return;
  134. }
  135. this->m_bytesWritten += payload.size ();
  136. if (!this->m_pruned || this->m_bytesWritten > SIZE_LIMIT / 16) {
  137. this->prune ();
  138. }
  139. }
  140. void ShaderCache::prune () {
  141. this->m_pruned = true;
  142. this->m_bytesWritten = 0;
  143. struct File {
  144. std::filesystem::path path;
  145. std::filesystem::file_time_type time;
  146. uintmax_t size;
  147. };
  148. std::vector<File> files;
  149. uintmax_t total = 0;
  150. std::error_code error;
  151. for (auto it = std::filesystem::recursive_directory_iterator (this->m_directory, error);
  152. !error && it != std::filesystem::recursive_directory_iterator (); it.increment (error)) {
  153. if (!it->is_regular_file (error)) {
  154. continue;
  155. }
  156. const auto size = it->file_size (error);
  157. const auto time = it->last_write_time (error);
  158. if (!error) {
  159. files.push_back ({ it->path (), time, size });
  160. total += size;
  161. }
  162. }
  163. if (total <= SIZE_LIMIT) {
  164. return;
  165. }
  166. std::ranges::sort (files, {}, &File::time);
  167. for (const auto& file : files) {
  168. if (total <= SIZE_LIMIT / 4 * 3) {
  169. break;
  170. }
  171. if (std::filesystem::remove (file.path, error)) {
  172. total -= file.size;
  173. }
  174. }
  175. }
  176. std::optional<GLSLContext::Sources> ShaderCache::loadTranslation (const std::string& key) {
  177. std::lock_guard lock (this->m_mutex);
  178. const auto entry = this->entry ("translations", key);
  179. if (!entry.has_value ()) {
  180. return std::nullopt;
  181. }
  182. const auto data = this->read (*entry);
  183. if (!data.has_value ()) {
  184. return std::nullopt;
  185. }
  186. GLSLContext::Sources sources;
  187. size_t offset = 0;
  188. if (!readString (*data, offset, sources.vertex) || !readString (*data, offset, sources.fragment)
  189. || !readString (*data, offset, sources.geometry) || offset != data->size ()) {
  190. return std::nullopt;
  191. }
  192. return sources;
  193. }
  194. void ShaderCache::storeTranslation (const std::string& key, const GLSLContext::Sources& sources) {
  195. std::lock_guard lock (this->m_mutex);
  196. const auto entry = this->entry ("translations", key);
  197. if (!entry.has_value ()) {
  198. return;
  199. }
  200. std::string payload;
  201. payload.reserve (sources.vertex.size () + sources.fragment.size () + sources.geometry.size () + 12);
  202. appendString (payload, sources.vertex);
  203. appendString (payload, sources.fragment);
  204. appendString (payload, sources.geometry);
  205. this->write (*entry, payload);
  206. }
  207. bool ShaderCache::programsSupported () {
  208. std::lock_guard lock (this->m_mutex);
  209. if (!this->m_enabled) {
  210. return false;
  211. }
  212. if (!this->m_programsSupported.has_value ()) {
  213. GLint formats = 0;
  214. if (GLEW_VERSION_4_1 || GLEW_ARB_get_program_binary) {
  215. glGetIntegerv (GL_NUM_PROGRAM_BINARY_FORMATS, &formats);
  216. }
  217. this->m_programsSupported = formats > 0;
  218. // binaries only load into the driver that made them
  219. for (const GLenum name : { GL_VENDOR, GL_RENDERER, GL_VERSION, GL_SHADING_LANGUAGE_VERSION }) {
  220. const auto* value = reinterpret_cast<const char*> (glGetString (name));
  221. this->m_driver += value != nullptr ? value : "";
  222. this->m_driver += '\0';
  223. }
  224. }
  225. return *this->m_programsSupported;
  226. }
  227. GLuint ShaderCache::loadProgram (const std::string& key) {
  228. if (!this->programsSupported ()) {
  229. return 0;
  230. }
  231. std::lock_guard lock (this->m_mutex);
  232. const auto entry = this->entry ("programs", this->m_driver + key);
  233. if (!entry.has_value ()) {
  234. return 0;
  235. }
  236. const auto data = this->read (*entry);
  237. uint32_t format;
  238. size_t offset = 0;
  239. if (!data.has_value () || !readU32 (*data, offset, format) || offset == data->size ()) {
  240. return 0;
  241. }
  242. const GLuint program = glCreateProgram ();
  243. glProgramBinary (program, format, data->data () + offset, static_cast<GLsizei> (data->size () - offset));
  244. GLint linked = GL_FALSE;
  245. glGetProgramiv (program, GL_LINK_STATUS, &linked);
  246. if (linked != GL_TRUE) {
  247. // some driver updates break binaries without a version change
  248. glDeleteProgram (program);
  249. std::error_code error;
  250. std::filesystem::remove (entry->path, error);
  251. return 0;
  252. }
  253. return program;
  254. }
  255. void ShaderCache::storeProgram (const std::string& key, GLuint program) {
  256. if (!this->programsSupported ()) {
  257. return;
  258. }
  259. std::lock_guard lock (this->m_mutex);
  260. const auto entry = this->entry ("programs", this->m_driver + key);
  261. GLint length = 0;
  262. if (!entry.has_value ()) {
  263. return;
  264. }
  265. glGetProgramiv (program, GL_PROGRAM_BINARY_LENGTH, &length);
  266. if (length <= 0) {
  267. return;
  268. }
  269. std::string payload (4 + length, '\0');
  270. GLenum format = 0;
  271. GLsizei written = 0;
  272. glGetProgramBinary (program, length, &written, &format, payload.data () + 4);
  273. if (written <= 0) {
  274. return;
  275. }
  276. memcpy (payload.data (), &format, 4);
  277. payload.resize (4 + written);
  278. this->write (*entry, payload);
  279. }