ScriptProcessorRuleBehavior.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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 <SceneAPI/SceneData/Behaviors/ScriptProcessorRuleBehavior.h>
  9. #include <AzCore/IO/FileIO.h>
  10. #include <AzCore/IO/Path/Path.h>
  11. #include <AzCore/RTTI/BehaviorContext.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <AzCore/Settings/SettingsRegistryMergeUtils.h>
  14. #include <AzCore/std/smart_ptr/make_shared.h>
  15. #include <AzFramework/API/ApplicationAPI.h>
  16. #include <AzFramework/Asset/AssetSystemComponent.h>
  17. #include <AzFramework/StringFunc/StringFunc.h>
  18. #include <AzToolsFramework/API/EditorPythonConsoleBus.h>
  19. #include <AzToolsFramework/API/EditorPythonRunnerRequestsBus.h>
  20. #include <SceneAPI/SceneCore/Containers/Scene.h>
  21. #include <SceneAPI/SceneCore/Containers/SceneGraph.h>
  22. #include <SceneAPI/SceneCore/Containers/SceneManifest.h>
  23. #include <SceneAPI/SceneCore/Containers/Utilities/Filters.h>
  24. #include <SceneAPI/SceneCore/Containers/Views/FilterIterator.h>
  25. #include <SceneAPI/SceneCore/Containers/Views/PairIterator.h>
  26. #include <SceneAPI/SceneData/Rules/ScriptProcessorRule.h>
  27. #include <SceneAPI/SceneCore/Utilities/Reporting.h>
  28. #include <SceneAPI/SceneCore/Events/ExportProductList.h>
  29. namespace AZ::SceneAPI::Behaviors
  30. {
  31. class EditorPythonConsoleNotificationHandler final
  32. : protected AzToolsFramework::EditorPythonConsoleNotificationBus::Handler
  33. {
  34. public:
  35. EditorPythonConsoleNotificationHandler()
  36. {
  37. BusConnect();
  38. }
  39. ~EditorPythonConsoleNotificationHandler()
  40. {
  41. BusDisconnect();
  42. }
  43. ////////////////////////////////////////////////////////////////////////////////////////////
  44. // AzToolsFramework::EditorPythonConsoleNotifications
  45. void OnTraceMessage([[maybe_unused]] AZStd::string_view message) override
  46. {
  47. using namespace AZ::SceneAPI::Utilities;
  48. AZ_TracePrintf(LogWindow, "%.*s \n", AZ_STRING_ARG(message));
  49. }
  50. void OnErrorMessage([[maybe_unused]] AZStd::string_view message) override
  51. {
  52. using namespace AZ::SceneAPI::Utilities;
  53. AZ_TracePrintf(ErrorWindow, "[ERROR] %.*s \n", AZ_STRING_ARG(message));
  54. }
  55. void OnExceptionMessage([[maybe_unused]] AZStd::string_view message) override
  56. {
  57. using namespace AZ::SceneAPI::Utilities;
  58. AZ_TracePrintf(ErrorWindow, "[EXCEPTION] %.*s \n", AZ_STRING_ARG(message));
  59. }
  60. };
  61. using ExportProductList = AZ::SceneAPI::Events::ExportProductList;
  62. // a event bus to signal during scene building
  63. struct ScriptBuildingNotifications
  64. : public AZ::EBusTraits
  65. {
  66. virtual AZStd::string OnUpdateManifest(Containers::Scene& scene) = 0;
  67. virtual ExportProductList OnPrepareForExport(
  68. const Containers::Scene& scene,
  69. AZStd::string_view outputDirectory,
  70. AZStd::string_view platformIdentifier,
  71. const ExportProductList& productList) = 0;
  72. };
  73. using ScriptBuildingNotificationBus = AZ::EBus<ScriptBuildingNotifications>;
  74. // a back end to handle scene builder events for a script
  75. struct ScriptBuildingNotificationBusHandler final
  76. : public ScriptBuildingNotificationBus::Handler
  77. , public AZ::BehaviorEBusHandler
  78. {
  79. AZ_EBUS_BEHAVIOR_BINDER(
  80. ScriptBuildingNotificationBusHandler,
  81. "{DF2B51DE-A4D0-4139-B5D0-DF185832380D}",
  82. AZ::SystemAllocator,
  83. OnUpdateManifest,
  84. OnPrepareForExport);
  85. virtual ~ScriptBuildingNotificationBusHandler() = default;
  86. AZStd::string OnUpdateManifest(Containers::Scene& scene) override
  87. {
  88. AZStd::string result;
  89. CallResult(result, FN_OnUpdateManifest, scene);
  90. ScriptBuildingNotificationBusHandler::BusDisconnect();
  91. return result;
  92. }
  93. ExportProductList OnPrepareForExport(
  94. const Containers::Scene& scene,
  95. AZStd::string_view outputDirectory,
  96. AZStd::string_view platformIdentifier,
  97. const ExportProductList& productList) override
  98. {
  99. ExportProductList result;
  100. CallResult(result, FN_OnPrepareForExport, scene, outputDirectory, platformIdentifier, productList);
  101. ScriptBuildingNotificationBusHandler::BusDisconnect();
  102. return result;
  103. }
  104. static void Reflect(AZ::ReflectContext* context)
  105. {
  106. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  107. {
  108. behaviorContext->EBus<ScriptBuildingNotificationBus>("ScriptBuildingNotificationBus")
  109. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  110. ->Attribute(AZ::Script::Attributes::Module, "scene")
  111. ->Handler<ScriptBuildingNotificationBusHandler>()
  112. ->Event("OnUpdateManifest", &ScriptBuildingNotificationBus::Events::OnUpdateManifest)
  113. ->Event("OnPrepareForExport", &ScriptBuildingNotificationBus::Events::OnPrepareForExport);
  114. }
  115. }
  116. };
  117. struct ScriptProcessorRuleBehavior::ExportEventHandler final
  118. : public AZ::SceneAPI::SceneCore::ExportingComponent
  119. {
  120. using PreExportEventContextFunction = AZStd::function<bool(Events::PreExportEventContext&)>;
  121. PreExportEventContextFunction m_preExportEventContextFunction;
  122. ExportEventHandler(PreExportEventContextFunction preExportEventContextFunction)
  123. : m_preExportEventContextFunction(preExportEventContextFunction)
  124. {
  125. BindToCall(&ExportEventHandler::PrepareForExport);
  126. AZ::SceneAPI::SceneCore::ExportingComponent::Activate();
  127. }
  128. ~ExportEventHandler()
  129. {
  130. AZ::SceneAPI::SceneCore::ExportingComponent::Deactivate();
  131. }
  132. // this allows a Python script to add product assets on "scene export"
  133. Events::ProcessingResult PrepareForExport(Events::PreExportEventContext& context)
  134. {
  135. return m_preExportEventContextFunction(context) ? Events::ProcessingResult::Success : Events::ProcessingResult::Failure;
  136. }
  137. };
  138. void ScriptProcessorRuleBehavior::Activate()
  139. {
  140. Events::AssetImportRequestBus::Handler::BusConnect();
  141. m_exportEventHandler = AZStd::make_shared<ExportEventHandler>([this](Events::PreExportEventContext& context)
  142. {
  143. return this->DoPrepareForExport(context);
  144. });
  145. }
  146. void ScriptProcessorRuleBehavior::Deactivate()
  147. {
  148. m_exportEventHandler.reset();
  149. Events::AssetImportRequestBus::Handler::BusDisconnect();
  150. UnloadPython();
  151. }
  152. bool ScriptProcessorRuleBehavior::LoadPython(const AZ::SceneAPI::Containers::Scene& scene, AZStd::string& scriptPath, Events::ProcessingResult& fallbackResult)
  153. {
  154. using namespace AZ::SceneAPI;
  155. fallbackResult = Events::ProcessingResult::Failure;
  156. int scriptDiscoveryAttempts = 0;
  157. const Containers::SceneManifest& manifest = scene.GetManifest();
  158. auto view = Containers::MakeDerivedFilterView<DataTypes::IScriptProcessorRule>(manifest.GetValueStorage());
  159. for (const auto& scriptItem : view)
  160. {
  161. AZ::IO::FixedMaxPath scriptFilename(scriptItem.GetScriptFilename());
  162. if (scriptFilename.empty())
  163. {
  164. AZ_Warning("scene", false, "Skipping an empty script filename in (%s)", scene.GetManifestFilename().c_str());
  165. continue;
  166. }
  167. ++scriptDiscoveryAttempts;
  168. fallbackResult = (scriptItem.GetScriptProcessorFallbackLogic() == DataTypes::ScriptProcessorFallbackLogic::ContinueBuild) ?
  169. Events::ProcessingResult::Ignored : Events::ProcessingResult::Failure;
  170. // check for file exist via absolute path
  171. if (!IO::FileIOBase::GetInstance()->Exists(scriptFilename.c_str()))
  172. {
  173. // get project folder
  174. auto settingsRegistry = AZ::SettingsRegistry::Get();
  175. AZ::IO::FixedMaxPath projectPath;
  176. if (!settingsRegistry->Get(projectPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectPath))
  177. {
  178. AZ_Error("scene", false, "With (%s) could not find Project Path during script discovery.",
  179. scene.GetManifestFilename().c_str());
  180. return false;
  181. }
  182. // check for script in the project folder
  183. AZ::IO::FixedMaxPath projectScriptPath = projectPath / scriptFilename;
  184. if (!IO::FileIOBase::GetInstance()->Exists(projectScriptPath.c_str()))
  185. {
  186. AZ_Warning("scene", false, "Skipping a missing script (%s) in manifest file (%s)",
  187. scriptFilename.c_str(),
  188. scene.GetManifestFilename().c_str());
  189. continue;
  190. }
  191. scriptFilename = AZStd::move(projectScriptPath);
  192. }
  193. scriptPath = scriptFilename.c_str();
  194. break;
  195. }
  196. if (scriptPath.empty())
  197. {
  198. AZ_Warning("scene", scriptDiscoveryAttempts == 0,
  199. "The scene manifest (%s) attempted to use script rule, but no script file path could be found.",
  200. scene.GetManifestFilename().c_str());
  201. return false;
  202. }
  203. // already prepared the Python VM?
  204. if (m_editorPythonEventsInterface)
  205. {
  206. return true;
  207. }
  208. // lazy load the Python interface
  209. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get();
  210. if (editorPythonEventsInterface->IsPythonActive() == false)
  211. {
  212. const bool silenceWarnings = false;
  213. if (editorPythonEventsInterface->StartPython(silenceWarnings) == false)
  214. {
  215. editorPythonEventsInterface = nullptr;
  216. }
  217. }
  218. // both Python and the script need to be ready
  219. if (editorPythonEventsInterface == nullptr)
  220. {
  221. AZ_Warning("scene", false,
  222. "The scene manifest (%s) attempted to prepare Python but Python can not start",
  223. scene.GetManifestFilename().c_str());
  224. return false;
  225. }
  226. m_editorPythonEventsInterface = editorPythonEventsInterface;
  227. return true;
  228. }
  229. void ScriptProcessorRuleBehavior::UnloadPython()
  230. {
  231. if (m_editorPythonEventsInterface)
  232. {
  233. const bool silenceWarnings = true;
  234. m_editorPythonEventsInterface->StopPython(silenceWarnings);
  235. m_editorPythonEventsInterface = nullptr;
  236. }
  237. }
  238. bool ScriptProcessorRuleBehavior::DoPrepareForExport(Events::PreExportEventContext& context)
  239. {
  240. using namespace AzToolsFramework;
  241. AZStd::string scriptPath;
  242. auto executeCallback = [&context, &scriptPath]()
  243. {
  244. // set up script's hook callback
  245. EditorPythonRunnerRequestBus::Broadcast(&EditorPythonRunnerRequestBus::Events::ExecuteByFilename,
  246. scriptPath.c_str());
  247. // call script's callback to allow extra products
  248. ExportProductList extraProducts;
  249. ScriptBuildingNotificationBus::BroadcastResult(extraProducts, &ScriptBuildingNotificationBus::Events::OnPrepareForExport,
  250. context.GetScene(),
  251. context.GetOutputDirectory(),
  252. context.GetPlatformIdentifier(),
  253. context.GetProductList()
  254. );
  255. // add new products
  256. for (const auto& product : extraProducts.GetProducts())
  257. {
  258. context.GetProductList().AddProduct(
  259. product.m_filename,
  260. product.m_id,
  261. product.m_assetType,
  262. product.m_lod,
  263. product.m_subId,
  264. product.m_dependencyFlags);
  265. }
  266. };
  267. [[maybe_unused]] Events::ProcessingResult fallbackResult;
  268. if (LoadPython(context.GetScene(), scriptPath, fallbackResult))
  269. {
  270. EditorPythonConsoleNotificationHandler logger;
  271. m_editorPythonEventsInterface->ExecuteWithLock(executeCallback);
  272. }
  273. return true;
  274. }
  275. void ScriptProcessorRuleBehavior::Reflect(ReflectContext* context)
  276. {
  277. ScriptBuildingNotificationBusHandler::Reflect(context);
  278. SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context);
  279. if (serializeContext)
  280. {
  281. serializeContext->Class<ScriptProcessorRuleBehavior, BehaviorComponent>()->Version(1);
  282. }
  283. }
  284. Events::ProcessingResult ScriptProcessorRuleBehavior::UpdateManifest(
  285. Containers::Scene& scene,
  286. Events::AssetImportRequest::ManifestAction action,
  287. [[maybe_unused]] Events::AssetImportRequest::RequestingApplication requester)
  288. {
  289. using namespace AzToolsFramework;
  290. if (action != ManifestAction::Update)
  291. {
  292. return Events::ProcessingResult::Ignored;
  293. }
  294. Events::ProcessingResult fallbackResult;
  295. AZStd::string scriptPath;
  296. if (LoadPython(scene, scriptPath, fallbackResult))
  297. {
  298. AZStd::string manifestUpdate;
  299. auto executeCallback = [&scene, &manifestUpdate, &scriptPath]()
  300. {
  301. EditorPythonRunnerRequestBus::Broadcast(&EditorPythonRunnerRequestBus::Events::ExecuteByFilename,
  302. scriptPath.c_str());
  303. ScriptBuildingNotificationBus::BroadcastResult(manifestUpdate, &ScriptBuildingNotificationBus::Events::OnUpdateManifest,
  304. scene);
  305. };
  306. EditorPythonConsoleNotificationHandler logger;
  307. m_editorPythonEventsInterface->ExecuteWithLock(executeCallback);
  308. // if the returned scene manifest is empty then ignore the script update
  309. if (manifestUpdate.empty())
  310. {
  311. return Events::ProcessingResult::Ignored;
  312. }
  313. // attempt to load the manifest string back to a JSON-scene-manifest
  314. auto sceneManifestLoader = AZStd::make_unique<AZ::SceneAPI::Containers::SceneManifest>();
  315. auto loadOutcome = sceneManifestLoader->LoadFromString(manifestUpdate);
  316. if (loadOutcome.IsSuccess())
  317. {
  318. scene.GetManifest().Clear();
  319. for (size_t entryIndex = 0; entryIndex < sceneManifestLoader->GetEntryCount(); ++entryIndex)
  320. {
  321. scene.GetManifest().AddEntry(sceneManifestLoader->GetValue(entryIndex));
  322. }
  323. return Events::ProcessingResult::Success;
  324. }
  325. else
  326. {
  327. // if the manifest was not updated by the script, then return back the fallback result
  328. return fallbackResult;
  329. }
  330. }
  331. return Events::ProcessingResult::Ignored;
  332. }
  333. void ScriptProcessorRuleBehavior::GetManifestDependencyPaths(AZStd::vector<AZStd::string>& paths)
  334. {
  335. paths.emplace_back("/scriptFilename");
  336. }
  337. } // namespace AZ