assetUtils.cpp 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "assetUtils.h"
  9. #include <AzCore/Component/ComponentApplication.h>
  10. #include <AzCore/Math/Sha1.h>
  11. #include <native/assetprocessor.h>
  12. #include <native/utilities/PlatformConfiguration.h>
  13. #include <native/utilities/StatsCapture.h>
  14. #include <native/AssetManager/FileStateCache.h>
  15. #include <native/AssetDatabase/AssetDatabase.h>
  16. #include <utilities/ThreadHelper.h>
  17. #include <QCoreApplication>
  18. #include <QElapsedTimer>
  19. #include <QTemporaryDir>
  20. #include <QTextStream>
  21. #include <QTimeZone>
  22. #include <QRandomGenerator>
  23. #include <AzQtComponents/Utilities/RandomNumberGenerator.h>
  24. #if defined(__APPLE__)
  25. #include <mach-o/dyld.h>
  26. #include <libgen.h>
  27. #include <unistd.h>
  28. #elif defined(AZ_PLATFORM_LINUX)
  29. #include <libgen.h>
  30. #endif
  31. #include <AzCore/JSON/document.h>
  32. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  33. #include <AzCore/Utils/Utils.h>
  34. #include <AzFramework/API/ApplicationAPI.h>
  35. #include <AzFramework/Platform/PlatformDefaults.h>
  36. #include <AzToolsFramework/UI/Logging/LogLine.h>
  37. #include <xxhash/xxhash.h>
  38. #include <native/utilities/UuidManager.h>
  39. #if defined(AZ_PLATFORM_WINDOWS)
  40. # include <windows.h>
  41. #else
  42. # include <QFile>
  43. #endif
  44. #if defined(AZ_PLATFORM_APPLE) || defined(AZ_PLATFORM_LINUX)
  45. #include <fcntl.h>
  46. #endif
  47. #if defined(AZ_PLATFORM_LINUX)
  48. #include <sys/types.h>
  49. #include <sys/stat.h>
  50. #include <fcntl.h>
  51. #endif // defined(AZ_PLATFORM_LINUX)
  52. #include <sstream>
  53. namespace AssetUtilsInternal
  54. {
  55. static const unsigned int g_RetryWaitInterval = 250; // The amount of time that we are waiting for retry.
  56. // This is because Qt has to init random number gen on each thread.
  57. AZ_THREAD_LOCAL bool g_hasInitializedRandomNumberGenerator = false;
  58. constexpr AZStd::string_view AssetProcessorUserSetregRelPath = "user/Registry/asset_processor.setreg";
  59. // so that even if we do init two seeds at exactly the same msec time, theres still this extra
  60. // changing number
  61. static AZStd::atomic_int g_randomNumberSequentialSeed;
  62. bool FileCopyMoveWithTimeout(QString sourceFile, QString outputFile, bool isCopy, unsigned int waitTimeInSeconds)
  63. {
  64. bool failureOccurredOnce = false; // used for logging.
  65. bool operationSucceeded = false;
  66. QFile outFile(outputFile);
  67. QElapsedTimer timer;
  68. timer.start();
  69. do
  70. {
  71. QString normalized = AssetUtilities::NormalizeFilePath(outputFile);
  72. AssetProcessor::ProcessingJobInfoBus::Broadcast(
  73. &AssetProcessor::ProcessingJobInfoBus::Events::BeginCacheFileUpdate, normalized.toUtf8().constData());
  74. //Removing the old file if it exists
  75. if (outFile.exists())
  76. {
  77. if (!outFile.remove())
  78. {
  79. if (!failureOccurredOnce)
  80. {
  81. // This is not a warning because there is retry logic in place.
  82. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Unable to remove file %s to copy source file %s in... (We may retry)\n", outputFile.toUtf8().constData(), sourceFile.toUtf8().constData());
  83. failureOccurredOnce = true;
  84. }
  85. //not able to remove the file
  86. if (waitTimeInSeconds != 0)
  87. {
  88. //Sleep only for non zero waitTime
  89. QThread::msleep(AssetUtilsInternal::g_RetryWaitInterval);
  90. }
  91. continue;
  92. }
  93. }
  94. //ensure that the output dir is present
  95. QFileInfo outFileInfo(outputFile);
  96. if (!outFileInfo.absoluteDir().mkpath("."))
  97. {
  98. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Failed to create directory (%s).\n", outFileInfo.absolutePath().toUtf8().data());
  99. return false;
  100. }
  101. if (isCopy && QFile::copy(sourceFile, outputFile))
  102. {
  103. //Success
  104. operationSucceeded = true;
  105. break;
  106. }
  107. else if (!isCopy && QFile::rename(sourceFile, outputFile))
  108. {
  109. //Success
  110. operationSucceeded = true;
  111. break;
  112. }
  113. else
  114. {
  115. failureOccurredOnce = true;
  116. if (waitTimeInSeconds != 0)
  117. {
  118. //Sleep only for non zero waitTime
  119. QThread::msleep(AssetUtilsInternal::g_RetryWaitInterval);
  120. }
  121. }
  122. } while (!timer.hasExpired(waitTimeInSeconds * 1000)); //We will keep retrying until the timer has expired the inputted timeout
  123. // once we're done, regardless of success or failure, we 'unlock' those files for further process.
  124. // if we failed, also re-trigger them to rebuild (the bool param at the end of the ebus call)
  125. QString normalized = AssetUtilities::NormalizeFilePath(outputFile);
  126. AssetProcessor::ProcessingJobInfoBus::Broadcast(
  127. &AssetProcessor::ProcessingJobInfoBus::Events::EndCacheFileUpdate, normalized.toUtf8().constData(), !operationSucceeded);
  128. if (!operationSucceeded)
  129. {
  130. //operation failed for the given timeout
  131. AZ_Warning(AssetProcessor::ConsoleChannel, false, "WARNING: Could not %s source from %s to %s, giving up\n",
  132. isCopy ? "copy" : "move (via rename)",
  133. sourceFile.toUtf8().constData(), outputFile.toUtf8().constData());
  134. return false;
  135. }
  136. else if (failureOccurredOnce)
  137. {
  138. // if we failed once, write to log to indicate that we eventually succeeded.
  139. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "SUCCESS: after failure, we later succeeded to copy/move file %s\n", outputFile.toUtf8().constData());
  140. }
  141. return true;
  142. }
  143. static bool DumpAssetProcessorUserSettingsToFile(AZ::SettingsRegistryInterface& settingsRegistry)
  144. {
  145. using namespace AssetUtilities;
  146. AZ::IO::FixedMaxPath setregPath = AZ::Utils::GetProjectPath();
  147. setregPath /= AssetProcessorUserSetregRelPath;
  148. // AssetProcessor saves Bootstrap settings and user settings
  149. constexpr AZStd::string_view BootstrapSettingsKey = AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey;
  150. constexpr AZStd::string_view UserSettingsKey = AssetProcessorUserSettingsRootKey;
  151. auto allowedListKey = AZ::SettingsRegistryInterface::FixedValueString(BootstrapSettingsKey) + "/allowed_list";
  152. auto branchTokenKey = AZ::SettingsRegistryInterface::FixedValueString(BootstrapSettingsKey) + "/assetProcessor_branch_token";
  153. auto generalUserSettingsKey = AZ::SettingsRegistryInterface::FixedValueString(UserSettingsKey);
  154. AZStd::string apSettingsJson;
  155. AZ::IO::ByteContainerStream apSettingsStream(&apSettingsJson);
  156. AZ::SettingsRegistryMergeUtils::DumperSettings apDumperSettings;
  157. apDumperSettings.m_prettifyOutput = true;
  158. AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the
  159. // capture. Newer versions issue unused warning
  160. apDumperSettings.m_includeFilter = [&allowedListKey, &branchTokenKey, &generalUserSettingsKey](AZStd::string_view path)
  161. AZ_POP_DISABLE_WARNING
  162. {
  163. // The objects leading up to the keys to dump must be included in order the keys to be dumped
  164. return allowedListKey.starts_with(path.substr(0, allowedListKey.size())) ||
  165. branchTokenKey.starts_with(path.substr(0, branchTokenKey.size())) ||
  166. generalUserSettingsKey.starts_with(path.substr(0, generalUserSettingsKey.size()));
  167. };
  168. if (AZ::SettingsRegistryMergeUtils::DumpSettingsRegistryToStream(settingsRegistry, "", apSettingsStream, apDumperSettings))
  169. {
  170. constexpr const char* AssetProcessorTmpSetreg = "asset_processor.setreg.tmp";
  171. // Write to a temporary file first before renaming it to the final file location
  172. // This is needed to reduce the potential of a race condition which occurs when other applications attempt to load settings registry
  173. // files from the project's user Registry folder while the AssetProcessor is writing the file out the asset_processor.setreg
  174. // at the same time
  175. QString tempDirValue;
  176. AssetUtilities::CreateTempWorkspace(tempDirValue);
  177. QDir tempDir(tempDirValue);
  178. AZ::IO::FixedMaxPath tmpSetregPath = tempDir.absoluteFilePath(QString(AssetProcessorTmpSetreg)).toUtf8().data();
  179. constexpr auto modeFlags = AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY | AZ::IO::SystemFile::SF_OPEN_CREATE
  180. | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH;
  181. if (AZ::IO::SystemFile apSetregFile; apSetregFile.Open(tmpSetregPath.c_str(), modeFlags))
  182. {
  183. size_t bytesWritten = apSetregFile.Write(apSettingsJson.data(), apSettingsJson.size());
  184. // Close the file so that it can be renamed.
  185. apSetregFile.Close();
  186. if (bytesWritten == apSettingsJson.size())
  187. {
  188. // Create the directory to contain the moved setreg file
  189. AZ::IO::SystemFile::CreateDir(AZ::IO::FixedMaxPath(setregPath.ParentPath()).c_str());
  190. return AZ::IO::SystemFile::Rename(tmpSetregPath.c_str(), setregPath.c_str(), true);
  191. }
  192. }
  193. else
  194. {
  195. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Unable to open AssetProcessor user setreg file (%s)\n", setregPath.c_str());
  196. }
  197. }
  198. else
  199. {
  200. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Dump of AssetProcessor User Settings failed. \n");
  201. }
  202. return false;
  203. }
  204. }
  205. namespace AssetUtilities
  206. {
  207. // do not place Qt objects in global scope, they allocate and refcount threaded data.
  208. AZ::SettingsRegistryInterface::FixedValueString s_projectPath;
  209. AZ::SettingsRegistryInterface::FixedValueString s_projectName;
  210. AZ::SettingsRegistryInterface::FixedValueString s_assetRoot;
  211. AZ::SettingsRegistryInterface::FixedValueString s_cachedEngineRoot;
  212. int s_truncateFingerprintTimestampPrecision{ 1 };
  213. AZStd::optional<bool> s_fileHashOverride{};
  214. AZStd::optional<bool> s_fileHashSetting{};
  215. void SetTruncateFingerprintTimestamp(int precision)
  216. {
  217. s_truncateFingerprintTimestampPrecision = precision;
  218. }
  219. void SetUseFileHashOverride(bool override, bool enable)
  220. {
  221. if(override)
  222. {
  223. s_fileHashOverride = enable ? 1 : 0;
  224. }
  225. else
  226. {
  227. s_fileHashOverride.reset();
  228. }
  229. }
  230. void ResetAssetRoot()
  231. {
  232. s_assetRoot = {};
  233. s_cachedEngineRoot = {};
  234. }
  235. void ResetGameName()
  236. {
  237. s_projectName = {};
  238. }
  239. bool CopyDirectory(QDir source, QDir destination)
  240. {
  241. if (!destination.exists())
  242. {
  243. bool result = destination.mkpath(".");
  244. if (!result)
  245. {
  246. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Failed to create directory (%s).\n", destination.absolutePath().toUtf8().data());
  247. return false;
  248. }
  249. }
  250. QFileInfoList entries = source.entryInfoList(QDir::NoDotAndDotDot | QDir::Files | QDir::Dirs);
  251. for (const QFileInfo& entry : entries)
  252. {
  253. if (entry.isDir())
  254. {
  255. //if the entry is a directory than recursively call the function
  256. if (!CopyDirectory(QDir(source.absolutePath() + "/" + entry.completeBaseName()), QDir(destination.absolutePath() + "/" + entry.completeBaseName())))
  257. {
  258. return false;
  259. }
  260. }
  261. else
  262. {
  263. //if the entry is a file than copy it but before than ensure that the destination file is not present
  264. QString destinationFile = destination.absolutePath() + "/" + entry.fileName();
  265. if (QFile::exists(destinationFile))
  266. {
  267. if (!QFile::remove(destinationFile))
  268. {
  269. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Unable to remove file (%s).\n", destinationFile.toUtf8().data());
  270. return false;
  271. }
  272. }
  273. QString sourceFile = source.absolutePath() + "/" + entry.fileName();
  274. if (!QFile::copy(sourceFile, destinationFile))
  275. {
  276. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Unable to copy sourcefile (%s) to destination (%s).\n", sourceFile.toUtf8().data(), destinationFile.toUtf8().data());
  277. return false;
  278. }
  279. }
  280. }
  281. return true;
  282. }
  283. bool ComputeAssetRoot(QDir& root, const QDir* rootOverride)
  284. {
  285. if (!s_assetRoot.empty())
  286. {
  287. root = QDir(QString::fromUtf8(s_assetRoot.c_str(), aznumeric_cast<int>(s_assetRoot.size())));
  288. return true;
  289. }
  290. // Use the override if supplied and not an empty string
  291. if (rootOverride && !rootOverride->path().isEmpty())
  292. {
  293. root = *rootOverride;
  294. s_assetRoot = root.absolutePath().toUtf8().constData();
  295. return true;
  296. }
  297. const AzFramework::CommandLine* commandLine = nullptr;
  298. AzFramework::ApplicationRequests::Bus::BroadcastResult(commandLine, &AzFramework::ApplicationRequests::GetCommandLine);
  299. static const char AssetRootParam[] = "assetroot";
  300. if (commandLine && commandLine->HasSwitch(AssetRootParam))
  301. {
  302. s_assetRoot = commandLine->GetSwitchValue(AssetRootParam, 0).c_str();
  303. root = QDir(s_assetRoot.c_str());
  304. return true;
  305. }
  306. AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get();
  307. if (settingsRegistry == nullptr)
  308. {
  309. AZ_Warning("AssetProcessor", false, "Unable to retrieve Global SettingsRegistry at this time."
  310. " Has a ComponentApplication(or a class derived from ComponentApplication) been constructed yet?");
  311. return false;
  312. }
  313. AZ::IO::FixedMaxPathString engineRootFolder;
  314. if (settingsRegistry->Get(engineRootFolder, AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder))
  315. {
  316. root = QDir(QString::fromUtf8(engineRootFolder.c_str(), aznumeric_cast<int>(engineRootFolder.size())));
  317. s_assetRoot = root.absolutePath().toUtf8().constData();
  318. return true;
  319. }
  320. // The EngineRootFolder Key has not been found in the SettingsRegistry
  321. auto engineRootError = AZ::SettingsRegistryInterface::FixedValueString::format("The EngineRootFolder is not set in the SettingsRegistry at key %s.",
  322. AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder);
  323. AssetProcessor::MessageInfoBus::Broadcast(&AssetProcessor::MessageInfoBusTraits::OnErrorMessage, engineRootError.c_str());
  324. return false;
  325. }
  326. //! Get the external engine root folder if the engine is external to the current root folder.
  327. //! If the current root folder is also the engine folder, then this behaves the same as ComputeEngineRoot
  328. bool ComputeEngineRoot(QDir& root, const QDir* engineRootOverride)
  329. {
  330. if (!s_cachedEngineRoot.empty())
  331. {
  332. root = QDir(QString::fromUtf8(s_cachedEngineRoot.c_str(), aznumeric_cast<int>(s_cachedEngineRoot.size())));
  333. return true;
  334. }
  335. // Compute the AssetRoot if it is empty as well
  336. if (s_assetRoot.empty())
  337. {
  338. AssetUtilities::ComputeAssetRoot(root, engineRootOverride);
  339. }
  340. AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get();
  341. // Use the engineRootOverride if supplied and not empty
  342. if (engineRootOverride && !engineRootOverride->path().isEmpty())
  343. {
  344. root = *engineRootOverride;
  345. s_cachedEngineRoot = root.absolutePath().toUtf8().constData();
  346. return true;
  347. }
  348. if (settingsRegistry == nullptr)
  349. {
  350. return false;
  351. }
  352. AZ::IO::FixedMaxPathString engineRootFolder;
  353. if (settingsRegistry->Get(engineRootFolder, AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder))
  354. {
  355. root = QDir(QString::fromUtf8(engineRootFolder.c_str(), aznumeric_cast<int>(engineRootFolder.size())));
  356. s_cachedEngineRoot = root.absolutePath().toUtf8().constData();
  357. return true;
  358. }
  359. return false;
  360. }
  361. bool MakeFileWritable(const QString& fileName)
  362. {
  363. #if defined WIN32
  364. DWORD fileAttributes = GetFileAttributesA(fileName.toUtf8());
  365. if (fileAttributes == INVALID_FILE_ATTRIBUTES)
  366. {
  367. //file does not exist
  368. return false;
  369. }
  370. if ((fileAttributes & FILE_ATTRIBUTE_READONLY))
  371. {
  372. fileAttributes = fileAttributes & ~(FILE_ATTRIBUTE_READONLY);
  373. if (SetFileAttributesA(fileName.toUtf8(), fileAttributes))
  374. {
  375. return true;
  376. }
  377. return false;
  378. }
  379. else
  380. {
  381. //file is writeable
  382. return true;
  383. }
  384. #else
  385. QFileInfo fileInfo(fileName);
  386. if (!fileInfo.exists())
  387. {
  388. return false;
  389. }
  390. if (fileInfo.permission(QFile::WriteUser))
  391. {
  392. // file already has the write permission
  393. return true;
  394. }
  395. else
  396. {
  397. QFile::Permissions filePermissions = fileInfo.permissions();
  398. if (QFile::setPermissions(fileName, filePermissions | QFile::WriteUser))
  399. {
  400. //write permission added
  401. return true;
  402. }
  403. return false;
  404. }
  405. #endif
  406. }
  407. bool CheckCanLock(const QString& fileName)
  408. {
  409. #if defined(AZ_PLATFORM_WINDOWS)
  410. AZStd::wstring usableFileName;
  411. usableFileName.resize(fileName.length(), 0);
  412. fileName.toWCharArray(usableFileName.data());
  413. // third parameter dwShareMode (0) prevents share access
  414. const DWORD dwShareMode = 0;
  415. HANDLE fileHandle = CreateFileW(usableFileName.c_str(), GENERIC_READ, dwShareMode, nullptr, OPEN_EXISTING, 0, 0);
  416. if (fileHandle != INVALID_HANDLE_VALUE)
  417. {
  418. CloseHandle(fileHandle);
  419. return true;
  420. }
  421. return false;
  422. #else
  423. int open_flags = O_RDONLY | O_NONBLOCK;
  424. #if defined(PLATFORM_APPLE)
  425. // O_EXLOCK only supported on APPLE
  426. open_flags |= O_EXLOCK
  427. #endif
  428. int handle = open(fileName.toUtf8().constData(), open_flags);
  429. if (handle != -1)
  430. {
  431. close(handle);
  432. return true;
  433. }
  434. return false;
  435. #endif
  436. }
  437. QString ComputeProjectName(QString gameNameOverride, bool force)
  438. {
  439. if (force || s_projectName.empty())
  440. {
  441. // Override Game Name if a non-empty override string has been supplied
  442. if (!gameNameOverride.isEmpty())
  443. {
  444. s_projectName = gameNameOverride.toUtf8().constData();
  445. }
  446. else
  447. {
  448. s_projectName = AZ::Utils::GetProjectName();
  449. }
  450. }
  451. return QString::fromUtf8(s_projectName.c_str(), aznumeric_cast<int>(s_projectName.size()));
  452. }
  453. QString ComputeProjectPath(bool resetCachedProjectPath/*=false*/)
  454. {
  455. if (resetCachedProjectPath)
  456. {
  457. // Clear any cached value if reset was requested
  458. s_projectPath.clear();
  459. }
  460. if (s_projectPath.empty())
  461. {
  462. // Check command-line args first
  463. QStringList args = QCoreApplication::arguments();
  464. for (QString arg : args)
  465. {
  466. if (arg.contains(QString("/%1=").arg(ProjectPathOverrideParameter), Qt::CaseInsensitive)
  467. || arg.contains(QString("--%1=").arg(ProjectPathOverrideParameter), Qt::CaseInsensitive))
  468. {
  469. QString rawValueString = arg.split("=")[1].trimmed();
  470. if (!rawValueString.isEmpty())
  471. {
  472. QDir path(rawValueString);
  473. if (path.isAbsolute())
  474. {
  475. s_projectPath = rawValueString.toUtf8().constData();
  476. break;
  477. }
  478. }
  479. }
  480. }
  481. }
  482. if (s_projectPath.empty())
  483. {
  484. s_projectPath = AZ::Utils::GetProjectPath();
  485. }
  486. return QString::fromUtf8(s_projectPath.c_str(), aznumeric_cast<int>(s_projectPath.size()));
  487. }
  488. bool ShouldUseFileHashing()
  489. {
  490. // Check if the settings file is overridden, if so, use the override instead
  491. if(s_fileHashOverride)
  492. {
  493. return *s_fileHashOverride;
  494. }
  495. // Check if we read the settings file already, if so, use the cached value
  496. if(s_fileHashSetting)
  497. {
  498. return *s_fileHashSetting;
  499. }
  500. auto settingsRegistry = AZ::SettingsRegistry::Get();
  501. if (settingsRegistry)
  502. {
  503. bool curValue = true;
  504. settingsRegistry->Get(curValue, AZ::SettingsRegistryInterface::FixedValueString(AssetProcessor::AssetProcessorSettingsKey)
  505. + "/Fingerprinting/UseFileHashing");
  506. AZ_TracePrintf(AssetProcessor::DebugChannel, "UseFileHashing: %s\n", curValue ? "True" : "False");
  507. s_fileHashSetting = curValue;
  508. return curValue;
  509. }
  510. AZ_TracePrintf(AssetProcessor::DebugChannel, "No UseFileHashing setting found\n");
  511. s_fileHashSetting = true;
  512. return *s_fileHashSetting;
  513. }
  514. QString ReadAllowedlistFromSettingsRegistry([[maybe_unused]] QString initialFolder)
  515. {
  516. AZ::SettingsRegistryInterface::FixedValueString allowedListKey{ AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey };
  517. allowedListKey += "/allowed_list";
  518. AZ::SettingsRegistryInterface::FixedValueString allowedListIp;
  519. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry && settingsRegistry->Get(allowedListIp, allowedListKey))
  520. {
  521. return QString::fromUtf8(allowedListIp.c_str(), aznumeric_cast<int>(allowedListIp.size()));
  522. }
  523. return {};
  524. }
  525. QString ReadRemoteIpFromSettingsRegistry([[maybe_unused]] QString initialFolder)
  526. {
  527. AZ::SettingsRegistryInterface::FixedValueString remoteIpKey{ AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey };
  528. remoteIpKey += "/remote_ip";
  529. AZ::SettingsRegistryInterface::FixedValueString remoteIp;
  530. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry && settingsRegistry->Get(remoteIp, remoteIpKey))
  531. {
  532. return QString::fromUtf8(remoteIp.c_str(), aznumeric_cast<int>(remoteIp.size()));
  533. }
  534. return {};
  535. }
  536. bool WriteAllowedlistToSettingsRegistry(const QStringList& newAllowedList)
  537. {
  538. auto settingsRegistry = AZ::SettingsRegistry::Get();
  539. if (!settingsRegistry)
  540. {
  541. AZ_Error(AssetProcessor::ConsoleChannel, false, "Unable access Settings Registry. Branch Token cannot be updated");
  542. return false;
  543. }
  544. auto allowedListKey = AZ::SettingsRegistryInterface::FixedValueString(AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey)
  545. + "/allowed_list";
  546. AZStd::string currentAllowedList;
  547. if (settingsRegistry->Get(currentAllowedList, allowedListKey))
  548. {
  549. // Split the current allowedList into an array and compare against the new allowed list
  550. AZStd::vector<AZStd::string_view> allowedListArray;
  551. auto AppendAllowedIpTokens = [&allowedListArray](AZStd::string_view token) { allowedListArray.emplace_back(token); };
  552. AZ::StringFunc::TokenizeVisitor(currentAllowedList, AppendAllowedIpTokens, ',');
  553. auto CompareQListToAzVector = [](AZStd::string_view currentAllowedIp, const QString& newAllowedIp)
  554. {
  555. return currentAllowedIp == newAllowedIp.toUtf8().constData();
  556. };
  557. if (AZStd::equal(allowedListArray.begin(), allowedListArray.end(), newAllowedList.begin(), newAllowedList.end(), CompareQListToAzVector))
  558. {
  559. // no need to update, remote_ip already matches
  560. return true;
  561. }
  562. }
  563. // Update Settings Registry with new token
  564. AZStd::string azNewAllowedList{ newAllowedList.join(',').toUtf8().constData() };
  565. settingsRegistry->Set(allowedListKey, azNewAllowedList);
  566. return AssetUtilsInternal::DumpAssetProcessorUserSettingsToFile(*settingsRegistry);
  567. }
  568. quint16 ReadListeningPortFromSettingsRegistry(QString initialFolder /*= QString()*/)
  569. {
  570. if (initialFolder.isEmpty())
  571. {
  572. QDir engineRoot;
  573. if (!AssetUtilities::ComputeEngineRoot(engineRoot))
  574. {
  575. //return the default port
  576. return 45643;
  577. }
  578. initialFolder = engineRoot.absolutePath();
  579. }
  580. AZ::SettingsRegistryInterface::FixedValueString remotePortKey{ AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey };
  581. remotePortKey += "/remote_port";
  582. AZ::s64 portNumber;
  583. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry && settingsRegistry->Get(portNumber, remotePortKey))
  584. {
  585. return aznumeric_cast<quint16>(portNumber);
  586. }
  587. //return the default port
  588. return 45643;
  589. }
  590. QStringList ReadPlatformsFromCommandLine()
  591. {
  592. QStringList args = QCoreApplication::arguments();
  593. for (QString arg : args)
  594. {
  595. if (arg.contains("--platforms=", Qt::CaseInsensitive) || arg.contains("/platforms=", Qt::CaseInsensitive))
  596. {
  597. QString rawPlatformString = arg.split("=")[1];
  598. return rawPlatformString.split(",");
  599. }
  600. }
  601. return QStringList();
  602. }
  603. bool CopyFileWithTimeout(QString sourceFile, QString outputFile, unsigned int waitTimeInSeconds)
  604. {
  605. return AssetUtilsInternal::FileCopyMoveWithTimeout(sourceFile, outputFile, true, waitTimeInSeconds);
  606. }
  607. bool MoveFileWithTimeout(QString sourceFile, QString outputFile, unsigned int waitTimeInSeconds)
  608. {
  609. return AssetUtilsInternal::FileCopyMoveWithTimeout(sourceFile, outputFile, false, waitTimeInSeconds);
  610. }
  611. bool CreateDirectoryWithTimeout(QDir dir, unsigned int waitTimeinSeconds)
  612. {
  613. if (dir.exists())
  614. {
  615. return true;
  616. }
  617. [[maybe_unused]] int retries = 0;
  618. QElapsedTimer timer;
  619. timer.start();
  620. do
  621. {
  622. retries++;
  623. // Try to create the directory path
  624. if (dir.mkpath("."))
  625. {
  626. return true;
  627. }
  628. else
  629. {
  630. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Unable to create output directory path: %s retrying.\n", dir.absolutePath().toUtf8().data());
  631. }
  632. if (dir.exists())
  633. {
  634. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Output directory: %s created by another operation.\n", dir.absolutePath().toUtf8().data());
  635. return true;
  636. }
  637. if (waitTimeinSeconds != 0)
  638. {
  639. QThread::msleep(AssetUtilsInternal::g_RetryWaitInterval);
  640. }
  641. } while (!timer.hasExpired(waitTimeinSeconds * 1000));
  642. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Failed to create output directory: %s after %d retries.\n", dir.absolutePath().toUtf8().data(), retries);
  643. return false;
  644. }
  645. QString NormalizeAndRemoveAlias(QString path)
  646. {
  647. QString normalizedPath = NormalizeFilePath(path);
  648. if (normalizedPath.startsWith("@"))
  649. {
  650. int aliasEndIndex = normalizedPath.indexOf("@/", Qt::CaseInsensitive);
  651. if (aliasEndIndex != -1)
  652. {
  653. normalizedPath.remove(0, aliasEndIndex + 2);// adding two to remove both the percentage sign and the native separator
  654. }
  655. else
  656. {
  657. //try finding the second % index than,maybe the path is like @SomeAlias@somefolder/somefile.ext
  658. aliasEndIndex = normalizedPath.indexOf("@", 1, Qt::CaseInsensitive);
  659. if (aliasEndIndex != -1)
  660. {
  661. normalizedPath.remove(0, aliasEndIndex + 1); //adding one to remove the percentage sign only
  662. }
  663. }
  664. }
  665. return normalizedPath;
  666. }
  667. bool ComputeProjectCacheRoot(QDir& projectCacheRoot)
  668. {
  669. if (auto registry = AZ::SettingsRegistry::Get(); registry != nullptr)
  670. {
  671. AZ::SettingsRegistryInterface::FixedValueString projectCacheRootValue;
  672. if (registry->Get(projectCacheRootValue, AZ::SettingsRegistryMergeUtils::FilePathKey_CacheProjectRootFolder);
  673. !projectCacheRootValue.empty())
  674. {
  675. projectCacheRoot = QDir(QString::fromUtf8(projectCacheRootValue.c_str(), aznumeric_cast<int>(projectCacheRootValue.size())));
  676. return true;
  677. }
  678. }
  679. return false;
  680. }
  681. bool ComputeFenceDirectory(QDir& fenceDir)
  682. {
  683. QDir cacheRoot;
  684. if (!AssetUtilities::ComputeProjectCacheRoot(cacheRoot))
  685. {
  686. return false;
  687. }
  688. fenceDir = QDir(cacheRoot.filePath("fence"));
  689. return true;
  690. }
  691. AZStd::string_view StripAssetPlatformNoCopy(AZStd::string_view relativeProductPath, AZStd::string_view* outputPlatform)
  692. {
  693. // Skip over the assetPlatform path segment if it is matches one of the platform defaults
  694. // Otherwise return the path unchanged
  695. AZStd::string_view originalPath = relativeProductPath;
  696. AZStd::optional firstPathSegment = AZ::StringFunc::TokenizeNext(relativeProductPath, AZ_CORRECT_AND_WRONG_FILESYSTEM_SEPARATOR);
  697. if (firstPathSegment && (AzFramework::PlatformHelper::GetPlatformIdFromName(*firstPathSegment) != AzFramework::PlatformId::Invalid
  698. || firstPathSegment == AssetBuilderSDK::CommonPlatformName))
  699. {
  700. if(outputPlatform)
  701. {
  702. *outputPlatform = *firstPathSegment;
  703. }
  704. return relativeProductPath;
  705. }
  706. return originalPath;
  707. }
  708. QString StripAssetPlatform(AZStd::string_view relativeProductPath)
  709. {
  710. AZStd::string_view result = StripAssetPlatformNoCopy(relativeProductPath);
  711. return QString::fromUtf8(result.data(), aznumeric_cast<int>(result.size()));
  712. }
  713. QString NormalizeFilePath(const QString& filePath)
  714. {
  715. // do NOT convert to absolute paths here, we just want to manipulate the string itself.
  716. QString returnString = filePath;
  717. // QDir::cleanPath only replaces backslashes with forward slashes in the input string if the OS
  718. // it is currently natively running on uses backslashes as its native path separator.
  719. // see https://github.com/qt/qtbase/blob/40143c189b7c1bf3c2058b77d00ea5c4e3be8b28/src/corelib/io/qdir.cpp#L2357
  720. // This assumption is incorrect in this application - it can receive file paths from data files created on
  721. // backslash operating systems even if its a non-backslash operating system.
  722. // we can skip this step in the cases where cleanPath will do it for us:
  723. if (QDir::separator() == QLatin1Char('/'))
  724. {
  725. returnString.replace(QLatin1Char('\\'), QLatin1Char('/'));
  726. }
  727. // cleanPath to remove/resolve .. and . and any extra slashes, and remove any trailing slashes.
  728. returnString = QDir::cleanPath(returnString);
  729. #if defined(AZ_PLATFORM_WINDOWS)
  730. // windows has an additional idiosyncrasy - it returns upper and lower case drive letters
  731. // from various APIs differently. we will settle on upper case as the standard.
  732. if ((returnString.length() > 1) && (returnString.at(1) == ':'))
  733. {
  734. QCharRef firstChar = returnString[0]; // QCharRef allows you to modify the string in place.
  735. firstChar = firstChar.toUpper();
  736. }
  737. #endif
  738. return returnString;
  739. }
  740. QString NormalizeDirectoryPath(const QString& directoryPath)
  741. {
  742. QString dirPath(NormalizeFilePath(directoryPath));
  743. while ((dirPath.endsWith('/')))
  744. {
  745. dirPath.resize(dirPath.length() - 1);
  746. }
  747. return dirPath;
  748. }
  749. AZ::Uuid CreateSafeSourceUUIDFromName(const char* sourceName, bool caseInsensitive)
  750. {
  751. AZStd::string lowerVersion(sourceName);
  752. if (caseInsensitive)
  753. {
  754. AZStd::to_lower(lowerVersion.begin(), lowerVersion.end());
  755. }
  756. AzFramework::StringFunc::Replace(lowerVersion, '\\', '/');
  757. return AZ::Uuid::CreateName(lowerVersion.c_str());
  758. }
  759. AZ::Outcome<AZ::Uuid, AZStd::string> GetSourceUuid(const AssetProcessor::SourceAssetReference& sourceAsset)
  760. {
  761. if (!sourceAsset)
  762. {
  763. return {};
  764. }
  765. auto* uuidRequests = AZ::Interface<AssetProcessor::IUuidRequests>::Get();
  766. if (uuidRequests)
  767. {
  768. return uuidRequests->GetUuid(sourceAsset);
  769. }
  770. AZ_Assert(false, "Programmer Error: GetSourceUuid called before IUuidRequests interface is available.");
  771. return {};
  772. }
  773. AZ::Outcome<AZStd::unordered_set<AZ::Uuid>, AZStd::string> GetLegacySourceUuids(const AssetProcessor::SourceAssetReference& sourceAsset)
  774. {
  775. auto* uuidRequests = AZ::Interface<AssetProcessor::IUuidRequests>::Get();
  776. if (uuidRequests)
  777. {
  778. return uuidRequests->GetLegacyUuids(sourceAsset);
  779. }
  780. AZ_Assert(false, "Programmer Error: GetSourceUuid called before IUuidRequests interface is available.");
  781. return {};
  782. }
  783. void NormalizeFilePaths(QStringList& filePaths)
  784. {
  785. for (int pathIdx = 0; pathIdx < filePaths.size(); ++pathIdx)
  786. {
  787. filePaths[pathIdx] = NormalizeFilePath(filePaths[pathIdx]);
  788. }
  789. }
  790. unsigned int ComputeCRC32(const char* inString, unsigned int priorCRC)
  791. {
  792. AZ::Crc32 crc(priorCRC != -1 ? priorCRC : 0U);
  793. crc.Add(inString, ::strlen(inString), false);
  794. return crc;
  795. }
  796. unsigned int ComputeCRC32(const char* data, size_t dataSize, unsigned int priorCRC)
  797. {
  798. AZ::Crc32 crc(priorCRC != -1 ? priorCRC : 0U);
  799. crc.Add(data, dataSize, false);
  800. return crc;
  801. }
  802. unsigned int ComputeCRC32Lowercase(const char* inString, unsigned int priorCRC)
  803. {
  804. AZ::Crc32 crc(priorCRC != -1 ? priorCRC : 0U);
  805. crc.Add(inString); // note that the char* version of Add() sets lowercase to be true by default.
  806. return crc;
  807. }
  808. unsigned int ComputeCRC32Lowercase(const char* data, size_t dataSize, unsigned int priorCRC)
  809. {
  810. AZ::Crc32 crc(priorCRC != -1 ? priorCRC : 0U);
  811. crc.Add(data, dataSize, true);
  812. return crc;
  813. }
  814. bool UpdateBranchToken()
  815. {
  816. AZStd::string appBranchToken;
  817. AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::CalculateBranchTokenForEngineRoot, appBranchToken);
  818. auto settingsRegistry = AZ::SettingsRegistry::Get();
  819. if (!settingsRegistry)
  820. {
  821. AZ_Error(AssetProcessor::ConsoleChannel, false, "Unable access Settings Registry. Branch Token cannot be updated");
  822. return false;
  823. }
  824. AZStd::string registryBranchToken;
  825. auto branchTokenKey = AZ::SettingsRegistryInterface::FixedValueString(AZ::SettingsRegistryMergeUtils::BootstrapSettingsRootKey) + "/assetProcessor_branch_token";
  826. if (settingsRegistry->Get(registryBranchToken, branchTokenKey))
  827. {
  828. if (appBranchToken == registryBranchToken)
  829. {
  830. // no need to update, branch token match
  831. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Branch token (%s) is already correct, not updating\n", appBranchToken.c_str());
  832. return true;
  833. }
  834. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Updating branch token (%s)\n", appBranchToken.c_str());
  835. }
  836. else
  837. {
  838. AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Adding branch token (%s)\n", appBranchToken.c_str());
  839. }
  840. // Update Settings Registry with new token
  841. settingsRegistry->Set(branchTokenKey, appBranchToken);
  842. return AssetUtilsInternal::DumpAssetProcessorUserSettingsToFile(*settingsRegistry);
  843. }
  844. QString ComputeJobDescription(const AssetProcessor::AssetRecognizer* recognizer)
  845. {
  846. QString jobDescription{ recognizer->m_name.c_str() };
  847. return jobDescription.toLower();
  848. }
  849. AZStd::string ComputeJobLogFolder()
  850. {
  851. return AZStd::string::format("@log@/JobLogs");
  852. }
  853. AZStd::string ComputeJobLogFileName(const AzToolsFramework::AssetSystem::JobInfo& jobInfo)
  854. {
  855. return AZStd::string::format("%s-%u-%llu.log", jobInfo.m_sourceFile.c_str(), jobInfo.GetHash(), jobInfo.m_jobRunKey);
  856. }
  857. AZStd::string ComputeJobLogFileName(const AssetBuilderSDK::CreateJobsRequest& createJobsRequest)
  858. {
  859. return AZStd::string::format("%s-%s_createJobs.log", createJobsRequest.m_sourceFile.c_str(), createJobsRequest.m_builderid.ToString<AZStd::string>(false).c_str());
  860. }
  861. ReadJobLogResult ReadJobLog(AzToolsFramework::AssetSystem::JobInfo& jobInfo, AzToolsFramework::AssetSystem::AssetJobLogResponse& response)
  862. {
  863. AZStd::string logFile = AssetUtilities::ComputeJobLogFolder() + "/" + AssetUtilities::ComputeJobLogFileName(jobInfo);
  864. return ReadJobLog(logFile.c_str(), response);
  865. }
  866. ReadJobLogResult ReadJobLog(const char* absolutePath, AzToolsFramework::AssetSystem::AssetJobLogResponse& response)
  867. {
  868. response.m_isSuccess = false;
  869. AZ::IO::HandleType handle = AZ::IO::InvalidHandle;
  870. AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance();
  871. if (!fileIO)
  872. {
  873. AZ_TracePrintf("AssetProcessorManager", "Error: AssetProcessorManager: FileIO is unavailable\n", absolutePath);
  874. response.m_jobLog = "FileIO is unavailable";
  875. response.m_isSuccess = false;
  876. return ReadJobLogResult::MissingFileIO;
  877. }
  878. if (!fileIO->Open(absolutePath, AZ::IO::OpenMode::ModeRead | AZ::IO::OpenMode::ModeBinary, handle))
  879. {
  880. AZ_TracePrintf("AssetProcessorManager", "Error: AssetProcessorManager: Failed to find the log file %s for a request.\n", absolutePath);
  881. response.m_jobLog.append(AZStd::string::format("Error: No log file found for the given log (%s)", absolutePath).c_str());
  882. response.m_isSuccess = false;
  883. return ReadJobLogResult::MissingLogFile;
  884. }
  885. AZ::u64 actualSize = 0;
  886. fileIO->Size(handle, actualSize);
  887. if (actualSize == 0)
  888. {
  889. AZ_TracePrintf("AssetProcessorManager", "Error: AssetProcessorManager: Log File %s is empty.\n", absolutePath);
  890. response.m_jobLog.append(AZStd::string::format("Error: Log is empty (%s)", absolutePath).c_str());
  891. response.m_isSuccess = false;
  892. fileIO->Close(handle);
  893. return ReadJobLogResult::EmptyLogFile;
  894. }
  895. size_t currentResponseSize = response.m_jobLog.size();
  896. response.m_jobLog.resize(currentResponseSize + actualSize);
  897. fileIO->Read(handle, response.m_jobLog.data() + currentResponseSize, actualSize);
  898. fileIO->Close(handle);
  899. response.m_isSuccess = true;
  900. return ReadJobLogResult::Success;
  901. }
  902. template<typename T>
  903. bool SetUserSetting(const char* settingName, T value)
  904. {
  905. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  906. {
  907. constexpr AZStd::string_view UserSettingsKey = AssetProcessorUserSettingsRootKey;
  908. auto settingKey = AZ::SettingsRegistryInterface::FixedValueString(UserSettingsKey) + "/" + settingName;
  909. bool wasSet = settingsRegistry->Set(settingKey, value);
  910. if (wasSet)
  911. {
  912. AssetProcessorUserSettingsNotificationBus::Broadcast(&AssetProcessorUserSettingsNotificationBus::Events::OnSettingChanged, settingName);
  913. return AssetUtilsInternal::DumpAssetProcessorUserSettingsToFile(*settingsRegistry);
  914. }
  915. }
  916. return false;
  917. }
  918. template<typename T>
  919. T GetUserSetting(const char* settingName, T defaultValue)
  920. {
  921. T resultValue = defaultValue;
  922. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  923. {
  924. constexpr AZStd::string_view UserSettingsKey = AssetProcessorUserSettingsRootKey;
  925. auto settingKey = AZ::SettingsRegistryInterface::FixedValueString(UserSettingsKey) + "/" + settingName;
  926. settingsRegistry->Get(resultValue, settingKey);
  927. }
  928. return resultValue;
  929. }
  930. bool SaveSettingsFile()
  931. {
  932. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  933. {
  934. return AssetUtilsInternal::DumpAssetProcessorUserSettingsToFile(*settingsRegistry);
  935. }
  936. return false;
  937. }
  938. // we implement these for the types the settings registry allows
  939. template bool SetUserSetting<bool>(const char* settingName, bool value);
  940. template bool GetUserSetting<bool>(const char* settingName, bool defaultValue);
  941. template bool SetUserSetting<AZ::s64>(const char* settingName, AZ::s64 value);
  942. template AZ::s64 GetUserSetting<AZ::s64>(const char* settingName, AZ::s64 defaultValue);
  943. template bool SetUserSetting<AZ::u64>(const char* settingName, AZ::u64 value);
  944. template AZ::u64 GetUserSetting<AZ::u64>(const char* settingName, AZ::u64 defaultValue);
  945. template bool SetUserSetting<double>(const char* settingName, double value);
  946. template double GetUserSetting<double>(const char* settingName, double defaultValue);
  947. template bool SetUserSetting<AZStd::string>(const char* settingName, AZStd::string value);
  948. template AZStd::string GetUserSetting<AZStd::string>(const char* settingName, AZStd::string defaultValue);
  949. unsigned int GenerateFingerprint(const AssetProcessor::JobDetails& jobDetail)
  950. {
  951. // it is assumed that m_fingerprintFilesList contains the original file and all dependencies, and is in a stable order without duplicates
  952. // CRC32 is not an effective hash for this purpose, so we will build a string and then use SHA1 on it.
  953. // to avoid resizing and copying repeatedly we will keep track of the largest reserved capacity ever needed for this function, and reserve that much data
  954. static size_t s_largestFingerprintCapacitySoFar = 1;
  955. AZStd::string fingerprintString;
  956. fingerprintString.reserve(s_largestFingerprintCapacitySoFar);
  957. // in general, we'll build a string which is:
  958. // (version):[Array of individual file fingerprints][Array of individual job fingerprints]
  959. // with each element of the arrays seperated by colons.
  960. fingerprintString.append(jobDetail.m_extraInformationForFingerprinting);
  961. for (const auto& fingerprintFile : jobDetail.m_fingerprintFiles)
  962. {
  963. fingerprintString.append(":");
  964. fingerprintString.append(GetFileFingerprint(fingerprintFile.first, fingerprintFile.second));
  965. }
  966. // now the other jobs, which this job depends on:
  967. for (const AssetProcessor::JobDependencyInternal& jobDependencyInternal : jobDetail.m_jobDependencyList)
  968. {
  969. if (jobDependencyInternal.m_jobDependency.m_type == AssetBuilderSDK::JobDependencyType::OrderOnce ||
  970. jobDependencyInternal.m_jobDependency.m_type == AssetBuilderSDK::JobDependencyType::OrderOnly)
  971. {
  972. // We do not want to include the fingerprint of dependent jobs if the job dependency type is OrderOnce or OrderOnly.
  973. continue;
  974. }
  975. AssetProcessor::JobDesc jobDesc(AssetProcessor::SourceAssetReference(jobDependencyInternal.m_jobDependency.m_sourceFile.m_sourceFileDependencyPath.c_str()),
  976. jobDependencyInternal.m_jobDependency.m_jobKey, jobDependencyInternal.m_jobDependency.m_platformIdentifier);
  977. for (auto builderIter = jobDependencyInternal.m_builderUuidList.begin(); builderIter != jobDependencyInternal.m_builderUuidList.end(); ++builderIter)
  978. {
  979. AZ::u32 dependentJobFingerprint;
  980. AssetProcessor::ProcessingJobInfoBus::BroadcastResult(dependentJobFingerprint, &AssetProcessor::ProcessingJobInfoBusTraits::GetJobFingerprint, AssetProcessor::JobIndentifier(jobDesc, *builderIter));
  981. if (dependentJobFingerprint != 0)
  982. {
  983. fingerprintString.append(AZStd::string::format(":%u", dependentJobFingerprint));
  984. }
  985. }
  986. }
  987. s_largestFingerprintCapacitySoFar = AZStd::GetMax(fingerprintString.capacity(), s_largestFingerprintCapacitySoFar);
  988. if (fingerprintString.empty())
  989. {
  990. AZ_Assert(false, "GenerateFingerprint was called but no input files were requested for fingerprinting.");
  991. return 0;
  992. }
  993. AZ::Sha1 sha;
  994. sha.ProcessBytes(AZStd::as_bytes(AZStd::span(fingerprintString)));
  995. AZ::u32 digest[5];
  996. sha.GetDigest(digest);
  997. return digest[0]; // we only currently use 32-bit hashes. This could be extended if collisions still occur.
  998. }
  999. std::uint64_t AdjustTimestamp(QDateTime timestamp, int overridePrecision)
  1000. {
  1001. if (timestamp.isDaylightTime())
  1002. {
  1003. int offsetTimeinSecs = timestamp.timeZone().daylightTimeOffset(timestamp);
  1004. timestamp = timestamp.addSecs(-1 * offsetTimeinSecs);
  1005. }
  1006. timestamp = timestamp.toUTC();
  1007. auto timeMilliseconds = timestamp.toMSecsSinceEpoch();
  1008. int checkPrecision = (overridePrecision ? overridePrecision : s_truncateFingerprintTimestampPrecision);
  1009. // Reduce the precision from milliseconds to the specified precision (default is 1, so no change)
  1010. timeMilliseconds /= checkPrecision;
  1011. timeMilliseconds *= checkPrecision;
  1012. return timeMilliseconds;
  1013. }
  1014. AZ::u64 GetFileHash(const char* filePath, bool force, AZ::IO::SizeType* bytesReadOut, int hashMsDelay)
  1015. {
  1016. #ifndef AZ_TESTS_ENABLED
  1017. // Only used for unit tests, speed is critical for GetFileHash.
  1018. hashMsDelay = 0;
  1019. #endif
  1020. bool useFileHashing = ShouldUseFileHashing();
  1021. if(!useFileHashing || !filePath)
  1022. {
  1023. return 0;
  1024. }
  1025. AZ::u64 hash = 0;
  1026. if(!force)
  1027. {
  1028. auto* fileStateInterface = AZ::Interface<AssetProcessor::IFileStateRequests>::Get();
  1029. if (fileStateInterface && fileStateInterface->GetHash(filePath, &hash))
  1030. {
  1031. return hash;
  1032. }
  1033. }
  1034. // keep track of how much time we spend actually hashing files.
  1035. AZStd::string statName = AZStd::string::format("HashFile,%s", filePath);
  1036. AssetProcessor::StatsCapture::BeginCaptureStat(statName.c_str());
  1037. hash = AssetBuilderSDK::GetFileHash(filePath, bytesReadOut, hashMsDelay);
  1038. AssetProcessor::StatsCapture::EndCaptureStat(statName.c_str());
  1039. return hash;
  1040. }
  1041. AZ::u64 AdjustTimestamp(QDateTime timestamp)
  1042. {
  1043. timestamp = timestamp.toUTC();
  1044. auto timeMilliseconds = timestamp.toMSecsSinceEpoch();
  1045. // Reduce the precision from milliseconds to the specified precision (default is 1, so no change)
  1046. timeMilliseconds /= s_truncateFingerprintTimestampPrecision;
  1047. timeMilliseconds *= s_truncateFingerprintTimestampPrecision;
  1048. return timeMilliseconds;
  1049. }
  1050. AZStd::string GetFileFingerprint(const AZStd::string& absolutePath, const AZStd::string& nameToUse)
  1051. {
  1052. bool fileFound = false;
  1053. AssetProcessor::FileStateInfo fileStateInfo;
  1054. auto* fileStateInterface = AZ::Interface<AssetProcessor::IFileStateRequests>::Get();
  1055. if (fileStateInterface)
  1056. {
  1057. fileFound = fileStateInterface->GetFileInfo(QString::fromUtf8(absolutePath.c_str()), &fileStateInfo);
  1058. }
  1059. QDateTime lastModifiedTime = fileStateInfo.m_modTime;
  1060. if (!fileFound || !lastModifiedTime.isValid())
  1061. {
  1062. // we still use the name here so that when missing files change, it still counts as a change.
  1063. // we also don't use '0' as the placeholder, so that there is a difference between files that do not exist
  1064. // and files which have 0 bytes size.
  1065. return AZStd::string::format("-:-:%s", nameToUse.c_str());
  1066. }
  1067. else
  1068. {
  1069. bool useHash = ShouldUseFileHashing();
  1070. AZ::u64 fileIdentifier;
  1071. if(useHash)
  1072. {
  1073. fileIdentifier = GetFileHash(absolutePath.c_str());
  1074. }
  1075. else
  1076. {
  1077. fileIdentifier = AdjustTimestamp(lastModifiedTime);
  1078. }
  1079. // its possible that the dependency has moved to a different file with the same modtime/hash
  1080. // so we add the size of it too.
  1081. // its also possible that it moved to a different file with the same modtime/hash AND size,
  1082. // but with a different name. So we add that too.
  1083. return AZStd::string::format("%llX:%llu:%s", fileIdentifier, fileStateInfo.m_fileSize, nameToUse.c_str());
  1084. }
  1085. }
  1086. AZStd::string ComputeJobLogFileName(const AssetProcessor::JobEntry& jobEntry)
  1087. {
  1088. return AZStd::string::format(
  1089. "%s-%u-%llu.log", jobEntry.m_sourceAssetReference.RelativePath().c_str(), jobEntry.GetHash(), jobEntry.m_jobRunKey);
  1090. }
  1091. bool CreateTempRootFolder(QString startFolder, QDir& tempRoot)
  1092. {
  1093. tempRoot.setPath(startFolder);
  1094. if (!tempRoot.exists("AssetProcessorTemp"))
  1095. {
  1096. if (!tempRoot.mkpath("AssetProcessorTemp"))
  1097. {
  1098. AZ_WarningOnce("Asset Utils", false, "Could not create a temp folder at %s", startFolder.toUtf8().constData());
  1099. return false;
  1100. }
  1101. }
  1102. if (!tempRoot.cd("AssetProcessorTemp"))
  1103. {
  1104. AZ_WarningOnce("Asset Utils", false, "Could not access temp folder at %s/AssetProcessorTemp", startFolder.toUtf8().constData());
  1105. return false;
  1106. }
  1107. return true;
  1108. }
  1109. bool CreateTempWorkspace(QString startFolder, QString& result)
  1110. {
  1111. if (!AssetUtilsInternal::g_hasInitializedRandomNumberGenerator)
  1112. {
  1113. AssetUtilsInternal::g_hasInitializedRandomNumberGenerator = true;
  1114. // seed the random number generator a different seed as the main thread. random numbers are thread-specific.
  1115. // note that 0 is an invalid random seed.
  1116. AzQtComponents::GetRandomGenerator()->seed(QTime::currentTime().msecsSinceStartOfDay() + AssetUtilsInternal::g_randomNumberSequentialSeed.fetch_add(1) + 1);
  1117. }
  1118. QDir tempRoot;
  1119. if (!CreateTempRootFolder(startFolder, tempRoot))
  1120. {
  1121. result.clear();
  1122. return false;
  1123. }
  1124. // try multiple times in the very low chance that its going to be a collision:
  1125. for (int attempts = 0; attempts < 3; ++attempts)
  1126. {
  1127. QTemporaryDir tempDir(tempRoot.absoluteFilePath("JobTemp-XXXXXX"));
  1128. tempDir.setAutoRemove(false);
  1129. if ((tempDir.path().isEmpty()) || (!QDir(tempDir.path()).exists()))
  1130. {
  1131. QByteArray errorData = tempDir.errorString().toUtf8();
  1132. AZ_WarningOnce("Asset Utils", false, "Could not create new temp folder in %s - error from OS is '%s'", tempRoot.absolutePath().toUtf8().constData(), errorData.constData());
  1133. result.clear();
  1134. AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(100));
  1135. continue;
  1136. }
  1137. result = tempDir.path();
  1138. break;
  1139. }
  1140. return !result.isEmpty();
  1141. }
  1142. bool CreateTempWorkspace(QString& result)
  1143. {
  1144. // Use the project user folder as a temp workspace folder
  1145. // The benefits are
  1146. // * It's on the same drive as the Cache/ so we will be moving files instead of copying from drive to drive
  1147. // * It is discoverable by the user and thus deletable and we can also tell people to send us that folder without them having to go digging for it
  1148. QDir rootDir;
  1149. bool foundValidPath{};
  1150. if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr)
  1151. {
  1152. if (AZ::IO::Path userPath; settingsRegistry->Get(userPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectUserPath))
  1153. {
  1154. rootDir.setPath(QString::fromUtf8(userPath.c_str(), aznumeric_cast<int>(userPath.Native().size())));
  1155. foundValidPath = true;
  1156. }
  1157. }
  1158. if (!foundValidPath)
  1159. {
  1160. foundValidPath = ComputeAssetRoot(rootDir);
  1161. }
  1162. if (foundValidPath)
  1163. {
  1164. QString tempPath = rootDir.absolutePath();
  1165. return CreateTempWorkspace(tempPath, result);
  1166. }
  1167. result.clear();
  1168. return false;
  1169. }
  1170. QString GuessProductNameInDatabase(QString path, QString platform, AssetProcessor::AssetDatabaseConnection* databaseConnection)
  1171. {
  1172. QString productName;
  1173. QString inputName;
  1174. QString platformName;
  1175. QString jobDescription;
  1176. using namespace AzToolsFramework::AssetDatabase;
  1177. productName = AssetUtilities::NormalizeAndRemoveAlias(path);
  1178. // most of the time, the incoming request will be for an actual product name, so optimize this by assuming that is the case
  1179. // and do an optimized query for it
  1180. if (platform.isEmpty())
  1181. {
  1182. platform = AzToolsFramework::AssetSystem::GetHostAssetPlatform();
  1183. }
  1184. QString platformPrepend = QString("%1/").arg(platform);
  1185. QString productNameWithPlatform = productName;
  1186. if (!productName.startsWith(platformPrepend, Qt::CaseInsensitive))
  1187. {
  1188. productNameWithPlatform = productName = QString("%1/%2").arg(platform, productName);
  1189. }
  1190. ProductDatabaseEntryContainer products;
  1191. if (databaseConnection->GetProductsByProductName(productNameWithPlatform, products))
  1192. {
  1193. // if we find stuff, then return immediately, productName is already a productName.
  1194. return productName;
  1195. }
  1196. // if that fails, see at least if it starts with the given product name.
  1197. if (databaseConnection->GetProductsLikeProductName(productName, AssetDatabaseConnection::LikeType::StartsWith, products))
  1198. {
  1199. return productName;
  1200. }
  1201. if (!databaseConnection->GetProductsLikeProductName(productNameWithPlatform, AssetDatabaseConnection::LikeType::StartsWith, products))
  1202. {
  1203. return {};
  1204. }
  1205. return productName.toLower();
  1206. }
  1207. bool UpdateToCorrectCase(const QString& rootPath, QString& relativePathFromRoot, bool checkEntirePath /* = true*/)
  1208. {
  1209. // normalize the input string:
  1210. relativePathFromRoot = NormalizeFilePath(relativePathFromRoot);
  1211. // the File State Cache is itself case-insensitive on all operating systems an is warmed up as the application starts
  1212. // from a quick iteration of all files that exist, before any real logic is created. It is safe to check
  1213. // it for the existence of a file and early out to save time.
  1214. auto* fileStateInterface = AZ::Interface<AssetProcessor::IFileStateRequests>::Get();
  1215. if (fileStateInterface)
  1216. {
  1217. AssetProcessor::FileStateInfo fsInfo;
  1218. // use AZ::IO::Path here to combine the strings. Qt will otherwise potentially make assumptions about the
  1219. // working directory and give weird results that differ depending on the operating system.
  1220. AZ::IO::Path fullPath = AZ::IO::Path(rootPath.toUtf8().constData()) / relativePathFromRoot.toUtf8().constData();
  1221. if (!fileStateInterface->GetFileInfo(QString::fromUtf8(fullPath.c_str()), &fsInfo))
  1222. {
  1223. return false; // file does not exist according to the cache, which itself, is case insensitive.
  1224. }
  1225. // fsInfo contains the absolute path, but we need to update only the relative path part.
  1226. if (!rootPath.isEmpty()) // rootpath could be empty and relativePathFromRoot could be a full path
  1227. {
  1228. // to get here, length of rootpath will be at LEAST one.
  1229. relativePathFromRoot = fsInfo.m_absolutePath.mid(rootPath.length() + 1);
  1230. }
  1231. else
  1232. {
  1233. relativePathFromRoot = fsInfo.m_absolutePath;
  1234. }
  1235. return true;
  1236. }
  1237. // If we get here, there is no cache, and we fall back on the actual update to correct case logic.
  1238. // The reason we have to do this is that it could be possible that the file has a different
  1239. // case than expected, so it won't "exist" on disk with that exact name.
  1240. AZStd::string relPathFromRoot = relativePathFromRoot.toUtf8().constData();
  1241. if(AzToolsFramework::AssetUtils::UpdateFilePathToCorrectCase(rootPath.toUtf8().constData(), relPathFromRoot, checkEntirePath))
  1242. {
  1243. relativePathFromRoot = QString::fromUtf8(relPathFromRoot.c_str(), aznumeric_cast<int>(relPathFromRoot.size()));
  1244. return true;
  1245. }
  1246. return false;
  1247. }
  1248. bool IsInCacheFolder(AZ::IO::PathView path, AZ::IO::Path cachePath)
  1249. {
  1250. if(cachePath.empty())
  1251. {
  1252. QDir cacheDir;
  1253. [[maybe_unused]] bool result = ComputeProjectCacheRoot(cacheDir);
  1254. AZ_Error("AssetUtils", result, "Failed to get cache root for IsInCacheFolder");
  1255. cachePath = cacheDir.absolutePath().toUtf8().constData();
  1256. }
  1257. return path.IsRelativeTo(cachePath) && !IsInIntermediateAssetsFolder(path, cachePath);
  1258. }
  1259. bool IsInIntermediateAssetsFolder(AZ::IO::PathView path, AZ::IO::PathView cachePath)
  1260. {
  1261. AZ::IO::FixedMaxPath fixedCachedPath = cachePath;
  1262. if (fixedCachedPath.empty())
  1263. {
  1264. QDir cacheDir;
  1265. [[maybe_unused]] bool result = ComputeProjectCacheRoot(cacheDir);
  1266. AZ_Error("AssetUtils", result, "Failed to get cache root for IsInCacheFolder");
  1267. fixedCachedPath = cacheDir.absolutePath().toUtf8().constData();
  1268. }
  1269. AZ::IO::FixedMaxPath intermediateAssetsPath = GetIntermediateAssetsFolder(cachePath);
  1270. return path.IsRelativeTo(intermediateAssetsPath);
  1271. }
  1272. AZ::IO::FixedMaxPath GetIntermediateAssetsFolder(AZ::IO::PathView cachePath)
  1273. {
  1274. AZ::IO::FixedMaxPath path(cachePath);
  1275. return path / AssetProcessor::IntermediateAssetsFolderName;
  1276. }
  1277. AZStd::string GetIntermediateAssetDatabaseName(AZ::IO::PathView relativePath)
  1278. {
  1279. // For intermediate assets, the platform must always be common, we don't support anything else for intermediate assets
  1280. AZ::IO::Path platformPrefix = AssetBuilderSDK::CommonPlatformName;
  1281. return (platformPrefix / relativePath).LexicallyNormal().StringAsPosix();
  1282. }
  1283. AZStd::optional<AzToolsFramework::AssetDatabase::SourceDatabaseEntry> GetTopLevelSourceForIntermediateAsset(
  1284. const AssetProcessor::SourceAssetReference& sourceAsset, AZStd::shared_ptr<AssetProcessor::AssetDatabaseConnection> db)
  1285. {
  1286. AzToolsFramework::AssetDatabase::SourceDatabaseEntryContainer sources;
  1287. db->GetSourcesByProductName(GetIntermediateAssetDatabaseName(sourceAsset.RelativePath()).c_str(), sources);
  1288. if (sources.empty())
  1289. {
  1290. return {};
  1291. }
  1292. if (sources.size() > 1)
  1293. {
  1294. AZ_Error(AssetProcessor::ConsoleChannel, false, "GetTopLevelSourceForProduct found multiple sources for product %s", sourceAsset.AbsolutePath().c_str());
  1295. return {};
  1296. }
  1297. AzToolsFramework::AssetDatabase::SourceDatabaseEntry source;
  1298. do
  1299. {
  1300. source = sources[0];
  1301. sources = {}; // Clear the array, otherwise it keeps accumulating the results
  1302. } while (db->GetSourcesByProductName(GetIntermediateAssetDatabaseName(source.m_sourceName.c_str()).c_str(), sources));
  1303. return source;
  1304. }
  1305. AZStd::optional<AZ::IO::Path> GetTopLevelSourcePathForIntermediateAsset(
  1306. const AssetProcessor::SourceAssetReference& sourceAsset, AZStd::shared_ptr<AssetProcessor::AssetDatabaseConnection> db)
  1307. {
  1308. auto topLevelSourceDbEntry = GetTopLevelSourceForIntermediateAsset(sourceAsset, db);
  1309. if (!topLevelSourceDbEntry)
  1310. {
  1311. return {};
  1312. }
  1313. AzToolsFramework::AssetDatabase::ScanFolderDatabaseEntry scanfolderForTopLevelSource;
  1314. if(!db->GetScanFolderByScanFolderID(topLevelSourceDbEntry->m_scanFolderPK, scanfolderForTopLevelSource))
  1315. {
  1316. return {};
  1317. }
  1318. AZ::IO::Path fullPath = scanfolderForTopLevelSource.m_scanFolder;
  1319. fullPath /= topLevelSourceDbEntry->m_sourceName;
  1320. return fullPath;
  1321. }
  1322. AZStd::vector<AssetProcessor::SourceAssetReference> GetAllIntermediateSources(
  1323. const AssetProcessor::SourceAssetReference& sourceAsset, AZStd::shared_ptr<AssetProcessor::AssetDatabaseConnection> db)
  1324. {
  1325. AZStd::vector<AssetProcessor::SourceAssetReference> sources;
  1326. auto topLevelSource = GetTopLevelSourceForIntermediateAsset(sourceAsset, db);
  1327. if (!topLevelSource)
  1328. {
  1329. AzToolsFramework::AssetDatabase::SourceDatabaseEntry source;
  1330. if(!db->GetSourceBySourceNameScanFolderId(sourceAsset.RelativePath().c_str(), sourceAsset.ScanFolderId(), source))
  1331. {
  1332. return {};
  1333. }
  1334. topLevelSource = source;
  1335. }
  1336. AzToolsFramework::AssetDatabase::ScanFolderDatabaseEntry scanFolder;
  1337. db->GetScanFolderByScanFolderID(topLevelSource->m_scanFolderPK, scanFolder);
  1338. sources.emplace_back(scanFolder.m_scanFolder.c_str(), topLevelSource->m_sourceName.c_str());
  1339. AzToolsFramework::AssetDatabase::ProductDatabaseEntryContainer products;
  1340. db->GetProductsBySourceID(topLevelSource->m_sourceID, products);
  1341. auto size = products.size();
  1342. for (int i = 0; i < size; ++i)
  1343. {
  1344. const auto& product = products[i];
  1345. if ((static_cast<AssetBuilderSDK::ProductOutputFlags>(product.m_flags.to_ullong()) & AssetBuilderSDK::ProductOutputFlags::IntermediateAsset) == AssetBuilderSDK::ProductOutputFlags::IntermediateAsset)
  1346. {
  1347. auto productPath = ProductPath::FromDatabasePath(product.m_productName);
  1348. sources.emplace_back(productPath.GetIntermediatePath().c_str());
  1349. // Note: This call is intentionally re-using the products array. The new results will be appended to the end (via push_back).
  1350. // The array will not be cleared. We're essentially using products as a queue
  1351. db->GetProductsBySourceNameScanFolderID(sources.back().RelativePath().c_str(), sources.back().ScanFolderId(), products);
  1352. size = products.size(); // Update the loop size since the array grew
  1353. }
  1354. }
  1355. return sources;
  1356. }
  1357. BuilderFilePatternMatcher::BuilderFilePatternMatcher(const AssetBuilderSDK::AssetBuilderPattern& pattern, const AZ::Uuid& builderDescID)
  1358. : AssetBuilderSDK::FilePatternMatcher(pattern)
  1359. , m_builderDescID(builderDescID)
  1360. {
  1361. }
  1362. BuilderFilePatternMatcher::BuilderFilePatternMatcher(const BuilderFilePatternMatcher& copy)
  1363. : AssetBuilderSDK::FilePatternMatcher(copy)
  1364. , m_builderDescID(copy.m_builderDescID)
  1365. {
  1366. }
  1367. const AZ::Uuid& BuilderFilePatternMatcher::GetBuilderDescID() const
  1368. {
  1369. return this->m_builderDescID;
  1370. };
  1371. QuitListener::QuitListener()
  1372. : m_requestedQuit(false)
  1373. {
  1374. }
  1375. QuitListener::~QuitListener()
  1376. {
  1377. BusDisconnect();
  1378. }
  1379. void QuitListener::ApplicationShutdownRequested()
  1380. {
  1381. m_requestedQuit = true;
  1382. }
  1383. bool QuitListener::WasQuitRequested() const
  1384. {
  1385. return m_requestedQuit;
  1386. }
  1387. JobLogTraceListener::JobLogTraceListener(const AZStd::string& logFileName, AZ::s64 jobKey, bool overwriteLogFile /* = false */)
  1388. {
  1389. m_logFileName = AssetUtilities::ComputeJobLogFolder() + "/" + logFileName;
  1390. m_runKey = jobKey;
  1391. m_forceOverwriteLog = overwriteLogFile;
  1392. AZ::Debug::TraceMessageBus::Handler::BusConnect();
  1393. }
  1394. JobLogTraceListener::JobLogTraceListener(const AzToolsFramework::AssetSystem::JobInfo& jobInfo, bool overwriteLogFile /* = false */)
  1395. {
  1396. m_logFileName = AssetUtilities::ComputeJobLogFolder() + "/" + AssetUtilities::ComputeJobLogFileName(jobInfo);
  1397. m_runKey = jobInfo.m_jobRunKey;
  1398. m_forceOverwriteLog = overwriteLogFile;
  1399. AZ::Debug::TraceMessageBus::Handler::BusConnect();
  1400. }
  1401. JobLogTraceListener::JobLogTraceListener(const AssetProcessor::JobEntry& jobEntry, bool overwriteLogFile /* = false */)
  1402. {
  1403. m_logFileName = AssetUtilities::ComputeJobLogFolder() + "/" + AssetUtilities::ComputeJobLogFileName(jobEntry);
  1404. m_runKey = jobEntry.m_jobRunKey;
  1405. m_forceOverwriteLog = overwriteLogFile;
  1406. AZ::Debug::TraceMessageBus::Handler::BusConnect();
  1407. }
  1408. JobLogTraceListener::~JobLogTraceListener()
  1409. {
  1410. BusDisconnect();
  1411. }
  1412. bool JobLogTraceListener::OnAssert(const char* message)
  1413. {
  1414. if (AssetProcessor::GetThreadLocalJobId() == m_runKey)
  1415. {
  1416. AppendLog(AzFramework::LogFile::SEV_ASSERT, "ASSERT", message);
  1417. return true;
  1418. }
  1419. return false;
  1420. }
  1421. bool JobLogTraceListener::OnException(const char* message)
  1422. {
  1423. if (AssetProcessor::GetThreadLocalJobId() == m_runKey)
  1424. {
  1425. m_inException = true;
  1426. AppendLog(AzFramework::LogFile::SEV_EXCEPTION, "EXCEPTION", message);
  1427. // we return false here so that the main app can also trace it, exceptions are bad enough
  1428. // that we want them to show up in all the logs.
  1429. }
  1430. return false;
  1431. }
  1432. // we want no trace of errors to show up from jobs, inside the console app
  1433. // only in explicit usages, so we return true for pre-error here too
  1434. bool JobLogTraceListener::OnPreError(const char* window, const char* /*file*/, int /*line*/, const char* /*func*/, const char* message)
  1435. {
  1436. if (AssetProcessor::GetThreadLocalJobId() == m_runKey)
  1437. {
  1438. AppendLog(m_inException ? AzFramework::LogFile::SEV_EXCEPTION : AzFramework::LogFile::SEV_ERROR, window, message);
  1439. return true;
  1440. }
  1441. return false;
  1442. }
  1443. bool JobLogTraceListener::OnWarning(const char* window, const char* message)
  1444. {
  1445. if (AssetProcessor::GetThreadLocalJobId() == m_runKey)
  1446. {
  1447. AppendLog(m_inException ? AzFramework::LogFile::SEV_EXCEPTION : AzFramework::LogFile::SEV_WARNING, window, message);
  1448. return true;
  1449. }
  1450. return false;
  1451. }
  1452. bool JobLogTraceListener::OnPrintf(const char* window, const char* message)
  1453. {
  1454. if (AssetProcessor::GetThreadLocalJobId() == m_runKey)
  1455. {
  1456. if(azstrnicmp(message, "S: ", 3) == 0)
  1457. {
  1458. std::string dummy;
  1459. std::istringstream stream(message);
  1460. AZ::s64 errorCount, warningCount;
  1461. stream >> dummy >> errorCount >> dummy >> warningCount;
  1462. m_errorCount += errorCount;
  1463. m_warningCount += warningCount;
  1464. }
  1465. if (azstrnicmp(window, "debug", 5) == 0)
  1466. {
  1467. AppendLog(AzFramework::LogFile::SEV_DEBUG, window, message);
  1468. }
  1469. else
  1470. {
  1471. AppendLog(m_inException ? AzFramework::LogFile::SEV_EXCEPTION : AzFramework::LogFile::SEV_NORMAL, window, message);
  1472. }
  1473. return true;
  1474. }
  1475. return false;
  1476. }
  1477. void JobLogTraceListener::AppendLog(AzFramework::LogFile::SeverityLevel severity, const char* window, const char* message)
  1478. {
  1479. if (m_isLogging)
  1480. {
  1481. return;
  1482. }
  1483. m_isLogging = true;
  1484. if (!m_logFile)
  1485. {
  1486. m_logFile.reset(new AzFramework::LogFile(m_logFileName.c_str(), m_forceOverwriteLog));
  1487. }
  1488. m_logFile->AppendLog(severity, window, message);
  1489. m_isLogging = false;
  1490. }
  1491. void JobLogTraceListener::AppendLog(AzToolsFramework::Logging::LogLine& logLine)
  1492. {
  1493. using namespace AzToolsFramework;
  1494. using namespace AzFramework;
  1495. if (m_isLogging)
  1496. {
  1497. return;
  1498. }
  1499. m_isLogging = true;
  1500. if (!m_logFile)
  1501. {
  1502. m_logFile.reset(new LogFile(m_logFileName.c_str(), m_forceOverwriteLog));
  1503. }
  1504. LogFile::SeverityLevel severity;
  1505. switch (logLine.GetLogType())
  1506. {
  1507. case Logging::LogLine::TYPE_MESSAGE:
  1508. severity = LogFile::SEV_NORMAL;
  1509. break;
  1510. case Logging::LogLine::TYPE_WARNING:
  1511. severity = LogFile::SEV_WARNING;
  1512. break;
  1513. case Logging::LogLine::TYPE_ERROR:
  1514. severity = LogFile::SEV_ERROR;
  1515. break;
  1516. default:
  1517. severity = LogFile::SEV_DEBUG;
  1518. }
  1519. m_logFile->AppendLog(severity, logLine.GetLogMessage().c_str(), (int)logLine.GetLogMessage().length(),
  1520. logLine.GetLogWindow().c_str(), (int)logLine.GetLogWindow().length(), logLine.GetLogThreadId(), logLine.GetLogTime());
  1521. m_isLogging = false;
  1522. }
  1523. AZ::s64 JobLogTraceListener::GetErrorCount() const
  1524. {
  1525. return m_errorCount;
  1526. }
  1527. AZ::s64 JobLogTraceListener::GetWarningCount() const
  1528. {
  1529. return m_warningCount;
  1530. }
  1531. void JobLogTraceListener::AddError()
  1532. {
  1533. ++m_errorCount;
  1534. }
  1535. void JobLogTraceListener::AddWarning()
  1536. {
  1537. ++m_warningCount;
  1538. }
  1539. AZStd::string GetRelativeProductPathForIntermediateSourcePath(AZStd::string_view relativeSourcePath)
  1540. {
  1541. AZStd::string productPath((AZ::IO::FixedMaxPath(AssetBuilderSDK::CommonPlatformName) / relativeSourcePath).StringAsPosix());
  1542. // Product paths are always lowercase
  1543. AZStd::to_lower(productPath.begin(), productPath.end());
  1544. return productPath;
  1545. }
  1546. ProductPath::ProductPath(AZStd::string scanfolderRelativeProductPath, AZStd::string platformIdentifier)
  1547. {
  1548. AZ_Assert(AZ::IO::PathView(scanfolderRelativeProductPath).IsRelative(), "scanfolderRelativeProductPath is not relative: %s", scanfolderRelativeProductPath.c_str());
  1549. QDir cacheDir;
  1550. [[maybe_unused]] bool result = ComputeProjectCacheRoot(cacheDir);
  1551. AZ_Error("AssetUtils", result, "Failed to get cache root");
  1552. AZ::IO::FixedMaxPath cachePath = cacheDir.absolutePath().toUtf8().constData();
  1553. // Lowercase the inputs. The cache path is always lowercased, which means the database path is lowercased,
  1554. // and for consistency, the intermediate path is also lowercased.
  1555. // All the other parts of the path must remain properly cased.
  1556. AZStd::to_lower(scanfolderRelativeProductPath.begin(), scanfolderRelativeProductPath.end());
  1557. AZStd::to_lower(platformIdentifier.begin(), platformIdentifier.end());
  1558. m_relativePath = NormalizeFilePath(scanfolderRelativeProductPath.c_str()).toUtf8().constData();
  1559. m_cachePath = cachePath / platformIdentifier / scanfolderRelativeProductPath;
  1560. m_intermediatePath = AssetUtilities::GetIntermediateAssetsFolder(cachePath) / scanfolderRelativeProductPath;
  1561. m_databasePath = AZ::IO::FixedMaxPath(platformIdentifier) / scanfolderRelativeProductPath;
  1562. }
  1563. ProductPath ProductPath::FromDatabasePath(AZStd::string_view databasePath, AZStd::string_view* platformOut)
  1564. {
  1565. AZStd::string_view platform;
  1566. AZStd::string_view relativeProductPath = AssetUtilities::StripAssetPlatformNoCopy(databasePath, &platform);
  1567. if(platformOut)
  1568. {
  1569. *platformOut = platform;
  1570. }
  1571. return ProductPath{ relativeProductPath, platform };
  1572. }
  1573. ProductPath ProductPath::FromAbsoluteProductPath(AZ::IO::PathView absolutePath, AZStd::string& outPlatform)
  1574. {
  1575. QDir cacheDir;
  1576. [[maybe_unused]] bool result = ComputeProjectCacheRoot(cacheDir);
  1577. AZ_Error("AssetUtils", result, "Failed to get cache root for IsInCacheFolder");
  1578. AZ::IO::FixedMaxPath parentFolder = cacheDir.absolutePath().toUtf8().constData();
  1579. bool intermediateAsset = IsInIntermediateAssetsFolder(absolutePath, parentFolder);
  1580. if (intermediateAsset)
  1581. {
  1582. parentFolder = AssetUtilities::GetIntermediateAssetsFolder(parentFolder);
  1583. outPlatform = AssetBuilderSDK::CommonPlatformName;
  1584. }
  1585. auto relativePath = absolutePath.LexicallyRelative(parentFolder);
  1586. if (!intermediateAsset)
  1587. {
  1588. AZStd::string_view platform;
  1589. auto fixedString = relativePath.FixedMaxPathStringAsPosix();
  1590. relativePath = StripAssetPlatformNoCopy(fixedString, &platform);
  1591. outPlatform = platform;
  1592. }
  1593. return ProductPath{ relativePath.StringAsPosix(), outPlatform };
  1594. }
  1595. } // namespace AssetUtilities