DynamicMaterialTestComponent.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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 <DynamicMaterialTestComponent.h>
  9. #include <SampleComponentManager.h>
  10. #include <SampleComponentConfig.h>
  11. #include <Automation/ScriptableImGui.h>
  12. #include <Automation/ScriptRunnerBus.h>
  13. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  14. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  15. #include <Atom/RPI.Reflect/Material/MaterialPropertiesLayout.h>
  16. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  17. #include <AzCore/Component/Entity.h>
  18. #include <AzCore/Debug/EventTrace.h>
  19. #include <AzCore/Math/Random.h>
  20. #include <RHI/BasicRHIComponent.h>
  21. namespace AtomSampleViewer
  22. {
  23. using namespace AZ;
  24. using namespace RPI;
  25. void DynamicMaterialTestComponent::Reflect(ReflectContext* context)
  26. {
  27. if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context))
  28. {
  29. serializeContext->Class<DynamicMaterialTestComponent, EntityLatticeTestComponent>()
  30. ->Version(0)
  31. ;
  32. }
  33. }
  34. DynamicMaterialTestComponent::DynamicMaterialTestComponent()
  35. : m_imguiSidebar("@user@/DynamicMaterialTestComponent/sidebar.xml")
  36. , m_compileTimer(CompileTimerQueueSize, CompileTimerQueueSize)
  37. {
  38. }
  39. void DynamicMaterialTestComponent::Activate()
  40. {
  41. TickBus::Handler::BusConnect();
  42. m_imguiSidebar.Activate();
  43. InitMaterialConfigs();
  44. Base::Activate();
  45. m_currentTime = 0.0f;
  46. }
  47. void DynamicMaterialTestComponent::Deactivate()
  48. {
  49. TickBus::Handler::BusDisconnect();
  50. m_imguiSidebar.Deactivate();
  51. Base::Deactivate();
  52. }
  53. void DynamicMaterialTestComponent::PrepareCreateLatticeInstances(uint32_t instanceCount)
  54. {
  55. const char* modelPath = "objects/shaderball_simple.azmodel";
  56. Data::AssetId modelAssetId;
  57. Data::AssetCatalogRequestBus::BroadcastResult(
  58. modelAssetId, &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath,
  59. modelPath, azrtti_typeid<ModelAsset>(), false);
  60. AZ_Assert(modelAssetId.IsValid(), "Failed to get model asset id: %s", modelPath);
  61. m_modelAsset.Create(modelAssetId);
  62. m_meshHandles.reserve(instanceCount);
  63. m_materials.reserve(instanceCount);
  64. // Give the models time to load before continuing scripts
  65. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::PauseScript);
  66. m_waitingForMeshes = true;
  67. }
  68. void DynamicMaterialTestComponent::CreateLatticeInstance(const Transform& transform)
  69. {
  70. AZ::Data::Asset<AZ::RPI::MaterialAsset>& materialAsset = m_materialConfigs[m_currentMaterialConfig].m_materialAsset;
  71. AZ::Data::Instance<AZ::RPI::Material> material = Material::Create(materialAsset);
  72. Render::MaterialAssignmentMap materialMap;
  73. Render::MaterialAssignment& defaultMaterial = materialMap[Render::DefaultMaterialAssignmentId];
  74. defaultMaterial.m_materialAsset = materialAsset;
  75. defaultMaterial.m_materialInstance = material;
  76. Render::MeshHandleDescriptor meshDescriptor;
  77. meshDescriptor.m_modelAsset = m_modelAsset;
  78. meshDescriptor.m_isRayTracingEnabled = false;
  79. auto meshHandle = GetMeshFeatureProcessor()->AcquireMesh(meshDescriptor, materialMap);
  80. GetMeshFeatureProcessor()->SetTransform(meshHandle, transform);
  81. Data::Instance<RPI::Model> model = GetMeshFeatureProcessor()->GetModel(meshHandle);
  82. if (model)
  83. {
  84. m_loadedMeshCounter++;
  85. }
  86. else
  87. {
  88. m_meshLoadEventHandlers.push_back(AZ::Render::MeshFeatureProcessorInterface::ModelChangedEvent::Handler
  89. {
  90. [this](AZ::Data::Instance<AZ::RPI::Model> model) { m_loadedMeshCounter++; }
  91. });
  92. GetMeshFeatureProcessor()->ConnectModelChangeEventHandler(meshHandle, m_meshLoadEventHandlers.back());
  93. }
  94. m_meshHandles.push_back(AZStd::move(meshHandle));
  95. m_materials.push_back(material);
  96. }
  97. void DynamicMaterialTestComponent::DestroyLatticeInstances()
  98. {
  99. for (auto& meshHandle : m_meshHandles)
  100. {
  101. GetMeshFeatureProcessor()->ReleaseMesh(meshHandle);
  102. }
  103. m_meshHandles.clear();
  104. m_materials.clear();
  105. m_loadedMeshCounter = 0;
  106. m_waitingForMeshes = false;
  107. m_meshLoadEventHandlers.clear();
  108. }
  109. void DynamicMaterialTestComponent::InitMaterialConfigs()
  110. {
  111. using namespace AZ::RPI;
  112. MaterialConfig config;
  113. config.m_name = "Default StandardPBR Material";
  114. config.m_materialAsset = AssetUtils::GetAssetByProductPath<MaterialAsset>(DefaultPbrMaterialPath, AssetUtils::TraceLevel::Assert);
  115. config.m_updateLatticeMaterials = [this]() { UpdateStandardPbrColors(); };
  116. m_materialConfigs.push_back(config);
  117. config.m_name = "C++ Functor Test Material";
  118. config.m_materialAsset = AssetUtils::GetAssetByProductPath<MaterialAsset>("materials/dynamicmaterialtest/emissivewithcppfunctors.azmaterial", AssetUtils::TraceLevel::Assert);
  119. config.m_updateLatticeMaterials = [this]() { UpdateEmissiveMaterialIntensity(); };
  120. m_materialConfigs.push_back(config);
  121. config.m_name = "Lua Functor Test Material";
  122. config.m_materialAsset = AssetUtils::GetAssetByProductPath<MaterialAsset>("materials/dynamicmaterialtest/emissivewithluafunctors.azmaterial", AssetUtils::TraceLevel::Assert);
  123. config.m_updateLatticeMaterials = [this]() { UpdateEmissiveMaterialIntensity(); };
  124. m_materialConfigs.push_back(config);
  125. m_currentMaterialConfig = 0;
  126. }
  127. void DynamicMaterialTestComponent::UpdateStandardPbrColors()
  128. {
  129. static const Color colorOptions[] =
  130. {
  131. Color(1.0f, 0.0f, 0.0f, 1.0f),
  132. Color(0.0f, 1.0f, 0.0f, 1.0f),
  133. Color(0.0f, 0.0f, 1.0f, 1.0f),
  134. Color(1.0f, 1.0f, 0.0f, 1.0f),
  135. Color(0.0f, 1.0f, 1.0f, 1.0f),
  136. Color(1.0f, 0.0f, 1.0f, 1.0f),
  137. };
  138. // Create a new SimpleLcgRandom every time to keep a consistent seed and consistent color selection.
  139. SimpleLcgRandom random;
  140. for (int i = 0; i < m_meshHandles.size(); ++i)
  141. {
  142. auto& material = m_materials[i];
  143. static const float CylesPerSecond = 0.5f;
  144. const float t = aznumeric_cast<float>(sin(m_currentTime * CylesPerSecond * AZ::Constants::TwoPi) * 0.5f + 0.5f);
  145. const int colorIndexA = random.GetRandom() % AZ_ARRAY_SIZE(colorOptions);
  146. int colorIndexB = colorIndexA;
  147. while (colorIndexA == colorIndexB)
  148. {
  149. colorIndexB = random.GetRandom() % AZ_ARRAY_SIZE(colorOptions);
  150. }
  151. const Color color = colorOptions[colorIndexA] * t + colorOptions[colorIndexB] * (1.0f - t);
  152. MaterialPropertyIndex colorProperty = material->FindPropertyIndex(AZ::Name{"baseColor.color"});
  153. material->SetPropertyValue(colorProperty, color);
  154. }
  155. }
  156. void DynamicMaterialTestComponent::UpdateEmissiveMaterialIntensity()
  157. {
  158. for (int i = 0; i < m_meshHandles.size(); ++i)
  159. {
  160. auto& meshHandle = m_meshHandles[i];
  161. auto& material = m_materials[i];
  162. const float distance = GetMeshFeatureProcessor()->GetTransform(meshHandle).GetTranslation().GetLengthEstimate();
  163. static const float DistanceScale = 0.02f;
  164. static const float CylesPerSecond = 0.5f;
  165. const float t = aznumeric_cast<float>(sin((DistanceScale * distance + m_currentTime * CylesPerSecond) * AZ::Constants::TwoPi) * 0.5f + 0.5f);
  166. static const float MinIntensity = 1.0f;
  167. static const float MaxIntensity = 4.0f;
  168. const float intensity = AZ::Lerp(MinIntensity, MaxIntensity, t);
  169. MaterialPropertyIndex intensityProperty = material->FindPropertyIndex(AZ::Name{"emissive.intensity"});
  170. material->SetPropertyValue(intensityProperty, intensity);
  171. }
  172. }
  173. void DynamicMaterialTestComponent::CompileMaterials()
  174. {
  175. AZ::Debug::Timer timer;
  176. timer.Stamp();
  177. for (auto& material : m_materials)
  178. {
  179. material->Compile();
  180. }
  181. m_compileTimer.PushValue(timer.GetDeltaTimeInSeconds() * 1'000'000);
  182. }
  183. void DynamicMaterialTestComponent::OnTick(float deltaTime, ScriptTimePoint /*scriptTime*/)
  184. {
  185. AZ_TRACE_METHOD();
  186. if (m_waitingForMeshes)
  187. {
  188. if(m_loadedMeshCounter == m_meshHandles.size())
  189. {
  190. m_waitingForMeshes = false;
  191. ScriptRunnerRequestBus::Broadcast(&ScriptRunnerRequests::ResumeScript);
  192. // Reset the clock so we get consistent animation for scripts
  193. m_currentTime = 0;
  194. }
  195. }
  196. AZ_Assert(m_loadedMeshCounter <= m_meshHandles.size(), "Mesh load handlers were called multiple times?");
  197. bool updateMaterials = false;
  198. if (!m_pause)
  199. {
  200. m_currentTime += deltaTime;
  201. updateMaterials = true;
  202. }
  203. if (m_imguiSidebar.Begin())
  204. {
  205. RenderImGuiLatticeControls();
  206. ImGui::Separator();
  207. bool configChanged = false;
  208. for (int i = 0; i < m_materialConfigs.size(); ++i)
  209. {
  210. configChanged = configChanged || ScriptableImGui::RadioButton(m_materialConfigs[i].m_name.c_str(), &m_currentMaterialConfig, i);
  211. }
  212. if (configChanged)
  213. {
  214. RebuildLattice();
  215. }
  216. ImGui::Separator();
  217. ScriptableImGui::Checkbox("Pause", &m_pause);
  218. if (ScriptableImGui::Button("Reset Clock"))
  219. {
  220. m_currentTime = 0;
  221. updateMaterials = true;
  222. }
  223. ImGui::Separator();
  224. ImGui::Text("%d unique objects", aznumeric_cast<int32_t>(m_meshHandles.size()));
  225. ImGui::Text("Total Material Compile Time:");
  226. ImGuiHistogramQueue::WidgetSettings settings;
  227. settings.m_units = "microseconds";
  228. m_compileTimer.Tick(deltaTime, settings);
  229. ImGui::Text("Average per Material: %4.2f", m_compileTimer.GetDisplayedAverage() / m_materials.size());
  230. ImGui::Separator();
  231. m_imguiSidebar.End();
  232. }
  233. if (updateMaterials)
  234. {
  235. m_materialConfigs[m_currentMaterialConfig].m_updateLatticeMaterials();
  236. CompileMaterials();
  237. }
  238. }
  239. } // namespace AtomSampleViewer