DynamicMaterialTestComponent.cpp 11 KB

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