ScriptProcessorRuleBehavior.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 <AzToolsFramework/Debug/TraceContext.h>
  21. #include <Entity/EntityUtilityComponent.h>
  22. #include <Prefab/PrefabSystemComponentInterface.h>
  23. #include <Prefab/PrefabSystemScriptingBus.h>
  24. #include <SceneAPI/SceneCore/Containers/Scene.h>
  25. #include <SceneAPI/SceneCore/Containers/SceneGraph.h>
  26. #include <SceneAPI/SceneCore/Containers/SceneManifest.h>
  27. #include <SceneAPI/SceneCore/Containers/Utilities/Filters.h>
  28. #include <SceneAPI/SceneCore/Containers/Views/FilterIterator.h>
  29. #include <SceneAPI/SceneCore/Containers/Views/PairIterator.h>
  30. #include <SceneAPI/SceneData/Rules/ScriptProcessorRule.h>
  31. #include <SceneAPI/SceneCore/Utilities/Reporting.h>
  32. #include <SceneAPI/SceneCore/Events/ExportProductList.h>
  33. namespace AZ::SceneAPI::Behaviors
  34. {
  35. class EditorPythonConsoleNotificationHandler final
  36. : protected AzToolsFramework::EditorPythonConsoleNotificationBus::Handler
  37. {
  38. public:
  39. EditorPythonConsoleNotificationHandler()
  40. {
  41. BusConnect();
  42. }
  43. ~EditorPythonConsoleNotificationHandler()
  44. {
  45. BusDisconnect();
  46. }
  47. ////////////////////////////////////////////////////////////////////////////////////////////
  48. // AzToolsFramework::EditorPythonConsoleNotifications
  49. void OnTraceMessage([[maybe_unused]] AZStd::string_view message) override
  50. {
  51. using namespace AZ::SceneAPI::Utilities;
  52. AZ_TracePrintf(LogWindow, "%.*s \n", AZ_STRING_ARG(message));
  53. }
  54. void OnErrorMessage([[maybe_unused]] AZStd::string_view message) override
  55. {
  56. using namespace AZ::SceneAPI::Utilities;
  57. AZ_TracePrintf(ErrorWindow, "[ERROR] %.*s \n", AZ_STRING_ARG(message));
  58. }
  59. void OnExceptionMessage([[maybe_unused]] AZStd::string_view message) override
  60. {
  61. using namespace AZ::SceneAPI::Utilities;
  62. AZ_TracePrintf(ErrorWindow, "[EXCEPTION] %.*s \n", AZ_STRING_ARG(message));
  63. }
  64. };
  65. using ExportProductList = AZ::SceneAPI::Events::ExportProductList;
  66. // a event bus to signal during scene building
  67. struct ScriptBuildingNotifications
  68. : public AZ::EBusTraits
  69. {
  70. virtual AZStd::string OnUpdateManifest(Containers::Scene& scene) = 0;
  71. virtual ExportProductList OnPrepareForExport(
  72. const Containers::Scene& scene,
  73. AZStd::string_view outputDirectory,
  74. AZStd::string_view platformIdentifier,
  75. const ExportProductList& productList) = 0;
  76. };
  77. using ScriptBuildingNotificationBus = AZ::EBus<ScriptBuildingNotifications>;
  78. // a back end to handle scene builder events for a script
  79. struct ScriptBuildingNotificationBusHandler final
  80. : public ScriptBuildingNotificationBus::Handler
  81. , public AZ::BehaviorEBusHandler
  82. {
  83. AZ_EBUS_BEHAVIOR_BINDER(
  84. ScriptBuildingNotificationBusHandler,
  85. "{DF2B51DE-A4D0-4139-B5D0-DF185832380D}",
  86. AZ::SystemAllocator,
  87. OnUpdateManifest,
  88. OnPrepareForExport);
  89. virtual ~ScriptBuildingNotificationBusHandler() = default;
  90. AZStd::string OnUpdateManifest(Containers::Scene& scene) override
  91. {
  92. AZStd::string result;
  93. CallResult(result, FN_OnUpdateManifest, scene);
  94. ScriptBuildingNotificationBusHandler::BusDisconnect();
  95. return result;
  96. }
  97. ExportProductList OnPrepareForExport(
  98. const Containers::Scene& scene,
  99. AZStd::string_view outputDirectory,
  100. AZStd::string_view platformIdentifier,
  101. const ExportProductList& productList) override
  102. {
  103. ExportProductList result;
  104. CallResult(result, FN_OnPrepareForExport, scene, outputDirectory, platformIdentifier, productList);
  105. ScriptBuildingNotificationBusHandler::BusDisconnect();
  106. return result;
  107. }
  108. static void Reflect(AZ::ReflectContext* context)
  109. {
  110. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  111. {
  112. behaviorContext->EBus<ScriptBuildingNotificationBus>("ScriptBuildingNotificationBus")
  113. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  114. ->Attribute(AZ::Script::Attributes::Module, "scene")
  115. ->Handler<ScriptBuildingNotificationBusHandler>()
  116. ->Event("OnUpdateManifest", &ScriptBuildingNotificationBus::Events::OnUpdateManifest)
  117. ->Event("OnPrepareForExport", &ScriptBuildingNotificationBus::Events::OnPrepareForExport);
  118. }
  119. }
  120. };
  121. struct ScriptProcessorRuleBehavior::ExportEventHandler final
  122. : public AZ::SceneAPI::SceneCore::ExportingComponent
  123. {
  124. using PreExportEventContextFunction = AZStd::function<bool(Events::PreExportEventContext&)>;
  125. PreExportEventContextFunction m_preExportEventContextFunction;
  126. ExportEventHandler(PreExportEventContextFunction preExportEventContextFunction)
  127. : m_preExportEventContextFunction(preExportEventContextFunction)
  128. {
  129. BindToCall(&ExportEventHandler::PrepareForExport);
  130. AZ::SceneAPI::SceneCore::ExportingComponent::Activate();
  131. }
  132. ~ExportEventHandler()
  133. {
  134. AZ::SceneAPI::SceneCore::ExportingComponent::Deactivate();
  135. }
  136. // this allows a Python script to add product assets on "scene export"
  137. Events::ProcessingResult PrepareForExport(Events::PreExportEventContext& context)
  138. {
  139. return m_preExportEventContextFunction(context) ? Events::ProcessingResult::Success : Events::ProcessingResult::Failure;
  140. }
  141. };
  142. void ScriptProcessorRuleBehavior::Activate()
  143. {
  144. Events::AssetImportRequestBus::Handler::BusConnect();
  145. m_exportEventHandler = AZStd::make_shared<ExportEventHandler>([this](Events::PreExportEventContext& context)
  146. {
  147. return this->DoPrepareForExport(context);
  148. });
  149. }
  150. void ScriptProcessorRuleBehavior::Deactivate()
  151. {
  152. m_exportEventHandler.reset();
  153. Events::AssetImportRequestBus::Handler::BusDisconnect();
  154. UnloadPython();
  155. }
  156. bool ScriptProcessorRuleBehavior::LoadPython(const AZ::SceneAPI::Containers::Scene& scene, AZStd::string& scriptPath)
  157. {
  158. int scriptDiscoveryAttempts = 0;
  159. const AZ::SceneAPI::Containers::SceneManifest& manifest = scene.GetManifest();
  160. auto view = Containers::MakeDerivedFilterView<DataTypes::IScriptProcessorRule>(manifest.GetValueStorage());
  161. for (const auto& scriptItem : view)
  162. {
  163. AZ::IO::FixedMaxPath scriptFilename(scriptItem.GetScriptFilename());
  164. if (scriptFilename.empty())
  165. {
  166. AZ_Warning("scene", false, "Skipping an empty script filename in (%s)", scene.GetManifestFilename().c_str());
  167. continue;
  168. }
  169. ++scriptDiscoveryAttempts;
  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. if (LoadPython(context.GetScene(), scriptPath))
  268. {
  269. EditorPythonConsoleNotificationHandler logger;
  270. m_editorPythonEventsInterface->ExecuteWithLock(executeCallback);
  271. }
  272. return true;
  273. }
  274. void ScriptProcessorRuleBehavior::Reflect(ReflectContext* context)
  275. {
  276. ScriptBuildingNotificationBusHandler::Reflect(context);
  277. SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context);
  278. if (serializeContext)
  279. {
  280. serializeContext->Class<ScriptProcessorRuleBehavior, BehaviorComponent>()->Version(1);
  281. }
  282. }
  283. Events::ProcessingResult ScriptProcessorRuleBehavior::UpdateManifest(
  284. Containers::Scene& scene,
  285. Events::AssetImportRequest::ManifestAction action,
  286. [[maybe_unused]] Events::AssetImportRequest::RequestingApplication requester)
  287. {
  288. using namespace AzToolsFramework;
  289. if (action != ManifestAction::Update)
  290. {
  291. return Events::ProcessingResult::Ignored;
  292. }
  293. AZStd::string scriptPath;
  294. if (LoadPython(scene, scriptPath))
  295. {
  296. AZStd::string manifestUpdate;
  297. auto executeCallback = [&scene, &manifestUpdate, &scriptPath]()
  298. {
  299. EditorPythonRunnerRequestBus::Broadcast(&EditorPythonRunnerRequestBus::Events::ExecuteByFilename,
  300. scriptPath.c_str());
  301. ScriptBuildingNotificationBus::BroadcastResult(manifestUpdate, &ScriptBuildingNotificationBus::Events::OnUpdateManifest,
  302. scene);
  303. };
  304. EditorPythonConsoleNotificationHandler logger;
  305. m_editorPythonEventsInterface->ExecuteWithLock(executeCallback);
  306. EntityUtilityBus::Broadcast(&EntityUtilityBus::Events::ResetEntityContext);
  307. AZ::Interface<Prefab::PrefabSystemComponentInterface>::Get()->RemoveAllTemplates();
  308. // attempt to load the manifest string back to a JSON-scene-manifest
  309. auto sceneManifestLoader = AZStd::make_unique<AZ::SceneAPI::Containers::SceneManifest>();
  310. auto loadOutcome = sceneManifestLoader->LoadFromString(manifestUpdate);
  311. if (loadOutcome.IsSuccess())
  312. {
  313. scene.GetManifest().Clear();
  314. for (size_t entryIndex = 0; entryIndex < sceneManifestLoader->GetEntryCount(); ++entryIndex)
  315. {
  316. scene.GetManifest().AddEntry(sceneManifestLoader->GetValue(entryIndex));
  317. }
  318. return Events::ProcessingResult::Success;
  319. }
  320. }
  321. return Events::ProcessingResult::Ignored;
  322. }
  323. void ScriptProcessorRuleBehavior::GetManifestDependencyPaths(AZStd::vector<AZStd::string>& paths)
  324. {
  325. paths.emplace_back("/scriptFilename");
  326. }
  327. } // namespace AZ