ProceduralAssetHandler.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 <PrefabGroup/ProceduralAssetHandler.h>
  9. #include <AzCore/Asset/AssetTypeInfoBus.h>
  10. #include <AzCore/Serialization/Json/JsonUtils.h>
  11. #include <AzCore/std/smart_ptr/make_shared.h>
  12. #include <AzFramework/FileFunc/FileFunc.h>
  13. #include <AzQtComponents/Components/Widgets/FileDialog.h>
  14. #include <AzToolsFramework/AssetBrowser/AssetBrowserBus.h>
  15. #include <AzToolsFramework/AssetBrowser/AssetBrowserEntry.h>
  16. #include <AzToolsFramework/Prefab/PrefabLoaderInterface.h>
  17. #include <AzToolsFramework/Prefab/PrefabSystemComponentInterface.h>
  18. #include <AzToolsFramework/Prefab/Procedural/ProceduralPrefabAsset.h>
  19. #include <QMenu>
  20. namespace AZ::Prefab
  21. {
  22. // AssetTypeInfoHandler
  23. class PrefabGroupAssetHandler::AssetTypeInfoHandler final
  24. : public AZ::AssetTypeInfoBus::Handler
  25. , protected AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler
  26. {
  27. public:
  28. AZ_CLASS_ALLOCATOR(AssetTypeInfoHandler, AZ::SystemAllocator);
  29. AssetTypeInfoHandler();
  30. ~AssetTypeInfoHandler() override;
  31. AZ::Data::AssetType GetAssetType() const override;
  32. const char* GetAssetTypeDisplayName() const override;
  33. const char* GetGroup() const override;
  34. const char* GetBrowserIcon() const override;
  35. void GetAssetTypeExtensions(AZStd::vector<AZStd::string>& extensions) override;
  36. // AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler
  37. void AddContextMenuActions(QWidget* caller, QMenu* menu, const AZStd::vector<const AzToolsFramework::AssetBrowser::AssetBrowserEntry*>& entries) override;
  38. bool SaveAsAuthoredPrefab(const AZ::Data::AssetId& assetId, const char* destinationFilename);
  39. };
  40. PrefabGroupAssetHandler::AssetTypeInfoHandler::AssetTypeInfoHandler()
  41. {
  42. AZ::AssetTypeInfoBus::Handler::BusConnect(azrtti_typeid<ProceduralPrefabAsset>());
  43. AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect();
  44. }
  45. PrefabGroupAssetHandler::AssetTypeInfoHandler::~AssetTypeInfoHandler()
  46. {
  47. AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect();
  48. AZ::AssetTypeInfoBus::Handler::BusDisconnect(azrtti_typeid<ProceduralPrefabAsset>());
  49. }
  50. AZ::Data::AssetType PrefabGroupAssetHandler::AssetTypeInfoHandler::GetAssetType() const
  51. {
  52. return azrtti_typeid<ProceduralPrefabAsset>();
  53. }
  54. const char* PrefabGroupAssetHandler::AssetTypeInfoHandler::GetAssetTypeDisplayName() const
  55. {
  56. return "Procedural Prefab";
  57. }
  58. const char* PrefabGroupAssetHandler::AssetTypeInfoHandler::GetGroup() const
  59. {
  60. return "Procedural Prefab";
  61. }
  62. const char* PrefabGroupAssetHandler::AssetTypeInfoHandler::GetBrowserIcon() const
  63. {
  64. return "Icons/AssetBrowser/ProcPrefab_80.svg";
  65. }
  66. void PrefabGroupAssetHandler::AssetTypeInfoHandler::GetAssetTypeExtensions(AZStd::vector<AZStd::string>& extensions)
  67. {
  68. extensions.push_back(PrefabGroupAssetHandler::s_Extension);
  69. }
  70. void PrefabGroupAssetHandler::AssetTypeInfoHandler::AddContextMenuActions(
  71. [[maybe_unused]] QWidget* caller,
  72. QMenu* menu,
  73. const AZStd::vector<const AzToolsFramework::AssetBrowser::AssetBrowserEntry*>& entries)
  74. {
  75. using namespace AzToolsFramework::AssetBrowser;
  76. auto entryIt = AZStd::find_if
  77. (
  78. entries.begin(),
  79. entries.end(),
  80. [](const AssetBrowserEntry* entry) -> bool
  81. {
  82. return entry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Product;
  83. }
  84. );
  85. if (entryIt == entries.end())
  86. {
  87. return;
  88. }
  89. else if ((*entryIt)->GetEntryType() == AssetBrowserEntry::AssetEntryType::Product)
  90. {
  91. const ProductAssetBrowserEntry* product = azrtti_cast<const ProductAssetBrowserEntry*>(*entryIt);
  92. if (product->GetAssetType() == azrtti_typeid<ProceduralPrefabAsset>())
  93. {
  94. AZ::Data::AssetId assetId = product->GetAssetId();
  95. menu->addAction("Save as Prefab...", [assetId, this]()
  96. {
  97. QString filePath = AzQtComponents::FileDialog::GetSaveFileName(nullptr, QString("Save to file"), "", QString("Prefab file (*.prefab)"));
  98. if (filePath.isEmpty())
  99. {
  100. return;
  101. }
  102. if (SaveAsAuthoredPrefab(assetId, filePath.toUtf8().data()))
  103. {
  104. AZ_Printf("Prefab", "Prefab was saved to a .prefab file %s", filePath.toUtf8().data());
  105. }
  106. });
  107. }
  108. }
  109. }
  110. bool PrefabGroupAssetHandler::AssetTypeInfoHandler::SaveAsAuthoredPrefab(const AZ::Data::AssetId& assetId, const char* destinationFilename)
  111. {
  112. using namespace AzToolsFramework::Prefab;
  113. using namespace AZ::Data;
  114. auto procPrefabAsset = AssetManager::Instance().GetAsset<ProceduralPrefabAsset>(assetId, AssetLoadBehavior::Default);
  115. const auto status = AssetManager::Instance().BlockUntilLoadComplete(procPrefabAsset);
  116. if (status != AssetData::AssetStatus::Ready)
  117. {
  118. return false;
  119. }
  120. auto* prefabLoaderInterface = AZ::Interface<PrefabLoaderInterface>::Get();
  121. if (!prefabLoaderInterface)
  122. {
  123. return false;
  124. }
  125. const auto templateId = procPrefabAsset.GetAs<ProceduralPrefabAsset>()->GetTemplateId();
  126. AZStd::string outputJson;
  127. if (prefabLoaderInterface->SaveTemplateToString(templateId, outputJson) == false)
  128. {
  129. return false;
  130. }
  131. const auto fileMode = AZ::IO::OpenMode::ModeWrite | AZ::IO::OpenMode::ModeCreatePath | AZ::IO::OpenMode::ModeText;
  132. AZ::IO::FileIOStream outputFileStream;
  133. if (outputFileStream.Open(destinationFilename, fileMode) == false)
  134. {
  135. return false;
  136. }
  137. outputFileStream.Write(outputJson.size(), outputJson.data());
  138. return true;
  139. }
  140. // PrefabGroupAssetHandler
  141. AZStd::string_view PrefabGroupAssetHandler::s_Extension{ "procprefab" };
  142. PrefabGroupAssetHandler::PrefabGroupAssetHandler()
  143. {
  144. auto assetCatalog = AZ::Data::AssetCatalogRequestBus::FindFirstHandler();
  145. if (assetCatalog)
  146. {
  147. assetCatalog->EnableCatalogForAsset(azrtti_typeid<ProceduralPrefabAsset>());
  148. assetCatalog->AddExtension(s_Extension.data());
  149. }
  150. if (AZ::Data::AssetManager::IsReady())
  151. {
  152. AZ::Data::AssetManager::Instance().RegisterHandler(this, azrtti_typeid<ProceduralPrefabAsset>());
  153. }
  154. m_assetTypeInfoHandler = AZStd::make_shared<AssetTypeInfoHandler>();
  155. }
  156. PrefabGroupAssetHandler::~PrefabGroupAssetHandler()
  157. {
  158. m_assetTypeInfoHandler.reset();
  159. if (AZ::Data::AssetManager::IsReady())
  160. {
  161. AZ::Data::AssetManager::Instance().UnregisterHandler(this);
  162. }
  163. }
  164. AZ::Data::AssetData* PrefabGroupAssetHandler::CreateAsset([[maybe_unused]] const AZ::Data::AssetId& id, const AZ::Data::AssetType& type)
  165. {
  166. if (type != azrtti_typeid<ProceduralPrefabAsset>())
  167. {
  168. AZ_Error("prefab", false, "Invalid asset type! Only handle 'ProceduralPrefabAsset'");
  169. return nullptr;
  170. }
  171. return aznew ProceduralPrefabAsset{};
  172. }
  173. void PrefabGroupAssetHandler::DestroyAsset(AZ::Data::AssetData* ptr)
  174. {
  175. // Note: the PrefabLoaderInterface will handle the lifetime of the Prefab Template
  176. delete ptr;
  177. }
  178. void PrefabGroupAssetHandler::GetHandledAssetTypes(AZStd::vector<AZ::Data::AssetType>& assetTypes)
  179. {
  180. assetTypes.push_back(azrtti_typeid<ProceduralPrefabAsset>());
  181. }
  182. AZ::Data::AssetHandler::LoadResult PrefabGroupAssetHandler::LoadAssetData(
  183. const AZ::Data::Asset<AZ::Data::AssetData>& asset,
  184. AZStd::shared_ptr<AZ::Data::AssetDataStream> stream,
  185. [[maybe_unused]] const AZ::Data::AssetFilterCB& assetLoadFilterCB)
  186. {
  187. using namespace AzToolsFramework::Prefab;
  188. auto* proceduralPrefabAsset = asset.GetAs<ProceduralPrefabAsset>();
  189. if (!proceduralPrefabAsset)
  190. {
  191. AZ_Error("prefab", false, "This should be a ProceduralPrefabAsset type, as this is the only type we process!");
  192. return LoadResult::Error;
  193. }
  194. AZStd::string buffer;
  195. buffer.resize(stream->GetLoadedSize());
  196. stream->Read(stream->GetLoadedSize(), buffer.data());
  197. auto jsonOutcome = AZ::JsonSerializationUtils::ReadJsonString(buffer);
  198. if (jsonOutcome.IsSuccess() == false)
  199. {
  200. AZ_Error("prefab", false, "Asset JSON failed to compile %s", jsonOutcome.GetError().c_str());
  201. return LoadResult::Error;
  202. }
  203. const auto& jsonDoc = jsonOutcome.GetValue();
  204. if (jsonDoc.IsObject() == false)
  205. {
  206. return LoadResult::Error;
  207. }
  208. if (jsonDoc.FindMember("Source") == jsonDoc.MemberEnd())
  209. {
  210. return LoadResult::Error;
  211. }
  212. const auto& templateName = jsonDoc["Source"];
  213. AZStd::string stringJson;
  214. auto stringOutcome = AZ::JsonSerializationUtils::WriteJsonString(jsonDoc, stringJson);
  215. if (stringOutcome.IsSuccess() == false)
  216. {
  217. AZ_Error("prefab", false, "Could not write to JSON string %s", stringOutcome.GetError().c_str());
  218. return LoadResult::Error;
  219. }
  220. // prepare the template
  221. auto* prefabLoaderInterface = AZ::Interface<PrefabLoaderInterface>::Get();
  222. if (!prefabLoaderInterface)
  223. {
  224. return LoadResult::Error;
  225. }
  226. auto templateId = prefabLoaderInterface->LoadTemplateFromString(stringJson.data(), templateName.GetString());
  227. if (templateId == InvalidTemplateId)
  228. {
  229. return LoadResult::Error;
  230. }
  231. proceduralPrefabAsset->SetTemplateId(templateId);
  232. proceduralPrefabAsset->SetTemplateName(templateName.GetString());
  233. return LoadResult::LoadComplete;
  234. }
  235. AZStd::unique_ptr<PrefabGroupAssetHandler> s_PrefabGroupAssetHandler;
  236. }