ScriptProcessorRuleBehavior.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 <AzCore/std/string/regex.h>
  16. #include <AzFramework/API/ApplicationAPI.h>
  17. #include <AzFramework/Asset/AssetSystemComponent.h>
  18. #include <AzFramework/StringFunc/StringFunc.h>
  19. #include <AzToolsFramework/API/EditorPythonConsoleBus.h>
  20. #include <AzToolsFramework/API/EditorPythonRunnerRequestsBus.h>
  21. #include <SceneAPI/SceneCore/Containers/Scene.h>
  22. #include <SceneAPI/SceneCore/Containers/SceneGraph.h>
  23. #include <SceneAPI/SceneCore/Containers/SceneManifest.h>
  24. #include <SceneAPI/SceneCore/Containers/Utilities/Filters.h>
  25. #include <SceneAPI/SceneCore/Containers/Views/FilterIterator.h>
  26. #include <SceneAPI/SceneCore/Containers/Views/PairIterator.h>
  27. #include <SceneAPI/SceneData/Rules/ScriptProcessorRule.h>
  28. #include <SceneAPI/SceneCore/Utilities/Reporting.h>
  29. #include <SceneAPI/SceneCore/Events/ExportProductList.h>
  30. #include <SceneAPI/SceneCore/Events/AssetImportRequest.h>
  31. #include <SceneAPI/SceneCore/Events/ImportEventContext.h>
  32. namespace AZ::SceneAPI::Behaviors
  33. {
  34. class EditorPythonConsoleNotificationHandler final
  35. : protected AzToolsFramework::EditorPythonConsoleNotificationBus::Handler
  36. {
  37. public:
  38. EditorPythonConsoleNotificationHandler()
  39. {
  40. BusConnect();
  41. }
  42. ~EditorPythonConsoleNotificationHandler()
  43. {
  44. BusDisconnect();
  45. }
  46. ////////////////////////////////////////////////////////////////////////////////////////////
  47. // AzToolsFramework::EditorPythonConsoleNotifications
  48. void OnTraceMessage([[maybe_unused]] AZStd::string_view message) override
  49. {
  50. using namespace AZ::SceneAPI::Utilities;
  51. AZ_TracePrintf(LogWindow, "%.*s \n", AZ_STRING_ARG(message));
  52. }
  53. void OnErrorMessage([[maybe_unused]] AZStd::string_view message) override
  54. {
  55. using namespace AZ::SceneAPI::Utilities;
  56. AZ_TracePrintf(ErrorWindow, "[ERROR] %.*s \n", AZ_STRING_ARG(message));
  57. }
  58. void OnExceptionMessage([[maybe_unused]] AZStd::string_view message) override
  59. {
  60. using namespace AZ::SceneAPI::Utilities;
  61. AZ_TracePrintf(ErrorWindow, "[EXCEPTION] %.*s \n", AZ_STRING_ARG(message));
  62. }
  63. };
  64. using ExportProductList = AZ::SceneAPI::Events::ExportProductList;
  65. // a event bus to signal during scene building
  66. struct ScriptBuildingNotifications
  67. : public AZ::EBusTraits
  68. {
  69. virtual AZStd::string OnUpdateManifest(Containers::Scene& scene) = 0;
  70. virtual ExportProductList OnPrepareForExport(
  71. const Containers::Scene& scene,
  72. AZStd::string_view outputDirectory,
  73. AZStd::string_view platformIdentifier,
  74. const ExportProductList& productList) = 0;
  75. };
  76. using ScriptBuildingNotificationBus = AZ::EBus<ScriptBuildingNotifications>;
  77. // a back end to handle scene builder events for a script
  78. struct ScriptBuildingNotificationBusHandler final
  79. : public ScriptBuildingNotificationBus::Handler
  80. , public AZ::BehaviorEBusHandler
  81. {
  82. AZ_EBUS_BEHAVIOR_BINDER(
  83. ScriptBuildingNotificationBusHandler,
  84. "{DF2B51DE-A4D0-4139-B5D0-DF185832380D}",
  85. AZ::SystemAllocator,
  86. OnUpdateManifest,
  87. OnPrepareForExport);
  88. virtual ~ScriptBuildingNotificationBusHandler() = default;
  89. AZStd::string OnUpdateManifest(Containers::Scene& scene) override
  90. {
  91. ScriptScope onUpdateManifestScope(this);
  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. ScriptScope onPrepareForExportScope(this);
  104. ExportProductList result;
  105. CallResult(result, FN_OnPrepareForExport, scene, outputDirectory, platformIdentifier, productList);
  106. ScriptBuildingNotificationBusHandler::BusDisconnect();
  107. return result;
  108. }
  109. AZStd::atomic_int m_count = 1;
  110. static BehaviorEBusHandler* Create()
  111. {
  112. return aznew ScriptBuildingNotificationBusHandler();
  113. }
  114. static void Destroy(BehaviorEBusHandler* behaviorEBusHandler)
  115. {
  116. auto* handler =
  117. static_cast<ScriptBuildingNotificationBusHandler*>(behaviorEBusHandler);
  118. --handler->m_count;
  119. if (handler->m_count == 0)
  120. {
  121. delete handler;
  122. }
  123. }
  124. static void Reflect(AZ::ReflectContext* context)
  125. {
  126. if (AZ::BehaviorContext* behaviorContext = azrtti_cast<AZ::BehaviorContext*>(context))
  127. {
  128. behaviorContext->EBus<ScriptBuildingNotificationBus>("ScriptBuildingNotificationBus")
  129. ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation)
  130. ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All)
  131. ->Attribute(AZ::Script::Attributes::Module, "scene")
  132. ->Handler<ScriptBuildingNotificationBusHandler>(&ScriptBuildingNotificationBusHandler::Create, &ScriptBuildingNotificationBusHandler::Destroy)
  133. ->Event("OnUpdateManifest", &ScriptBuildingNotificationBus::Events::OnUpdateManifest)
  134. ->Event("OnPrepareForExport", &ScriptBuildingNotificationBus::Events::OnPrepareForExport);
  135. }
  136. }
  137. struct ScriptScope final
  138. {
  139. ScriptScope(ScriptBuildingNotificationBusHandler* self)
  140. : m_self(self)
  141. {
  142. m_self->m_count++;
  143. }
  144. ~ScriptScope()
  145. {
  146. m_self->m_count--;
  147. if (m_self->m_count == 0)
  148. {
  149. // the script released the handler (i.e. set to None)
  150. BehaviorEBusHandler* self = m_self;
  151. AZStd::function<void()> destroySelf = [self]()
  152. {
  153. ScriptBuildingNotificationBusHandler::Destroy(self);
  154. };
  155. // Delay to delete self until the end of the scene pipeline
  156. m_self->m_count = 1;
  157. AZ::SceneAPI::Events::AssetPostImportRequestBus::QueueBroadcast(
  158. &AZ::SceneAPI::Events::AssetPostImportRequestBus::Events::CallAfterSceneExport, destroySelf);
  159. }
  160. }
  161. ScriptBuildingNotificationBusHandler* m_self = {};
  162. };
  163. };
  164. struct ScriptProcessorRuleBehavior::EventHandler final
  165. : public AZ::SceneAPI::SceneCore::ExportingComponent
  166. {
  167. AZ_CLASS_ALLOCATOR(ScriptProcessorRuleBehavior::EventHandler, AZ::SystemAllocator)
  168. using PreExportEventContextFunction = AZStd::function<bool(Events::PreExportEventContext&)>;
  169. PreExportEventContextFunction m_preExportEventContextFunction;
  170. EventHandler(PreExportEventContextFunction preExportEventContextFunction)
  171. : m_preExportEventContextFunction(preExportEventContextFunction)
  172. {
  173. BindToCall(&EventHandler::PrepareForExport);
  174. BindToCall(&EventHandler::PreImportEventContext);
  175. AZ::SceneAPI::SceneCore::ExportingComponent::Activate();
  176. }
  177. ~EventHandler()
  178. {
  179. AZ::SceneAPI::SceneCore::ExportingComponent::Deactivate();
  180. }
  181. // this allows a Python script to add product assets on "scene export"
  182. Events::ProcessingResult PrepareForExport(Events::PreExportEventContext& context)
  183. {
  184. return m_preExportEventContextFunction(context) ? Events::ProcessingResult::Success : Events::ProcessingResult::Failure;
  185. }
  186. // used to detect that the "next" source scene is starting to be processed
  187. Events::ProcessingResult PreImportEventContext([[maybe_unused]] Events::PreImportEventContext& context)
  188. {
  189. m_pythonScriptStack.clear();
  190. return Events::ProcessingResult::Success;
  191. }
  192. AZStd::vector<AZStd::string> m_pythonScriptStack;
  193. };
  194. void ScriptProcessorRuleBehavior::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  195. {
  196. provided.push_back(AZ_CRC_CE("ScriptProcessorRuleBehavior"));
  197. }
  198. void ScriptProcessorRuleBehavior::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  199. {
  200. incompatible.push_back(AZ_CRC_CE("ScriptProcessorRuleBehavior"));
  201. }
  202. void ScriptProcessorRuleBehavior::Activate()
  203. {
  204. Events::AssetImportRequestBus::Handler::BusConnect();
  205. m_eventHandler = AZStd::make_shared<EventHandler>([this](Events::PreExportEventContext& context)
  206. {
  207. return this->DoPrepareForExport(context);
  208. });
  209. }
  210. void ScriptProcessorRuleBehavior::Deactivate()
  211. {
  212. m_eventHandler.reset();
  213. Events::AssetImportRequestBus::Handler::BusDisconnect();
  214. UnloadPython();
  215. }
  216. AZStd::optional<AZStd::string> ScriptProcessorRuleBehavior::FindMatchingDefaultScript(const AZ::SceneAPI::Containers::Scene& scene)
  217. {
  218. AZStd::optional<AZ::SceneAPI::Events::ScriptConfig> scriptConfig;
  219. AZ::SceneAPI::Events::ScriptConfigEventBus::BroadcastResult(
  220. scriptConfig,
  221. &AZ::SceneAPI::Events::ScriptConfigEventBus::Events::MatchesScriptConfig,
  222. scene.GetSourceFilename());
  223. if (scriptConfig)
  224. {
  225. return AZStd::make_optional(scriptConfig.value().m_scriptPath.c_str());
  226. }
  227. return AZStd::nullopt;
  228. }
  229. AZStd::optional<AZStd::string> ScriptProcessorRuleBehavior::FindManifestScript(const AZ::SceneAPI::Containers::Scene& scene, Events::ProcessingResult& fallbackResult)
  230. {
  231. using namespace AZ::SceneAPI;
  232. AZStd::string scriptPath;
  233. fallbackResult = Events::ProcessingResult::Failure;
  234. int scriptDiscoveryAttempts = 0;
  235. const Containers::SceneManifest& manifest = scene.GetManifest();
  236. auto view = Containers::MakeDerivedFilterView<DataTypes::IScriptProcessorRule>(manifest.GetValueStorage());
  237. for (const auto& scriptItem : view)
  238. {
  239. AZ::IO::FixedMaxPath scriptFilename(scriptItem.GetScriptFilename());
  240. if (scriptFilename.empty())
  241. {
  242. AZ_Warning("scene", false, "Skipping an empty script filename in (%s)", scene.GetManifestFilename().c_str());
  243. continue;
  244. }
  245. ++scriptDiscoveryAttempts;
  246. fallbackResult = (scriptItem.GetScriptProcessorFallbackLogic() == DataTypes::ScriptProcessorFallbackLogic::ContinueBuild) ?
  247. Events::ProcessingResult::Ignored : Events::ProcessingResult::Failure;
  248. // check for file exist via absolute path
  249. if (!IO::FileIOBase::GetInstance()->Exists(scriptFilename.c_str()))
  250. {
  251. // get project folder
  252. auto settingsRegistry = AZ::SettingsRegistry::Get();
  253. AZ::IO::FixedMaxPath projectPath;
  254. if (!settingsRegistry->Get(projectPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_ProjectPath))
  255. {
  256. AZ_Error("scene", false, "With (%s) could not find Project Path during script discovery.",
  257. scene.GetManifestFilename().c_str());
  258. return AZStd::nullopt;
  259. }
  260. // check for script in the project folder
  261. AZ::IO::FixedMaxPath projectScriptPath = projectPath / scriptFilename;
  262. if (!IO::FileIOBase::GetInstance()->Exists(projectScriptPath.c_str()))
  263. {
  264. AZ_Warning("scene", false, "Skipping a missing script (%s) in manifest file (%s)",
  265. scriptFilename.c_str(),
  266. scene.GetManifestFilename().c_str());
  267. continue;
  268. }
  269. scriptFilename = AZStd::move(projectScriptPath);
  270. }
  271. scriptPath = scriptFilename.c_str();
  272. break;
  273. }
  274. if (scriptDiscoveryAttempts == 0)
  275. {
  276. if (!m_eventHandler->m_pythonScriptStack.empty())
  277. {
  278. scriptPath = m_eventHandler->m_pythonScriptStack.back();
  279. }
  280. }
  281. if (scriptPath.empty())
  282. {
  283. AZ_Warning("scene", scriptDiscoveryAttempts == 0,
  284. "The scene manifest (%s) attempted to use script rule, but no script file path could be found.",
  285. scene.GetManifestFilename().c_str());
  286. return AZStd::nullopt;
  287. }
  288. else
  289. {
  290. m_eventHandler->m_pythonScriptStack.push_back(scriptPath);
  291. }
  292. return AZStd::make_optional(AZStd::move(scriptPath));
  293. }
  294. bool ScriptProcessorRuleBehavior::LoadPython()
  295. {
  296. using namespace AZ::SceneAPI;
  297. // is the Python interface ready?
  298. if (m_pythonLoaded)
  299. {
  300. return true;
  301. }
  302. // lazy load the Python interface
  303. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get();
  304. // the Python interface is ready?
  305. if (editorPythonEventsInterface == nullptr)
  306. {
  307. return false;
  308. }
  309. m_pythonLoaded = editorPythonEventsInterface->IsPythonActive();
  310. if (m_pythonLoaded == false)
  311. {
  312. const bool silenceWarnings = false;
  313. m_pythonLoaded = editorPythonEventsInterface->StartPython(silenceWarnings);
  314. }
  315. // Python is ready?
  316. return m_pythonLoaded;
  317. }
  318. void ScriptProcessorRuleBehavior::UnloadPython()
  319. {
  320. if (m_pythonLoaded)
  321. {
  322. m_pythonLoaded = false;
  323. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get();
  324. if (editorPythonEventsInterface)
  325. {
  326. const bool silenceWarnings = true;
  327. editorPythonEventsInterface->StopPython(silenceWarnings);
  328. }
  329. }
  330. }
  331. void ScriptProcessorRuleBehavior::SignalScriptForExportEvent(Events::PreExportEventContext& context, AZStd::string& scriptPath)
  332. {
  333. auto executeCallback = [&context, &scriptPath]()
  334. {
  335. using namespace AzToolsFramework;
  336. // set up script's hook callback for "OnPrepareForExport"
  337. EditorPythonRunnerRequestBus::Broadcast(
  338. &EditorPythonRunnerRequestBus::Events::ExecuteByFilename,
  339. scriptPath.c_str());
  340. // call script's callback to allow extra products
  341. ExportProductList extraProducts;
  342. ScriptBuildingNotificationBus::BroadcastResult(
  343. extraProducts,
  344. &ScriptBuildingNotificationBus::Events::OnPrepareForExport,
  345. context.GetScene(),
  346. context.GetOutputDirectory(),
  347. context.GetPlatformIdentifier(),
  348. context.GetProductList()
  349. );
  350. // add new products
  351. for (const auto& product : extraProducts.GetProducts())
  352. {
  353. context.GetProductList().AddProduct(
  354. product.m_filename,
  355. product.m_id,
  356. product.m_assetType,
  357. product.m_lod,
  358. product.m_subId,
  359. product.m_dependencyFlags);
  360. }
  361. };
  362. EditorPythonConsoleNotificationHandler logger;
  363. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get();
  364. if (editorPythonEventsInterface)
  365. {
  366. editorPythonEventsInterface->ExecuteWithLock(executeCallback);
  367. }
  368. }
  369. bool ScriptProcessorRuleBehavior::DoPrepareForExport(Events::PreExportEventContext& context)
  370. {
  371. using namespace AzToolsFramework;
  372. if (LoadPython())
  373. {
  374. auto defaultScript = FindMatchingDefaultScript(context.GetScene());
  375. if (defaultScript)
  376. {
  377. SignalScriptForExportEvent(context, defaultScript.value());
  378. }
  379. [[maybe_unused]] Events::ProcessingResult fallbackResult;
  380. auto manifestScript = FindManifestScript(context.GetScene(), fallbackResult);
  381. if (manifestScript)
  382. {
  383. SignalScriptForExportEvent(context, manifestScript.value());
  384. }
  385. }
  386. else
  387. {
  388. AZ_Error("scene", false,
  389. "The scene (%s) attempted to prepare Python but Python can not start. "
  390. "Enable the EditorPythonBindings gem to fix this situation.",
  391. context.GetScene().GetSourceFilename().c_str());
  392. }
  393. return true;
  394. }
  395. void ScriptProcessorRuleBehavior::Reflect(ReflectContext* context)
  396. {
  397. ScriptBuildingNotificationBusHandler::Reflect(context);
  398. SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context);
  399. if (serializeContext)
  400. {
  401. serializeContext->Class<ScriptProcessorRuleBehavior, BehaviorComponent>()->Version(1);
  402. }
  403. }
  404. bool ScriptProcessorRuleBehavior::SignalScriptForUpdateManifest(Containers::Scene& scene, AZStd::string& manifestUpdate, AZStd::string& scriptPath)
  405. {
  406. using namespace AzToolsFramework;
  407. auto executeCallback = [&scene, &manifestUpdate, &scriptPath]()
  408. {
  409. // prepare a script for 'OnUpdateManifest' hook
  410. EditorPythonRunnerRequestBus::Broadcast(
  411. &EditorPythonRunnerRequestBus::Events::ExecuteByFilename,
  412. scriptPath.c_str());
  413. // signal the 'OnUpdateManifest' event for Python
  414. ScriptBuildingNotificationBus::BroadcastResult(
  415. manifestUpdate,
  416. &ScriptBuildingNotificationBus::Events::OnUpdateManifest,
  417. scene);
  418. };
  419. EditorPythonConsoleNotificationHandler logger;
  420. auto editorPythonEventsInterface = AZ::Interface<AzToolsFramework::EditorPythonEventsInterface>::Get();
  421. if (editorPythonEventsInterface)
  422. {
  423. editorPythonEventsInterface->ExecuteWithLock(executeCallback);
  424. }
  425. // if the returned scene manifest is empty then ignore the script update
  426. return (manifestUpdate.empty() == false);
  427. }
  428. Events::ProcessingResult ScriptProcessorRuleBehavior::UpdateManifest(
  429. Containers::Scene& scene,
  430. Events::AssetImportRequest::ManifestAction action,
  431. [[maybe_unused]] Events::AssetImportRequest::RequestingApplication requester)
  432. {
  433. using namespace AzToolsFramework;
  434. if (action != ManifestAction::Update)
  435. {
  436. return Events::ProcessingResult::Ignored;
  437. }
  438. if (LoadPython())
  439. {
  440. AZStd::string manifestUpdate;
  441. Events::ProcessingResult fallbackResult = Events::ProcessingResult::Failure;
  442. auto defaultScript = FindMatchingDefaultScript(scene);
  443. if (defaultScript)
  444. {
  445. SignalScriptForUpdateManifest(scene, manifestUpdate, defaultScript.value());
  446. }
  447. auto manifestScriptPath = FindManifestScript(scene, fallbackResult);
  448. if (manifestScriptPath)
  449. {
  450. SignalScriptForUpdateManifest(scene, manifestUpdate, manifestScriptPath.value());
  451. }
  452. // if the returned scene manifest is empty then ignore the script update
  453. if (manifestUpdate.empty())
  454. {
  455. return Events::ProcessingResult::Ignored;
  456. }
  457. // attempt to load the manifest string back to a JSON-scene-manifest
  458. auto sceneManifestLoader = AZStd::make_unique<AZ::SceneAPI::Containers::SceneManifest>();
  459. auto loadOutcome = sceneManifestLoader->LoadFromString(manifestUpdate);
  460. if (loadOutcome.IsSuccess())
  461. {
  462. scene.GetManifest().Clear();
  463. for (size_t entryIndex = 0; entryIndex < sceneManifestLoader->GetEntryCount(); ++entryIndex)
  464. {
  465. scene.GetManifest().AddEntry(sceneManifestLoader->GetValue(entryIndex));
  466. }
  467. return Events::ProcessingResult::Success;
  468. }
  469. else
  470. {
  471. // if the manifest was not updated by the script, then return back the fall back result
  472. return fallbackResult;
  473. }
  474. }
  475. else
  476. {
  477. AZ_Warning("scene", false,
  478. "The scene manifest (%s) attempted to prepare Python but Python can not start",
  479. scene.GetManifestFilename().c_str());
  480. }
  481. return Events::ProcessingResult::Ignored;
  482. }
  483. void ScriptProcessorRuleBehavior::GetManifestDependencyPaths(AZStd::vector<AZStd::string>& paths)
  484. {
  485. paths.emplace_back("/scriptFilename");
  486. }
  487. } // namespace AZ