resource_uid.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /**************************************************************************/
  2. /* resource_uid.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "resource_uid.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/crypto/crypto_core.h"
  33. #include "core/io/dir_access.h"
  34. #include "core/io/file_access.h"
  35. #include "core/io/resource_loader.h"
  36. #include "core/math/random_pcg.h"
  37. // These constants are off by 1, causing the 'z' and '9' characters never to be used.
  38. // This cannot be fixed without breaking compatibility; see GH-83843.
  39. static constexpr uint32_t char_count = ('z' - 'a');
  40. static constexpr uint32_t base = char_count + ('9' - '0');
  41. String ResourceUID::get_cache_file() {
  42. return ProjectSettings::get_singleton()->get_project_data_path().path_join("uid_cache.bin");
  43. }
  44. static constexpr uint8_t uuid_characters[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', '0', '1', '2', '3', '4', '5', '6', '7', '8' };
  45. static constexpr uint32_t uuid_characters_element_count = std_size(uuid_characters);
  46. static constexpr uint8_t max_uuid_number_length = 13; // Max 0x7FFFFFFFFFFFFFFF (uid://d4n4ub6itg400) size is 13 characters.
  47. String ResourceUID::id_to_text(ID p_id) const {
  48. if (p_id < 0) {
  49. return "uid://<invalid>";
  50. }
  51. char32_t tmp[max_uuid_number_length];
  52. uint32_t tmp_size = 0;
  53. do {
  54. uint32_t c = p_id % uuid_characters_element_count;
  55. tmp[tmp_size] = uuid_characters[c];
  56. p_id /= uuid_characters_element_count;
  57. ++tmp_size;
  58. } while (p_id);
  59. // tmp_size + uid:// (6) + 1 for null.
  60. String txt;
  61. txt.resize_uninitialized(tmp_size + 7);
  62. char32_t *p = txt.ptrw();
  63. p[0] = 'u';
  64. p[1] = 'i';
  65. p[2] = 'd';
  66. p[3] = ':';
  67. p[4] = '/';
  68. p[5] = '/';
  69. uint32_t size = 6;
  70. // The above loop give the number backward, recopy it in the string in the correct order.
  71. for (uint32_t i = 0; i < tmp_size; ++i) {
  72. p[size++] = tmp[tmp_size - i - 1];
  73. }
  74. p[size] = 0;
  75. return txt;
  76. }
  77. ResourceUID::ID ResourceUID::text_to_id(const String &p_text) const {
  78. if (!p_text.begins_with("uid://") || p_text == "uid://<invalid>") {
  79. return INVALID_ID;
  80. }
  81. uint32_t l = p_text.length();
  82. uint64_t uid = 0;
  83. for (uint32_t i = 6; i < l; i++) {
  84. uid *= base;
  85. uint32_t c = p_text[i];
  86. if (is_ascii_lower_case(c)) {
  87. uid += c - 'a';
  88. } else if (is_digit(c)) {
  89. uid += c - '0' + char_count;
  90. } else {
  91. return INVALID_ID;
  92. }
  93. }
  94. return ID(uid & 0x7FFFFFFFFFFFFFFF);
  95. }
  96. ResourceUID::ID ResourceUID::create_id() {
  97. // mbedTLS may not be fully initialized when the ResourceUID is created, so we
  98. // need to lazily instantiate the random number generator.
  99. if (crypto == nullptr) {
  100. crypto = memnew(CryptoCore::RandomGenerator);
  101. ((CryptoCore::RandomGenerator *)crypto)->init();
  102. }
  103. while (true) {
  104. ID id = INVALID_ID;
  105. MutexLock lock(mutex);
  106. Error err = ((CryptoCore::RandomGenerator *)crypto)->get_random_bytes((uint8_t *)&id, sizeof(id));
  107. ERR_FAIL_COND_V(err != OK, INVALID_ID);
  108. id &= 0x7FFFFFFFFFFFFFFF;
  109. bool exists = unique_ids.has(id);
  110. if (!exists) {
  111. return id;
  112. }
  113. }
  114. }
  115. ResourceUID::ID ResourceUID::create_id_for_path(const String &p_path) {
  116. ID id = INVALID_ID;
  117. RandomPCG rng;
  118. const String project_name = GLOBAL_GET("application/config/name");
  119. rng.seed(project_name.hash64() * p_path.hash64() * FileAccess::get_md5(p_path).hash64());
  120. while (true) {
  121. int64_t num1 = rng.rand();
  122. int64_t num2 = ((int64_t)rng.rand()) << 32;
  123. id = (num1 | num2) & 0x7FFFFFFFFFFFFFFF;
  124. MutexLock lock(mutex);
  125. if (!unique_ids.has(id)) {
  126. break;
  127. }
  128. }
  129. return id;
  130. }
  131. bool ResourceUID::has_id(ID p_id) const {
  132. MutexLock l(mutex);
  133. return unique_ids.has(p_id);
  134. }
  135. void ResourceUID::add_id(ID p_id, const String &p_path) {
  136. MutexLock l(mutex);
  137. ERR_FAIL_COND(unique_ids.has(p_id));
  138. Cache c;
  139. c.cs = p_path.utf8();
  140. unique_ids[p_id] = c;
  141. if (use_reverse_cache) {
  142. reverse_cache[c.cs] = p_id;
  143. }
  144. changed = true;
  145. }
  146. void ResourceUID::set_id(ID p_id, const String &p_path) {
  147. MutexLock l(mutex);
  148. ERR_FAIL_COND(!unique_ids.has(p_id));
  149. CharString cs = p_path.utf8();
  150. const char *update_ptr = cs.ptr();
  151. const char *cached_ptr = unique_ids[p_id].cs.ptr();
  152. if (update_ptr == nullptr && cached_ptr == nullptr) {
  153. return; // Both are empty strings.
  154. }
  155. if ((update_ptr == nullptr) != (cached_ptr == nullptr) || strcmp(update_ptr, cached_ptr) != 0) {
  156. unique_ids[p_id].cs = cs;
  157. unique_ids[p_id].saved_to_cache = false; //changed
  158. if (use_reverse_cache) {
  159. reverse_cache[cs] = p_id;
  160. }
  161. changed = true;
  162. }
  163. }
  164. String ResourceUID::get_id_path(ID p_id) const {
  165. ERR_FAIL_COND_V_MSG(p_id == INVALID_ID, String(), "Invalid UID.");
  166. MutexLock l(mutex);
  167. const ResourceUID::Cache *cache = unique_ids.getptr(p_id);
  168. #if TOOLS_ENABLED
  169. // On startup, the scan_for_uid_on_startup callback should be set and will
  170. // execute EditorFileSystem::scan_for_uid, which scans all project files
  171. // to reload the UID cache before the first scan.
  172. // Note: EditorFileSystem::scan_for_uid sets scan_for_uid_on_startup to nullptr
  173. // once the first scan_for_uid is complete.
  174. if (!cache && scan_for_uid_on_startup) {
  175. scan_for_uid_on_startup();
  176. cache = unique_ids.getptr(p_id);
  177. }
  178. #endif
  179. ERR_FAIL_COND_V_MSG(!cache, String(), vformat("Unrecognized UID: \"%s\".", id_to_text(p_id)));
  180. const CharString &cs = cache->cs;
  181. return String::utf8(cs.ptr());
  182. }
  183. ResourceUID::ID ResourceUID::get_path_id(const String &p_path) const {
  184. const ID *id = reverse_cache.getptr(p_path.utf8());
  185. if (id) {
  186. return *id;
  187. }
  188. return INVALID_ID;
  189. }
  190. void ResourceUID::remove_id(ID p_id) {
  191. MutexLock l(mutex);
  192. ERR_FAIL_COND(!unique_ids.has(p_id));
  193. if (use_reverse_cache) {
  194. reverse_cache.erase(unique_ids[p_id].cs);
  195. }
  196. unique_ids.erase(p_id);
  197. }
  198. String ResourceUID::uid_to_path(const String &p_uid) {
  199. return singleton->get_id_path(singleton->text_to_id(p_uid));
  200. }
  201. String ResourceUID::path_to_uid(const String &p_path) {
  202. const ID id = ResourceLoader::get_resource_uid(p_path);
  203. if (id == INVALID_ID) {
  204. return p_path;
  205. } else {
  206. return singleton->id_to_text(id);
  207. }
  208. }
  209. String ResourceUID::ensure_path(const String &p_uid_or_path) {
  210. if (p_uid_or_path.begins_with("uid://")) {
  211. return uid_to_path(p_uid_or_path);
  212. }
  213. return p_uid_or_path;
  214. }
  215. Error ResourceUID::save_to_cache() {
  216. String cache_file = get_cache_file();
  217. if (!FileAccess::exists(cache_file)) {
  218. Ref<DirAccess> d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  219. d->make_dir_recursive(String(cache_file).get_base_dir()); //ensure base dir exists
  220. }
  221. Ref<FileAccess> f = FileAccess::open(cache_file, FileAccess::WRITE);
  222. if (f.is_null()) {
  223. return ERR_CANT_OPEN;
  224. }
  225. MutexLock l(mutex);
  226. f->store_32(unique_ids.size());
  227. cache_entries = 0;
  228. for (KeyValue<ID, Cache> &E : unique_ids) {
  229. f->store_64(uint64_t(E.key));
  230. uint32_t s = E.value.cs.length();
  231. f->store_32(s);
  232. f->store_buffer((const uint8_t *)E.value.cs.ptr(), s);
  233. E.value.saved_to_cache = true;
  234. cache_entries++;
  235. }
  236. changed = false;
  237. return OK;
  238. }
  239. Error ResourceUID::load_from_cache(bool p_reset) {
  240. Ref<FileAccess> f = FileAccess::open(get_cache_file(), FileAccess::READ);
  241. if (f.is_null()) {
  242. return ERR_CANT_OPEN;
  243. }
  244. MutexLock l(mutex);
  245. if (p_reset) {
  246. if (use_reverse_cache) {
  247. reverse_cache.clear();
  248. }
  249. unique_ids.clear();
  250. }
  251. uint32_t entry_count = f->get_32();
  252. for (uint32_t i = 0; i < entry_count; i++) {
  253. int64_t id = f->get_64();
  254. int32_t len = f->get_32();
  255. Cache c;
  256. c.cs.resize_uninitialized(len + 1);
  257. ERR_FAIL_COND_V(c.cs.size() != len + 1, ERR_FILE_CORRUPT); // Out of memory.
  258. c.cs[len] = 0;
  259. int32_t rl = f->get_buffer((uint8_t *)c.cs.ptrw(), len);
  260. ERR_FAIL_COND_V(rl != len, ERR_FILE_CORRUPT);
  261. c.saved_to_cache = true;
  262. unique_ids[id] = c;
  263. if (use_reverse_cache) {
  264. reverse_cache[c.cs] = id;
  265. }
  266. }
  267. cache_entries = entry_count;
  268. changed = false;
  269. return OK;
  270. }
  271. Error ResourceUID::update_cache() {
  272. if (!changed) {
  273. return OK;
  274. }
  275. if (cache_entries == 0) {
  276. return save_to_cache();
  277. }
  278. MutexLock l(mutex);
  279. Ref<FileAccess> f;
  280. for (KeyValue<ID, Cache> &E : unique_ids) {
  281. if (!E.value.saved_to_cache) {
  282. if (f.is_null()) {
  283. f = FileAccess::open(get_cache_file(), FileAccess::READ_WRITE); // Append.
  284. if (f.is_null()) {
  285. return ERR_CANT_OPEN;
  286. }
  287. f->seek_end();
  288. }
  289. f->store_64(uint64_t(E.key));
  290. uint32_t s = E.value.cs.length();
  291. f->store_32(s);
  292. f->store_buffer((const uint8_t *)E.value.cs.ptr(), s);
  293. E.value.saved_to_cache = true;
  294. cache_entries++;
  295. }
  296. }
  297. if (f.is_valid()) {
  298. f->seek(0);
  299. f->store_32(cache_entries); //update amount of entries
  300. }
  301. changed = false;
  302. return OK;
  303. }
  304. String ResourceUID::get_path_from_cache(Ref<FileAccess> &p_cache_file, const String &p_uid_string) {
  305. const int64_t uid_from_string = singleton->text_to_id(p_uid_string);
  306. if (uid_from_string != INVALID_ID) {
  307. const uint32_t entry_count = p_cache_file->get_32();
  308. CharString cs;
  309. for (uint32_t i = 0; i < entry_count; i++) {
  310. int64_t id = p_cache_file->get_64();
  311. int32_t len = p_cache_file->get_32();
  312. cs.resize_uninitialized(len + 1);
  313. ERR_FAIL_COND_V(cs.size() != len + 1, String());
  314. cs[len] = 0;
  315. int32_t rl = p_cache_file->get_buffer((uint8_t *)cs.ptrw(), len);
  316. ERR_FAIL_COND_V(rl != len, String());
  317. if (id == uid_from_string) {
  318. return String::utf8(cs.get_data());
  319. }
  320. }
  321. }
  322. return String();
  323. }
  324. void ResourceUID::clear() {
  325. cache_entries = 0;
  326. if (use_reverse_cache) {
  327. reverse_cache.clear();
  328. }
  329. unique_ids.clear();
  330. changed = false;
  331. }
  332. void ResourceUID::_bind_methods() {
  333. ClassDB::bind_method(D_METHOD("id_to_text", "id"), &ResourceUID::id_to_text);
  334. ClassDB::bind_method(D_METHOD("text_to_id", "text_id"), &ResourceUID::text_to_id);
  335. ClassDB::bind_method(D_METHOD("create_id"), &ResourceUID::create_id);
  336. ClassDB::bind_method(D_METHOD("create_id_for_path", "path"), &ResourceUID::create_id_for_path);
  337. ClassDB::bind_method(D_METHOD("has_id", "id"), &ResourceUID::has_id);
  338. ClassDB::bind_method(D_METHOD("add_id", "id", "path"), &ResourceUID::add_id);
  339. ClassDB::bind_method(D_METHOD("set_id", "id", "path"), &ResourceUID::set_id);
  340. ClassDB::bind_method(D_METHOD("get_id_path", "id"), &ResourceUID::get_id_path);
  341. ClassDB::bind_method(D_METHOD("remove_id", "id"), &ResourceUID::remove_id);
  342. ClassDB::bind_static_method("ResourceUID", D_METHOD("uid_to_path", "uid"), &ResourceUID::uid_to_path);
  343. ClassDB::bind_static_method("ResourceUID", D_METHOD("path_to_uid", "path"), &ResourceUID::path_to_uid);
  344. ClassDB::bind_static_method("ResourceUID", D_METHOD("ensure_path", "path_or_uid"), &ResourceUID::ensure_path);
  345. BIND_CONSTANT(INVALID_ID)
  346. }
  347. ResourceUID *ResourceUID::singleton = nullptr;
  348. ResourceUID::ResourceUID() {
  349. ERR_FAIL_COND(singleton != nullptr);
  350. singleton = this;
  351. }
  352. ResourceUID::~ResourceUID() {
  353. if (crypto != nullptr) {
  354. memdelete((CryptoCore::RandomGenerator *)crypto);
  355. }
  356. }