MaterialAsset.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 <Atom/RPI.Reflect/Material/MaterialAsset.h>
  9. #include <Atom/RPI.Reflect/Material/MaterialPropertiesLayout.h>
  10. #include <Atom/RPI.Reflect/Material/MaterialFunctor.h>
  11. #include <Atom/RPI.Reflect/Material/MaterialVersionUpdate.h>
  12. #include <Atom/RPI.Reflect/Asset/AssetHandler.h>
  13. #include <Atom/RPI.Public/Shader/ShaderReloadDebugTracker.h>
  14. #include <AzCore/Asset/AssetSerializer.h>
  15. #include <AzCore/Serialization/SerializeContext.h>
  16. #include <AzCore/RTTI/BehaviorContext.h>
  17. #include <AzCore/Component/TickBus.h>
  18. namespace AZ
  19. {
  20. namespace RPI
  21. {
  22. void MaterialAsset::Reflect(ReflectContext* context)
  23. {
  24. if (auto* serializeContext = azrtti_cast<SerializeContext*>(context))
  25. {
  26. serializeContext->Class<MaterialAsset, AZ::Data::AssetData>()
  27. ->Version(15) // Forcing materials to be fully baked by builder
  28. ->Field("materialTypeAsset", &MaterialAsset::m_materialTypeAsset)
  29. ->Field("materialTypeVersion", &MaterialAsset::m_materialTypeVersion)
  30. ->Field("propertyValues", &MaterialAsset::m_propertyValues)
  31. ;
  32. }
  33. }
  34. MaterialAsset::MaterialAsset()
  35. {
  36. }
  37. MaterialAsset::~MaterialAsset()
  38. {
  39. AssetInitBus::Handler::BusDisconnect();
  40. }
  41. bool MaterialAsset::InitializeNonSerializedData()
  42. {
  43. if (m_isNonSerializedDataInitialized)
  44. {
  45. return true;
  46. }
  47. if (!m_materialTypeAsset.IsReady())
  48. {
  49. return false;
  50. }
  51. m_isNonSerializedDataInitialized = m_materialTypeAsset->InitializeNonSerializedData();
  52. return m_isNonSerializedDataInitialized;
  53. }
  54. const Data::Asset<MaterialTypeAsset>& MaterialAsset::GetMaterialTypeAsset() const
  55. {
  56. return m_materialTypeAsset;
  57. }
  58. const ShaderCollection& MaterialAsset::GetGeneralShaderCollection() const
  59. {
  60. return m_materialTypeAsset->GetGeneralShaderCollection();
  61. }
  62. const MaterialFunctorList& MaterialAsset::GetMaterialFunctors() const
  63. {
  64. return m_materialTypeAsset->GetMaterialFunctors();
  65. }
  66. const MaterialTypeAsset::MaterialPipelineMap& MaterialAsset::GetMaterialPipelinePayloads() const
  67. {
  68. return m_materialTypeAsset->GetMaterialPipelinePayloads();
  69. }
  70. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetMaterialSrgLayout(const SupervariantIndex& supervariantIndex) const
  71. {
  72. return m_materialTypeAsset->GetMaterialSrgLayout(supervariantIndex);
  73. }
  74. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetMaterialSrgLayout(const AZ::Name& supervariantName) const
  75. {
  76. return m_materialTypeAsset->GetMaterialSrgLayout(supervariantName);
  77. }
  78. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetMaterialSrgLayout() const
  79. {
  80. return m_materialTypeAsset->GetMaterialSrgLayout();
  81. }
  82. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetObjectSrgLayout(
  83. const SupervariantIndex& supervariantIndex, const ShaderCollection::Item::DrawItemType drawItemType) const
  84. {
  85. return m_materialTypeAsset->GetObjectSrgLayout(supervariantIndex, drawItemType);
  86. }
  87. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetObjectSrgLayout(
  88. const AZ::Name& supervariantName, const ShaderCollection::Item::DrawItemType drawItemType) const
  89. {
  90. return m_materialTypeAsset->GetObjectSrgLayout(supervariantName, drawItemType);
  91. }
  92. const RHI::Ptr<RHI::ShaderResourceGroupLayout>& MaterialAsset::GetObjectSrgLayout(
  93. const ShaderCollection::Item::DrawItemType drawItemType) const
  94. {
  95. return m_materialTypeAsset->GetObjectSrgLayout(drawItemType);
  96. }
  97. const MaterialPropertiesLayout* MaterialAsset::GetMaterialPropertiesLayout() const
  98. {
  99. return m_materialTypeAsset->GetMaterialPropertiesLayout();
  100. }
  101. void MaterialAsset::Finalize(AZStd::function<void(const char*)> reportWarning, AZStd::function<void(const char*)> reportError)
  102. {
  103. if (!reportWarning)
  104. {
  105. reportWarning = []([[maybe_unused]] const char* message)
  106. {
  107. AZ_Warning(s_debugTraceName, false, "%s", message);
  108. };
  109. }
  110. if (!reportError)
  111. {
  112. reportError = []([[maybe_unused]] const char* message)
  113. {
  114. AZ_Error(s_debugTraceName, false, "%s", message);
  115. };
  116. }
  117. // It is possible that the material type has had some properties renamed or otherwise updated. If that's the case,
  118. // and this material is still referencing the old property layout, we need to apply any auto updates to rename those
  119. // properties before using them to realign the property values.
  120. ApplyVersionUpdates(reportError);
  121. const MaterialPropertiesLayout* propertyLayout = GetMaterialPropertiesLayout();
  122. AZStd::vector<MaterialPropertyValue> finalizedPropertyValues(m_materialTypeAsset->GetDefaultPropertyValues().begin(), m_materialTypeAsset->GetDefaultPropertyValues().end());
  123. for (const auto& [name, value] : m_rawPropertyValues)
  124. {
  125. const MaterialPropertyIndex propertyIndex = propertyLayout->FindPropertyIndex(name);
  126. if (propertyIndex.IsValid())
  127. {
  128. const MaterialPropertyDescriptor* propertyDescriptor = propertyLayout->GetPropertyDescriptor(propertyIndex);
  129. if (value.Is<AZStd::string>() && propertyDescriptor->GetDataType() == MaterialPropertyDataType::Enum)
  130. {
  131. AZ::Name enumName = AZ::Name(value.GetValue<AZStd::string>());
  132. uint32_t enumValue = propertyDescriptor->GetEnumValue(enumName);
  133. if (enumValue == MaterialPropertyDescriptor::InvalidEnumValue)
  134. {
  135. reportWarning(AZStd::string::format("Material property name \"%s\" has invalid enum value \"%s\".", name.GetCStr(), enumName.GetCStr()).c_str());
  136. }
  137. else
  138. {
  139. finalizedPropertyValues[propertyIndex.GetIndex()] = enumValue;
  140. }
  141. }
  142. else if (value.Is<AZStd::string>() && propertyDescriptor->GetDataType() == MaterialPropertyDataType::Image)
  143. {
  144. // Here we assume that the material asset builder resolved any image source file paths to an ImageAsset reference.
  145. // So the only way a string could be present is if it's an empty image path reference, meaning no image should be bound.
  146. AZ_Assert(value.GetValue<AZStd::string>().empty(), "Material property '%s' references in image '%s'. Image file paths must be resolved by the material asset builder.");
  147. finalizedPropertyValues[propertyIndex.GetIndex()] = Data::Asset<ImageAsset>{};
  148. }
  149. else
  150. {
  151. // The material asset could be finalized sometime after the original JSON is loaded, and the material type might not have been available
  152. // at that time, so the data type would not be known for each property. So each raw property's type was based on what appeared in the JSON
  153. // and here we have the first opportunity to resolve that value with the actual type. For example, a float property could have been specified in
  154. // the JSON as 7 instead of 7.0, which is valid. Similarly, a Color and a Vector3 can both be specified as "[0.0,0.0,0.0]" in the JSON file.
  155. MaterialPropertyValue finalValue = value.CastToType(propertyDescriptor->GetStorageDataTypeId());
  156. if (ValidateMaterialPropertyDataType(finalValue.GetTypeId(), propertyDescriptor, reportError))
  157. {
  158. finalizedPropertyValues[propertyIndex.GetIndex()] = finalValue;
  159. }
  160. }
  161. }
  162. else
  163. {
  164. reportWarning(AZStd::string::format("Material property name \"%s\" is not found in the material properties layout and will not be used.", name.GetCStr()).c_str());
  165. }
  166. }
  167. m_propertyValues.swap(finalizedPropertyValues);
  168. }
  169. const AZStd::vector<MaterialPropertyValue>& MaterialAsset::GetPropertyValues() const
  170. {
  171. AZ_Assert(GetMaterialPropertiesLayout() && m_propertyValues.size() == GetMaterialPropertiesLayout()->GetPropertyCount(), "MaterialAsset should be finalized but does not have the right number of property values.");
  172. return m_propertyValues;
  173. }
  174. void MaterialAsset::SetReady()
  175. {
  176. m_status = AssetStatus::Ready;
  177. PostLoadInit();
  178. }
  179. bool MaterialAsset::PostLoadInit()
  180. {
  181. AssetInitBus::Handler::BusDisconnect();
  182. // Any MaterialAsset with invalid MaterialTypeAsset is not a successfully-loaded asset.
  183. return m_materialTypeAsset.IsReady();
  184. }
  185. void MaterialAsset::ApplyVersionUpdates(AZStd::function<void(const char*)> reportError)
  186. {
  187. if (m_materialTypeVersion == m_materialTypeAsset->GetVersion())
  188. {
  189. return;
  190. }
  191. [[maybe_unused]] const uint32_t originalVersion = m_materialTypeVersion;
  192. [[maybe_unused]] bool changesWereApplied =
  193. m_materialTypeAsset->GetMaterialVersionUpdates().ApplyVersionUpdates(*this, reportError);
  194. #if AZ_ENABLE_TRACING
  195. if (changesWereApplied)
  196. {
  197. const AZStd::string versionString = (originalVersion == UnspecifiedMaterialTypeVersion) ?
  198. "<Unspecified>" : AZStd::string::format("'%u'", originalVersion);
  199. AZStd::string assetString = GetId().ToString<AZStd::string>().c_str();
  200. AZ::Data::AssetInfo assetInfo;
  201. AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetInfo,
  202. &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, GetId());
  203. if (assetInfo.m_assetId.IsValid())
  204. {
  205. assetString += " (" + assetInfo.m_relativePath + ")";
  206. }
  207. AZ_Warning(
  208. "MaterialAsset", false,
  209. "This material is based on version %s of %s, and the material type is now at version '%u'. "
  210. "Automatic updates have been applied. Consider updating the .material source file for %s.",
  211. versionString.c_str(), m_materialTypeAsset.ToString<AZStd::string>().c_str(),
  212. m_materialTypeAsset->GetVersion(), assetString.c_str());
  213. }
  214. #endif
  215. m_materialTypeVersion = m_materialTypeAsset->GetVersion();
  216. }
  217. Data::AssetHandler::LoadResult MaterialAssetHandler::LoadAssetData(
  218. const AZ::Data::Asset<AZ::Data::AssetData>& asset,
  219. AZStd::shared_ptr<AZ::Data::AssetDataStream> stream,
  220. const AZ::Data::AssetFilterCB& assetLoadFilterCB)
  221. {
  222. if (Base::LoadAssetData(asset, stream, assetLoadFilterCB) == Data::AssetHandler::LoadResult::LoadComplete)
  223. {
  224. asset.GetAs<MaterialAsset>()->AssetInitBus::Handler::BusConnect();
  225. return Data::AssetHandler::LoadResult::LoadComplete;
  226. }
  227. return Data::AssetHandler::LoadResult::Error;
  228. }
  229. } // namespace RPI
  230. } // namespace AZ