| 17 | } |
| 18 | |
| 19 | std::string ConstructAssetDirectory(std::string customDirectory) |
| 20 | { |
| 21 | static const int searchDepth = 2; |
| 22 | static const std::string upDir = "../"; |
| 23 | static const std::string testPath = "Scripts/Gameflow.lua"; |
| 24 | |
| 25 | if (!customDirectory.empty()) |
| 26 | { |
| 27 | // Replace all backslashes with forward slashes. |
| 28 | std::replace(customDirectory.begin(), customDirectory.end(), '\\', '/'); |
| 29 | |
| 30 | // Add trailing slash if missing. |
| 31 | if (customDirectory.back() != '/') |
| 32 | customDirectory += '/'; |
| 33 | } |
| 34 | |
| 35 | // Wrap directory depth searching into try-catch block to avoid crashes if we get too |
| 36 | // shallow directory level (e.g. if user have placed executable in a disk root folder). |
| 37 | |
| 38 | try |
| 39 | { |
| 40 | // First, search custom directory, if exists, only then try own (empty) subdirectory. |
| 41 | |
| 42 | for (int useCustomSubdirectory = 1; useCustomSubdirectory >= 0; useCustomSubdirectory--) |
| 43 | { |
| 44 | // Quickly exit if no custom directory specified. |
| 45 | |
| 46 | if (useCustomSubdirectory && customDirectory.empty()) |
| 47 | continue; |
| 48 | |
| 49 | for (int depth = 0; depth < searchDepth + 1; depth++) |
| 50 | { |
| 51 | auto result = useCustomSubdirectory ? customDirectory : std::string{}; |
| 52 | bool isAbsolute = useCustomSubdirectory && std::filesystem::path(result).is_absolute(); |
| 53 | |
| 54 | if (isAbsolute) |
| 55 | { |
| 56 | // Custom directory may be specified as absolute. In such case, it makes no sense |
| 57 | // to search for assets on extra depth levels, since user never would expect that. |
| 58 | |
| 59 | if (depth > 0) |
| 60 | break; |
| 61 | } |
| 62 | else |
| 63 | { |
| 64 | // Add upward directory levels, according to current depth. |
| 65 | |
| 66 | for (int level = 0; level < depth; level++) |
| 67 | result = upDir + result; |
| 68 | } |
| 69 | |
| 70 | // Look if provided test path / file exists in current folder. If it is, |
| 71 | // it means this is a valid asset folder. |
| 72 | |
| 73 | auto testDir = result + (useCustomSubdirectory ? "/" : "") + testPath; |
| 74 | if (std::filesystem::is_regular_file(testDir)) |
| 75 | return result; |
| 76 | } |