ScriptCanvasBuilderWorker.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 <Asset/AssetDescription.h>
  9. #include <AssetBuilderSDK/SerializationDependencies.h>
  10. #include <AzCore/Asset/AssetManager.h>
  11. #include <AzCore/IO/FileIO.h>
  12. #include <AzCore/IO/IOUtils.h>
  13. #include <AzCore/Math/Uuid.h>
  14. #include <AzCore/Serialization/SerializeContext.h>
  15. #include <AzFramework/Script/ScriptComponent.h>
  16. #include <AzFramework/StringFunc/StringFunc.h>
  17. #include <Builder/ScriptCanvasBuilderWorker.h>
  18. #include <ScriptCanvas/Asset/RuntimeAsset.h>
  19. #include <ScriptCanvas/Asset/SubgraphInterfaceAsset.h>
  20. #include <ScriptCanvas/Assets/ScriptCanvasFileHandling.h>
  21. #include <ScriptCanvas/Components/EditorGraph.h>
  22. #include <ScriptCanvas/Components/EditorGraphVariableManagerComponent.h>
  23. #include <ScriptCanvas/Core/Connection.h>
  24. #include <ScriptCanvas/Core/GraphData.h>
  25. #include <ScriptCanvas/Core/Node.h>
  26. #include <ScriptCanvas/Grammar/AbstractCodeModel.h>
  27. #include <ScriptCanvas/Results/ErrorText.h>
  28. #include <ScriptCanvas/Utils/BehaviorContextUtils.h>
  29. namespace ScriptCanvasBuilder
  30. {
  31. void Worker::Activate(const AssetHandlers& handlers)
  32. {
  33. m_runtimeAssetHandler = handlers.m_runtimeAssetHandler;
  34. m_subgraphInterfaceHandler = handlers.m_subgraphInterfaceHandler;
  35. }
  36. void Worker::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) const
  37. {
  38. using namespace ScriptCanvas;
  39. AZStd::string fullPath;
  40. AzFramework::StringFunc::Path::ConstructFull(request.m_watchFolder.data(), request.m_sourceFile.data(), fullPath, false);
  41. AzFramework::StringFunc::Path::Normalize(fullPath);
  42. AZ_TracePrintf(s_scriptCanvasBuilder, "Start Creating Job: %s", fullPath.c_str());
  43. response.m_result = AssetBuilderSDK::CreateJobsResultCode::Failed;
  44. const_cast<Worker*>(this)->m_sourceUuid = request.m_sourceFileUUID;
  45. const ScriptCanvasEditor::EditorGraph* sourceGraph = nullptr;
  46. const ScriptCanvas::GraphData* graphData = nullptr;
  47. SourceHandle sourceHandle;
  48. // By default, entity IDs are made unique, so that multiple instances of the script canvas file can be loaded at the same time.
  49. // However, in this case the file is not loaded multiple times at once, and the entity IDs need to be stable so that
  50. // the logic used to generate the fingerprint for this file remains stable.
  51. const auto result = LoadFromFile(fullPath, MakeInternalGraphEntitiesUnique::No, LoadReferencedAssets::No);
  52. if (result)
  53. {
  54. sourceHandle = result.m_handle;
  55. sourceGraph = sourceHandle.Get();
  56. graphData = sourceGraph->GetGraphDataConst();
  57. }
  58. else
  59. {
  60. AZ_TracePrintf(s_scriptCanvasBuilder, "Failed to load the file: %s", fullPath.c_str());
  61. return;
  62. }
  63. if (!sourceGraph)
  64. {
  65. AZ_Error(s_scriptCanvasBuilder, false, "Graph Component missing after successfully loaded: %s", fullPath.c_str());
  66. return;
  67. }
  68. if (!graphData)
  69. {
  70. AZ_Error(s_scriptCanvasBuilder, false, "GraphData missing after successfully loaded: %s", fullPath.c_str());
  71. return;
  72. }
  73. struct EntityIdComparer
  74. {
  75. bool operator()(AZ::Entity* lhs, AZ::Entity* rhs)
  76. {
  77. AZ::EntityId lhsEntityId = lhs != nullptr ? lhs->GetId() : AZ::EntityId();
  78. AZ::EntityId rhsEntityId = rhs != nullptr ? rhs->GetId() : AZ::EntityId();
  79. return lhsEntityId < rhsEntityId;
  80. }
  81. };
  82. const AZStd::set<AZ::Entity*, EntityIdComparer> sortedEntities(graphData->m_nodes.begin(), graphData->m_nodes.end());
  83. size_t fingerprint = 0;
  84. for (const auto& nodeEntity : sortedEntities)
  85. {
  86. if (auto nodeComponent = AZ::EntityUtils::FindFirstDerivedComponent<ScriptCanvas::Node>(nodeEntity))
  87. {
  88. AZStd::hash_combine(fingerprint, nodeComponent->GenerateFingerprint());
  89. }
  90. }
  91. // Include the base node version in the hash, so when it changes, script canvas jobs are reprocessed.
  92. AZStd::hash_combine(fingerprint, ScriptCanvas::Node::GetNodeVersion());
  93. AZ::SerializeContext* serializeContext{};
  94. AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  95. if (!serializeContext)
  96. {
  97. AZ_Error(s_scriptCanvasBuilder, false
  98. , "SerializeContext is required to enumerate dependent assets in the ScriptCanvas file: %s, but was missing"
  99. , fullPath.c_str());
  100. return;
  101. }
  102. AZStd::unordered_map<AZStd::string, AZStd::unordered_set<AZ::Uuid>> jobDependenciesByKey;
  103. auto assetFilter = [this, &jobDependenciesByKey]
  104. ( void* instancePointer
  105. , const AZ::SerializeContext::ClassData* classData
  106. , [[maybe_unused]] const AZ::SerializeContext::ClassElement* classElement)
  107. {
  108. auto azTypeId = classData->m_azRtti->GetTypeId();
  109. if (azTypeId == azrtti_typeid<AZ::Data::Asset<ScriptCanvas::SubgraphInterfaceAsset>>())
  110. {
  111. const auto* subgraphAsset = reinterpret_cast<AZ::Data::Asset<const ScriptCanvas::SubgraphInterfaceAsset>*>(instancePointer);
  112. if (subgraphAsset->GetId().IsValid() && subgraphAsset->GetId().m_guid != this->m_sourceUuid)
  113. {
  114. AssetBuilderSDK::SourceFileDependency dependency;
  115. dependency.m_sourceFileDependencyUUID = subgraphAsset->GetId().m_guid;
  116. jobDependenciesByKey[s_scriptCanvasProcessJobKey].insert(dependency.m_sourceFileDependencyUUID);
  117. this->m_processEditorAssetDependencies.push_back
  118. ( { subgraphAsset->GetId(), azTypeId, AZ::Data::AssetLoadBehavior::PreLoad });
  119. }
  120. }
  121. else if (azTypeId == azrtti_typeid<AZ::Data::Asset<ScriptEvents::ScriptEventsAsset>>())
  122. {
  123. const auto* eventAsset = reinterpret_cast<AZ::Data::Asset<const ScriptEvents::ScriptEventsAsset>*>(instancePointer);
  124. if (eventAsset->GetId().IsValid() && eventAsset->GetId().m_guid != this->m_sourceUuid)
  125. {
  126. AssetBuilderSDK::SourceFileDependency dependency;
  127. dependency.m_sourceFileDependencyUUID = eventAsset->GetId().m_guid;
  128. jobDependenciesByKey[ScriptEvents::k_builderJobKey].insert(dependency.m_sourceFileDependencyUUID);
  129. this->m_processEditorAssetDependencies.push_back
  130. ( { eventAsset->GetId(), azTypeId, AZ::Data::AssetLoadBehavior::PreLoad });
  131. }
  132. }
  133. // always continue, make note of the script canvas dependencies
  134. return true;
  135. };
  136. if (!serializeContext->EnumerateInstanceConst(graphData
  137. , azrtti_typeid<ScriptCanvas::GraphData>()
  138. , assetFilter
  139. , {}
  140. , AZ::SerializeContext::ENUM_ACCESS_FOR_READ
  141. , nullptr
  142. , nullptr))
  143. {
  144. AZ_Error(s_scriptCanvasBuilder, false
  145. , "Failed to enumerate the graph data instance loaded from: %s"
  146. , fullPath.c_str());
  147. return;
  148. }
  149. // Flush asset database events to ensure no asset references are held by closures queued on Ebuses.
  150. AZ::Data::AssetManager::Instance().DispatchEvents();
  151. for (const AssetBuilderSDK::PlatformInfo& info : request.m_enabledPlatforms)
  152. {
  153. AssetBuilderSDK::JobDescriptor jobDescriptor;
  154. jobDescriptor.m_priority = 2;
  155. jobDescriptor.m_critical = true;
  156. jobDescriptor.m_jobKey = s_scriptCanvasProcessJobKey;
  157. jobDescriptor.SetPlatformIdentifier(info.m_identifier.c_str());
  158. jobDescriptor.m_additionalFingerprintInfo
  159. = AZStd::string(GetFingerprintString())
  160. .append("|")
  161. .append(AZStd::to_string(static_cast<AZ::u64>(fingerprint)));
  162. // Graph process job needs to wait until its dependency asset job finished
  163. for (const auto& jobDependencies : jobDependenciesByKey)
  164. {
  165. for (const auto& dependency : jobDependencies.second)
  166. {
  167. AssetBuilderSDK::JobDependency jobDependency;
  168. jobDependency.m_sourceFile.m_sourceFileDependencyUUID = dependency;
  169. jobDependency.m_jobKey = jobDependencies.first;
  170. jobDependency.m_platformIdentifier = info.m_identifier;
  171. jobDependency.m_type = AssetBuilderSDK::JobDependencyType::Order;
  172. jobDescriptor.m_jobDependencyList.push_back(AZStd::move(jobDependency));
  173. }
  174. }
  175. response.m_createJobOutputs.push_back(jobDescriptor);
  176. }
  177. response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success;
  178. AZ_TracePrintf(s_scriptCanvasBuilder, "Finish Creating Job: %s", fullPath.c_str());
  179. }
  180. const char* Worker::GetFingerprintString() const
  181. {
  182. if (m_fingerprintString.empty())
  183. {
  184. // compute it the first time
  185. const AZStd::string runtimeAssetTypeId = azrtti_typeid<ScriptCanvas::RuntimeAsset>().ToString<AZStd::string>();
  186. m_fingerprintString = AZStd::string::format("%s%i%s",
  187. AZ::ScriptDataContext::GetInterpreterVersion(), // this is the version of LUA - if it changes, we need to rebuild
  188. GetVersionNumber(),
  189. runtimeAssetTypeId.c_str());
  190. }
  191. return m_fingerprintString.c_str();
  192. }
  193. int Worker::GetVersionNumber() const
  194. {
  195. return GetBuilderVersion();
  196. }
  197. AZ::Uuid Worker::GetUUID()
  198. {
  199. return AZ::Uuid::CreateString("{6E86272B-7C06-4A65-9C25-9FA4AE21F993}");
  200. }
  201. void Worker::ProcessJob(const AssetBuilderSDK::ProcessJobRequest& request, AssetBuilderSDK::ProcessJobResponse& response) const
  202. {
  203. using namespace ScriptCanvas;
  204. AZ_TracePrintf(s_scriptCanvasBuilder, "Start Processing Job");
  205. // A runtime script canvas component is generated, which creates a .scriptcanvas_compiled file
  206. AZStd::string fullPath;
  207. AZStd::string fileNameOnly;
  208. AzFramework::StringFunc::Path::GetFullFileName(request.m_sourceFile.c_str(), fileNameOnly);
  209. fullPath = request.m_fullPath.c_str();
  210. AzFramework::StringFunc::Path::Normalize(fullPath);
  211. bool pathFound = false;
  212. AZStd::string relativePath;
  213. AzToolsFramework::AssetSystemRequestBus::BroadcastResult
  214. ( pathFound
  215. , &AzToolsFramework::AssetSystem::AssetSystemRequest::GetRelativeProductPathFromFullSourceOrProductPath
  216. , request.m_fullPath.c_str(), relativePath);
  217. if (!pathFound)
  218. {
  219. AZ_Error(s_scriptCanvasBuilder, false, "Failed to get engine relative path from %s", request.m_fullPath.c_str());
  220. return;
  221. }
  222. if (!m_runtimeAssetHandler)
  223. {
  224. AZ_Error(s_scriptCanvasBuilder, false, R"(Exporting of .scriptcanvas for "%s" file failed as no runtime asset handler was registered for script canvas.)", fullPath.data());
  225. return;
  226. }
  227. const auto result = LoadFromFile(request.m_fullPath, MakeInternalGraphEntitiesUnique::No);
  228. if (!result)
  229. {
  230. AZ_Error(s_scriptCanvasBuilder, false, R"(Loading of ScriptCanvas asset for source file "%s" has failed)", fullPath.data());
  231. return;
  232. }
  233. // Flush asset manager events to ensure no asset references are held by closures queued on Ebuses.
  234. AZ::Data::AssetManager::Instance().DispatchEvents();
  235. AZStd::string runtimeScriptCanvasOutputPath;
  236. AzFramework::StringFunc::Path::Join(request.m_tempDirPath.c_str(), fileNameOnly.c_str(), runtimeScriptCanvasOutputPath, true, true);
  237. AzFramework::StringFunc::Path::ReplaceExtension(runtimeScriptCanvasOutputPath, ScriptCanvas::RuntimeAsset::GetFileExtension());
  238. auto sourceHandle = result.m_handle;
  239. if (request.m_jobDescription.m_jobKey == s_scriptCanvasProcessJobKey)
  240. {
  241. AZ::Entity* buildEntity = sourceHandle.Get()->GetEntity();
  242. ProcessTranslationJobInput input;
  243. input.assetID = AZ::Data::AssetId(request.m_sourceFileUUID, RuntimeDataSubId);
  244. input.request = &request;
  245. input.response = &response;
  246. input.runtimeScriptCanvasOutputPath = runtimeScriptCanvasOutputPath;
  247. input.assetHandler = m_runtimeAssetHandler;
  248. input.buildEntity = buildEntity;
  249. input.fullPath = fullPath;
  250. input.fileNameOnly = fileNameOnly;
  251. input.namespacePath = relativePath;
  252. input.saveRawLua = true;
  253. auto translationOutcome = ProcessTranslationJob(input);
  254. if (translationOutcome.IsSuccess())
  255. {
  256. auto saveOutcome = SaveRuntimeAsset(input, input.runtimeDataOut);
  257. if (saveOutcome.IsSuccess())
  258. {
  259. // save function interface
  260. AzFramework::StringFunc::Path::StripExtension(fileNameOnly);
  261. ScriptCanvas::SubgraphInterfaceData functionInterface;
  262. functionInterface.m_name = fileNameOnly;
  263. functionInterface.m_interface = AZStd::move(input.interfaceOut);
  264. input.assetHandler = m_subgraphInterfaceHandler;
  265. AzFramework::StringFunc::Path::ReplaceExtension(input.runtimeScriptCanvasOutputPath, ScriptCanvas::SubgraphInterfaceAsset::GetFileExtension());
  266. auto saveInterfaceOutcome = SaveSubgraphInterface(input, functionInterface);
  267. if (saveInterfaceOutcome.IsSuccess())
  268. {
  269. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  270. }
  271. else
  272. {
  273. AZ_Error(s_scriptCanvasBuilder, false, saveInterfaceOutcome.GetError().data());
  274. }
  275. }
  276. else
  277. {
  278. AZ_Error(s_scriptCanvasBuilder, false, saveOutcome.GetError().c_str());
  279. }
  280. }
  281. else
  282. {
  283. if (AzFramework::StringFunc::Find(translationOutcome.GetError().c_str(), ScriptCanvas::ParseErrors::SourceUpdateRequired) != AZStd::string::npos)
  284. {
  285. AZ_Warning(s_scriptCanvasBuilder, false, ScriptCanvas::ParseErrors::SourceUpdateRequired);
  286. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  287. }
  288. else if (AzFramework::StringFunc::Find(translationOutcome.GetError().c_str(), ScriptCanvas::ParseErrors::EmptyGraph) != AZStd::string::npos)
  289. {
  290. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  291. }
  292. else
  293. {
  294. if (!ScriptCanvas::Grammar::g_processingErrorsForUnitTestsEnabled
  295. && AzFramework::StringFunc::Find(fileNameOnly, s_unitTestParseErrorPrefix) != AZStd::string::npos)
  296. {
  297. response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Success;
  298. }
  299. AZ_Error(s_scriptCanvasBuilder, false, translationOutcome.GetError().c_str());
  300. }
  301. }
  302. m_processEditorAssetDependencies.clear();
  303. }
  304. AZ_TracePrintf(s_scriptCanvasBuilder, "Finish Processing Job");
  305. }
  306. }