AreaLightExampleComponent.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857
  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 <AreaLightExampleComponent.h>
  9. #include <SampleComponentConfig.h>
  10. #include <Utils/Utils.h>
  11. #include <Automation/ScriptableImGui.h>
  12. #include <AzCore/Serialization/SerializeContext.h>
  13. #include <Atom/RPI.Reflect/Asset/AssetUtils.h>
  14. #include <Atom/RPI.Reflect/Model/ModelAsset.h>
  15. #include <Atom/RPI.Reflect/Material/MaterialAsset.h>
  16. #include <Atom/RPI.Public/RPISystemInterface.h>
  17. #include <Atom/RPI.Public/Scene.h>
  18. #include <Atom/RPI.Public/AuxGeom/AuxGeomDraw.h>
  19. #include <Atom/RPI.Public/Image/StreamingImage.h>
  20. #include <Atom/RPI.Public/Image/StreamingImagePool.h>
  21. #include <Atom/RPI.Public/Shader/ShaderSystem.h>
  22. #include <Atom/Component/DebugCamera/NoClipControllerComponent.h>
  23. #include <imgui/imgui.h>
  24. #include <RHI/BasicRHIComponent.h>
  25. namespace AtomSampleViewer
  26. {
  27. void AreaLightExampleComponent::Reflect(AZ::ReflectContext* context)
  28. {
  29. if (AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  30. {
  31. serializeContext->Class <AreaLightExampleComponent, AZ::Component>()
  32. ->Version(0)
  33. ;
  34. }
  35. }
  36. AZ::Quaternion AreaLightExampleComponent::Configuration::GetRotationQuaternion()
  37. {
  38. AZ::Quaternion rotation = AZ::Quaternion::CreateIdentity();
  39. rotation.SetFromEulerRadians(AZ::Vector3(m_rotations[0] + AZ::Constants::Pi, m_rotations[1], m_rotations[2]));
  40. return rotation;
  41. }
  42. AZ::Matrix3x3 AreaLightExampleComponent::Configuration::GetRotationMatrix()
  43. {
  44. return AZ::Matrix3x3::CreateFromQuaternion(GetRotationQuaternion());
  45. }
  46. AreaLightExampleComponent::AreaLightExampleComponent()
  47. : m_materialBrowser("@user@/AreaLightExampleComponent/material_browser.xml")
  48. , m_modelBrowser("@user@/AreaLightExampleComponent/model_browser.xml")
  49. {
  50. }
  51. void AreaLightExampleComponent::Activate()
  52. {
  53. // Get Feature processors
  54. m_meshFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::MeshFeatureProcessorInterface>();
  55. m_pointLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::PointLightFeatureProcessorInterface>();
  56. m_diskLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::DiskLightFeatureProcessorInterface>();
  57. m_capsuleLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::CapsuleLightFeatureProcessorInterface>();
  58. m_polygonLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::PolygonLightFeatureProcessorInterface>();
  59. m_quadLightFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::QuadLightFeatureProcessorInterface>();
  60. m_skyBoxFeatureProcessor = m_scene->GetFeatureProcessor<AZ::Render::SkyBoxFeatureProcessorInterface>();
  61. m_auxGeom = AZ::RPI::AuxGeomFeatureProcessorInterface::GetDrawQueueForScene(m_scene);
  62. // Create background
  63. m_skyBoxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::Cubemap);
  64. m_skyBoxFeatureProcessor->SetCubemap(Utils::GetSolidColorCubemap(0xFF202020));
  65. m_skyBoxFeatureProcessor->Enable(true);
  66. // Get material and set up material instances
  67. AZ::RPI::AssetUtils::TraceLevel traceLevel = AZ::RPI::AssetUtils::TraceLevel::Assert;
  68. static const char* defaultMaterialPath = "materials/presets/macbeth/00_illuminant.azmaterial";
  69. auto materialAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath<AZ::RPI::MaterialAsset>(defaultMaterialPath, traceLevel);
  70. InitializeMaterials(materialAsset);
  71. // Prepare meshes and lights
  72. auto modelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath<AZ::RPI::ModelAsset>(m_config.m_modelAssetPath.c_str(), traceLevel);
  73. m_meshHandles.resize(MaxVariants);
  74. UpdateModels(modelAsset);
  75. m_photometricValue.ConvertToPhotometricUnit(AZ::Render::PhotometricUnit::Lumen);
  76. m_lightHandles.resize(MaxVariants);
  77. UpdateLights();
  78. // Enable camera
  79. AZ::Debug::CameraControllerRequestBus::Event(GetCameraEntityId(), &AZ::Debug::CameraControllerRequestBus::Events::Enable,
  80. azrtti_typeid<AZ::Debug::NoClipControllerComponent>());
  81. // Sidebar
  82. m_materialBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  83. {
  84. return assetInfo.m_assetType == azrtti_typeid<AZ::RPI::MaterialAsset>() &&
  85. assetInfo.m_assetId.m_subId == 0; // no materials generated from models.
  86. });
  87. m_materialBrowser.Activate();
  88. m_materialBrowserSettings.m_labels.m_root = "Materials";
  89. m_modelBrowser.SetFilter([](const AZ::Data::AssetInfo& assetInfo)
  90. {
  91. return assetInfo.m_assetType == azrtti_typeid<AZ::RPI::ModelAsset>();
  92. });
  93. m_modelBrowser.Activate();
  94. m_modelBrowserSettings.m_labels.m_root = "Models";
  95. m_imguiSidebar.Activate();
  96. m_imguiSidebar.SetHideSidebar(true);
  97. // Connect to busses
  98. AZ::TickBus::Handler::BusConnect();
  99. }
  100. void AreaLightExampleComponent::Deactivate()
  101. {
  102. // Force validation off since it's a global flag.
  103. AZ::RPI::ShaderSystemInterface::Get()->SetGlobalShaderOption(AZ::Name{ "o_area_light_validation" }, AZ::RPI::ShaderOptionValue{ false });
  104. AZ::TickBus::Handler::BusDisconnect();
  105. m_imguiSidebar.Deactivate();
  106. m_modelBrowser.Deactivate();
  107. m_materialBrowser.Deactivate();
  108. ReleaseModels();
  109. ReleaseLights();
  110. m_materialInstances.clear();
  111. m_skyBoxFeatureProcessor->SetSkyboxMode(AZ::Render::SkyBoxMode::None);
  112. m_skyBoxFeatureProcessor->Enable(false);
  113. }
  114. void AreaLightExampleComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint timePoint)
  115. {
  116. DrawUI();
  117. DrawAuxGeom();
  118. }
  119. float AreaLightExampleComponent::GetPositionPercentage(uint32_t index)
  120. {
  121. return aznumeric_cast<float>(index) / aznumeric_cast<float>(m_config.m_count - 1);
  122. }
  123. AZ::Vector3 AreaLightExampleComponent::GetModelPosition(uint32_t index)
  124. {
  125. static float Spacing = 5.0f;
  126. // Total width of n models is Spacing * n, so the start x position is half of that.
  127. float startXPos = aznumeric_cast<float>(m_config.m_count - 1) * 0.5f * -Spacing;
  128. float xPos = startXPos + aznumeric_cast<float>(index) * Spacing;
  129. // y position pushes further away from the camera the more models there are to show.
  130. float yPos = -2.0f + Spacing * m_config.m_count * 0.4f;
  131. // z is slightly negative so the model's center is slightly below the camera's center
  132. float zPos = -1.0f;
  133. return AZ::Vector3(xPos, yPos, zPos);
  134. }
  135. template<typename T>
  136. T AreaLightExampleComponent::GetLerpValue(T values[2], uint32_t index, bool doLerp)
  137. {
  138. if (doLerp)
  139. {
  140. return AZ::Lerp(values[0], values[1], GetPositionPercentage(index));
  141. }
  142. return values[0];
  143. }
  144. AZ::Vector3 AreaLightExampleComponent::GetLightPosition(uint32_t index)
  145. {
  146. AZ::Vector3 position = GetModelPosition(index);
  147. position.SetZ(position.GetZ() + m_config.m_lightDistance);
  148. position += AZ::Vector3::CreateFromFloat3(m_config.m_positionOffset);
  149. return position;
  150. }
  151. void AreaLightExampleComponent::InitializeMaterials(AZ::Data::Asset<AZ::RPI::MaterialAsset> materialAsset)
  152. {
  153. m_roughnessPropertyIndex = materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(AZ::Name("roughness.factor"));
  154. m_metallicPropertyIndex = materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(AZ::Name("metallic.factor"));
  155. m_multiScatteringEnabledIndex = materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(AZ::Name("specularF0.enableMultiScatterCompensation"));
  156. m_materialInstances.resize(MaxVariants);
  157. for (AZ::Data::Instance<AZ::RPI::Material>& material : m_materialInstances)
  158. {
  159. material = AZ::RPI::Material::Create(materialAsset);
  160. }
  161. }
  162. void AreaLightExampleComponent::UpdateModels(AZ::Data::Asset<AZ::RPI::ModelAsset> modelAsset)
  163. {
  164. for (uint32_t i = 0; i < MaxVariants; ++i)
  165. {
  166. MeshHandle& meshHandle = m_meshHandles.at(i);
  167. if (i < m_config.m_count)
  168. {
  169. if (!meshHandle.IsValid())
  170. {
  171. meshHandle = m_meshFeatureProcessor->AcquireMesh(AZ::Render::MeshHandleDescriptor(modelAsset, m_materialInstances.at(i)));
  172. }
  173. else if (m_modelAsset.GetId() != modelAsset.GetId())
  174. {
  175. // Valid mesh handle, but wrong asset. Release and reacquire.
  176. m_meshFeatureProcessor->ReleaseMesh(meshHandle);
  177. meshHandle = m_meshFeatureProcessor->AcquireMesh(AZ::Render::MeshHandleDescriptor(modelAsset, m_materialInstances.at(i)));
  178. }
  179. AZ::Transform transform = AZ::Transform::CreateIdentity();
  180. transform.SetTranslation(GetModelPosition(i));
  181. m_meshFeatureProcessor->SetTransform(meshHandle, transform);
  182. }
  183. else if(meshHandle.IsValid())
  184. {
  185. m_meshFeatureProcessor->ReleaseMesh(meshHandle);
  186. }
  187. }
  188. m_modelAsset = modelAsset;
  189. }
  190. void AreaLightExampleComponent::UpdateMaterials()
  191. {
  192. bool allMaterialsCompiled = true;
  193. for (uint32_t i = 0; i < m_config.m_count; ++i)
  194. {
  195. MaterialInstance& materialInstance = m_materialInstances.at(i);
  196. if (m_roughnessPropertyIndex.IsValid())
  197. {
  198. float roughness = GetLerpValue(m_config.m_roughness, i, m_config.GetVaryRoughness());
  199. materialInstance->SetPropertyValue(m_roughnessPropertyIndex, roughness);
  200. }
  201. if (m_metallicPropertyIndex.IsValid())
  202. {
  203. float metallic = GetLerpValue(m_config.m_metallic, i, m_config.GetVaryMetallic());
  204. materialInstance->SetPropertyValue(m_metallicPropertyIndex, metallic);
  205. }
  206. if (m_multiScatteringEnabledIndex.IsValid())
  207. {
  208. materialInstance->SetPropertyValue(m_multiScatteringEnabledIndex, m_config.m_multiScattering);
  209. }
  210. allMaterialsCompiled = allMaterialsCompiled && materialInstance->Compile();
  211. }
  212. if (allMaterialsCompiled)
  213. {
  214. m_materialsNeedUpdate = false;
  215. }
  216. }
  217. template <typename FeatureProcessorType, typename HandleType>
  218. void AreaLightExampleComponent::UpdateLightForType(FeatureProcessorType featureProcessor, HandleType& handle, uint32_t index)
  219. {
  220. if (index < m_config.m_count)
  221. {
  222. if (!handle.IsValid())
  223. {
  224. handle = featureProcessor->AcquireLight();
  225. featureProcessor->SetAttenuationRadius(handle, 100.0f);
  226. }
  227. }
  228. else
  229. {
  230. featureProcessor->ReleaseLight(handle);
  231. }
  232. }
  233. void AreaLightExampleComponent::UpdatePointLight(PointLightHandle& handle, uint32_t index, AZ::Vector3 position)
  234. {
  235. UpdateLightForType(m_pointLightFeatureProcessor, handle, index);
  236. if (index < m_config.m_count)
  237. {
  238. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::OmnidirectionalSteradians);
  239. m_pointLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Candela>());
  240. float radius = GetLerpValue(m_config.m_radius, index, m_config.GetVaryRadius());
  241. m_pointLightFeatureProcessor->SetPosition(handle, position);
  242. m_pointLightFeatureProcessor->SetBulbRadius(handle, radius);
  243. }
  244. }
  245. void AreaLightExampleComponent::UpdateDiskLight(DiskLightHandle& handle, uint32_t index, AZ::Vector3 position)
  246. {
  247. UpdateLightForType(m_diskLightFeatureProcessor, handle, index);
  248. if (index < m_config.m_count)
  249. {
  250. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::DirectionalEffectiveSteradians);
  251. m_diskLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Candela>());
  252. m_diskLightFeatureProcessor->SetPosition(handle, position);
  253. AZ::Matrix3x3 rotationMatrix = m_config.GetRotationMatrix();
  254. m_diskLightFeatureProcessor->SetDirection(handle, rotationMatrix.GetBasisZ());
  255. float radius = GetLerpValue(m_config.m_radius, index, m_config.GetVaryRadius());
  256. m_diskLightFeatureProcessor->SetDiskRadius(handle, radius);
  257. }
  258. }
  259. void AreaLightExampleComponent::UpdateCapsuleLight(CapsuleLightHandle& handle, uint32_t index, AZ::Vector3 position)
  260. {
  261. UpdateLightForType(m_capsuleLightFeatureProcessor, handle, index);
  262. if (index < m_config.m_count)
  263. {
  264. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::OmnidirectionalSteradians);
  265. m_capsuleLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Candela>());
  266. AZ::Matrix3x3 rotationMatrix = m_config.GetRotationMatrix();
  267. AZ::Vector3 startPos = position - rotationMatrix.GetBasisZ() * m_config.m_capsuleHeight * 0.5f;
  268. AZ::Vector3 endPos = position + rotationMatrix.GetBasisZ() * m_config.m_capsuleHeight * 0.5f;
  269. m_capsuleLightFeatureProcessor->SetCapsuleLineSegment(handle, startPos, endPos);
  270. float radius = GetLerpValue(m_config.m_radius, index, m_config.GetVaryRadius());
  271. m_capsuleLightFeatureProcessor->SetCapsuleRadius(handle, radius);
  272. }
  273. }
  274. void AreaLightExampleComponent::UpdateQuadLight(QuadLightHandle& handle, uint32_t index, AZ::Vector3 position)
  275. {
  276. UpdateLightForType(m_quadLightFeatureProcessor, handle, index);
  277. if (index < m_config.m_count)
  278. {
  279. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::DirectionalEffectiveSteradians);
  280. m_photometricValue.SetArea(m_config.m_quadSize[0] * m_config.m_quadSize[1]);
  281. m_quadLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Nit>());
  282. m_quadLightFeatureProcessor->SetPosition(handle, position);
  283. m_quadLightFeatureProcessor->SetOrientation(handle, m_config.GetRotationQuaternion());
  284. m_quadLightFeatureProcessor->SetQuadDimensions(handle, m_config.m_quadSize[0], m_config.m_quadSize[1]);
  285. m_quadLightFeatureProcessor->SetLightEmitsBothDirections(handle, m_config.m_emitsBothDirections);
  286. m_quadLightFeatureProcessor->SetUseFastApproximation(handle, m_config.m_fastApproximation);
  287. }
  288. }
  289. void AreaLightExampleComponent::UpdatePolygonLight(PolygonLightHandle& handle, uint32_t index, AZ::Vector3 position)
  290. {
  291. UpdateLightForType(m_polygonLightFeatureProcessor, handle, index);
  292. if (index < m_config.m_count)
  293. {
  294. AZStd::vector<AZ::Vector3> points = GetPolygonVertices(m_config.m_polyStarCount, m_config.m_polyMinMaxRadius);
  295. m_photometricValue.SetEffectiveSolidAngle(AZ::Render::PhotometricValue::DirectionalEffectiveSteradians);
  296. m_photometricValue.SetArea(CalculatePolygonArea(points));
  297. m_polygonLightFeatureProcessor->SetRgbIntensity(handle, m_photometricValue.GetCombinedRgb<AZ::Render::PhotometricUnit::Nit>());
  298. m_polygonLightFeatureProcessor->SetPosition(handle, position);
  299. m_polygonLightFeatureProcessor->SetLightEmitsBothDirections(handle, m_config.m_emitsBothDirections);
  300. TransformVertices(points, m_config.GetRotationQuaternion(), position);
  301. AZ::Vector3 direction = m_config.GetRotationQuaternion().TransformVector(AZ::Vector3::CreateAxisZ());
  302. m_polygonLightFeatureProcessor->SetPolygonPoints(handle, points.data(), static_cast<uint32_t>(points.size()), direction);
  303. }
  304. }
  305. void AreaLightExampleComponent::UpdateLights()
  306. {
  307. m_photometricValue.SetIntensity(m_config.m_intensity);
  308. m_photometricValue.SetChroma(AZ::Color::CreateFromVector3(AZ::Vector3::CreateFromFloat3(m_config.m_color)));
  309. for (uint32_t i = 0; i < MaxVariants; ++i)
  310. {
  311. LightHandle& lightHandle = m_lightHandles.at(i);
  312. AZ::Vector3 lightPos = GetLightPosition(i);
  313. switch (m_config.m_lightType)
  314. {
  315. case Point:
  316. UpdatePointLight(lightHandle.m_point, i, lightPos);
  317. break;
  318. case Disk:
  319. UpdateDiskLight(lightHandle.m_disk, i, lightPos);
  320. break;
  321. case Capsule:
  322. UpdateCapsuleLight(lightHandle.m_capsule, i, lightPos);
  323. break;
  324. case Quad:
  325. UpdateQuadLight(lightHandle.m_quad, i, lightPos);
  326. break;
  327. case Polygon:
  328. UpdatePolygonLight(lightHandle.m_polygon, i, lightPos);
  329. break;
  330. }
  331. }
  332. }
  333. void AreaLightExampleComponent::TransformVertices(AZStd::vector<AZ::Vector3>& vertices, const AZ::Quaternion& orientation, const AZ::Vector3& translation)
  334. {
  335. for (AZ::Vector3& vertex : vertices)
  336. {
  337. vertex = orientation.TransformVector(vertex);
  338. vertex += translation;
  339. }
  340. }
  341. AZ::Vector3 AreaLightExampleComponent::GetCirclePoint(float n, float count)
  342. {
  343. // Calculate angle for this point in the star
  344. float ratio = 1.0f - (n / count);
  345. float angle = ratio * AZ::Constants::TwoPi;
  346. // Get normalized x, y coordinates for point
  347. float sin = 0.0f;
  348. float cos = 0.0f;
  349. AZ::SinCos(angle, sin, cos);
  350. return AZ::Vector3(sin, cos, 0.0f);
  351. }
  352. AZStd::vector<AZ::Vector3> AreaLightExampleComponent::GetPolygonVertices(uint32_t pointCount, float minMaxRadius[2])
  353. {
  354. uint32_t vertexCount = pointCount * 2; // For each of the stars points, there's a vertex bewteen the points.
  355. AZStd::vector<AZ::Vector3> points;
  356. points.reserve(vertexCount);
  357. for (uint32_t i = 0; i < vertexCount; ++i)
  358. {
  359. // Get a point on the circle and scale it by the min or max radius for every other point.
  360. AZ::Vector3 point = GetCirclePoint(static_cast<float>(i), static_cast<float>(vertexCount)) * minMaxRadius[i % 2];
  361. points.push_back(point);
  362. }
  363. return points;
  364. }
  365. AZStd::vector<AZ::Vector3> AreaLightExampleComponent::GetPolygonTriangles(uint32_t pointCount, float minMaxRadius[2])
  366. {
  367. AZStd::vector<AZ::Vector3> tris;
  368. tris.reserve(pointCount * 6); // 2 triangles with 3 vertices for each star point.
  369. uint32_t vertexCount = pointCount * 2; // For each of the stars points, there's a vertex bewteen the points.
  370. for (uint32_t i = 0; i < vertexCount; ++i)
  371. {
  372. uint32_t nextI = (i + 1) % vertexCount;
  373. AZ::Vector3 p0 = GetCirclePoint(static_cast<float>(i), static_cast<float>(vertexCount)) * minMaxRadius[i % 2];
  374. AZ::Vector3 p1 = GetCirclePoint(static_cast<float>(nextI), static_cast<float>(vertexCount)) * minMaxRadius[nextI % 2];
  375. tris.push_back(p0);
  376. tris.push_back(p1);
  377. tris.push_back(AZ::Vector3::CreateZero());
  378. }
  379. return tris;
  380. }
  381. void AreaLightExampleComponent::ReleaseModels()
  382. {
  383. for (MeshHandle& meshHandle : m_meshHandles)
  384. {
  385. m_meshFeatureProcessor->ReleaseMesh(meshHandle);
  386. }
  387. }
  388. void AreaLightExampleComponent::ReleaseLights()
  389. {
  390. for (LightHandle& lightHandle : m_lightHandles)
  391. {
  392. switch (m_config.m_lightType)
  393. {
  394. case Point:
  395. m_pointLightFeatureProcessor->ReleaseLight(lightHandle.m_point);
  396. break;
  397. case Disk:
  398. m_diskLightFeatureProcessor->ReleaseLight(lightHandle.m_disk);
  399. break;
  400. case Capsule:
  401. m_capsuleLightFeatureProcessor->ReleaseLight(lightHandle.m_capsule);
  402. break;
  403. case Quad:
  404. m_quadLightFeatureProcessor->ReleaseLight(lightHandle.m_quad);
  405. break;
  406. case Polygon:
  407. m_polygonLightFeatureProcessor->ReleaseLight(lightHandle.m_polygon);
  408. break;
  409. }
  410. }
  411. }
  412. void AreaLightExampleComponent::DrawUI()
  413. {
  414. ScriptableImGui::Begin("AreaLightSample", nullptr, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar);
  415. bool modelsNeedUpdate = false;
  416. bool lightsNeedUpdate = false;
  417. ImGui::Text("Area Light Example");
  418. ImGui::Separator();
  419. ImGui::Text("Mesh Settings");
  420. int count = m_config.m_count;
  421. if (ScriptableImGui::SliderInt("Count", &count, 1, MaxVariants))
  422. {
  423. m_config.m_count = aznumeric_cast<uint32_t>(count);
  424. modelsNeedUpdate = true;
  425. lightsNeedUpdate = true;
  426. }
  427. if (m_roughnessPropertyIndex.IsValid())
  428. {
  429. if (m_config.m_count > 1)
  430. {
  431. if (ScriptableImGui::Checkbox("Vary Roughness Across Models", &m_config.m_varyRoughness))
  432. {
  433. m_materialsNeedUpdate = true;
  434. }
  435. }
  436. if (m_config.GetVaryRoughness())
  437. {
  438. if (ScriptableImGui::SliderFloat2("Min Max Roughness", m_config.m_roughness, 0.0f, 1.0f))
  439. {
  440. m_materialsNeedUpdate = true;
  441. }
  442. }
  443. else if (ScriptableImGui::SliderFloat("Roughness", &m_config.m_roughness[0], 0.0f, 1.0f))
  444. {
  445. m_materialsNeedUpdate = true;
  446. }
  447. }
  448. if (m_metallicPropertyIndex.IsValid())
  449. {
  450. if (m_config.m_count > 1)
  451. {
  452. if (ScriptableImGui::Checkbox("Vary Metallic Across Models", &m_config.m_varyMetallic))
  453. {
  454. m_materialsNeedUpdate = true;
  455. }
  456. }
  457. if (m_config.GetVaryMetallic())
  458. {
  459. if (ScriptableImGui::SliderFloat2("Min Max Metallic", m_config.m_metallic, 0.0f, 1.0f))
  460. {
  461. m_materialsNeedUpdate = true;
  462. }
  463. }
  464. else if (ScriptableImGui::SliderFloat("Metallic", &m_config.m_metallic[0], 0.0f, 1.0f))
  465. {
  466. m_materialsNeedUpdate = true;
  467. }
  468. }
  469. ImGui::Separator();
  470. ImGui::Text("Light Settings");
  471. if (ScriptableImGui::Checkbox("Validate", &m_config.m_validation))
  472. {
  473. AZ::RPI::ShaderSystemInterface::Get()->SetGlobalShaderOption(AZ::Name{ "o_area_light_validation" }, AZ::RPI::ShaderOptionValue{ m_config.m_validation });
  474. }
  475. AZStd::vector<AZStd::string> lightTypeNames
  476. {
  477. "Point",
  478. "Disk",
  479. "Capsule",
  480. "Quad",
  481. "Polygon",
  482. };
  483. if (ScriptableImGui::BeginCombo("LightType", lightTypeNames.at(m_config.m_lightType).c_str()))
  484. {
  485. for (uint32_t i = 0; i < lightTypeNames.size(); ++i)
  486. {
  487. AZStd::string& name = lightTypeNames.at(i);
  488. if (ScriptableImGui::Selectable(name.c_str(), m_config.m_lightType == LightType(i)))
  489. {
  490. ReleaseLights();
  491. m_config.m_lightType = LightType(i);
  492. lightsNeedUpdate = true;
  493. }
  494. }
  495. ScriptableImGui::EndCombo();
  496. }
  497. if (ScriptableImGui::SliderFloat("Lumens", &m_config.m_intensity, 0.0f, 1000.0f, "%.3f", ImGuiSliderFlags_Logarithmic))
  498. {
  499. lightsNeedUpdate = true;
  500. }
  501. if (ScriptableImGui::ColorEdit3("Color", m_config.m_color, ImGuiColorEditFlags_Float))
  502. {
  503. lightsNeedUpdate = true;
  504. }
  505. if (ScriptableImGui::SliderFloat3("Position Offset", m_config.m_positionOffset, -3.0f, 3.0f))
  506. {
  507. lightsNeedUpdate = true;
  508. }
  509. if (m_config.m_lightType == Disk || m_config.m_lightType == Capsule || m_config.m_lightType == Quad || m_config.m_lightType == Polygon)
  510. {
  511. if (ScriptableImGui::SliderAngle("X rotation", &m_config.m_rotations[0]))
  512. {
  513. lightsNeedUpdate = true;
  514. }
  515. if (ScriptableImGui::SliderAngle("Y rotation", &m_config.m_rotations[1]))
  516. {
  517. lightsNeedUpdate = true;
  518. }
  519. if (m_config.m_lightType == Quad || m_config.m_lightType == Polygon) // Disk and Capsule are circular around z axis, so this only affects Quad and Polygon.
  520. {
  521. if (ScriptableImGui::SliderAngle("Z rotation", &m_config.m_rotations[2]))
  522. {
  523. lightsNeedUpdate = true;
  524. }
  525. }
  526. }
  527. // Radius
  528. if (m_config.m_lightType == Point || m_config.m_lightType == Disk || m_config.m_lightType == Capsule)
  529. {
  530. if (m_config.m_count > 1)
  531. {
  532. if (ScriptableImGui::Checkbox("Vary Radius Across Lights", &m_config.m_varyRadius))
  533. {
  534. lightsNeedUpdate = true;
  535. }
  536. }
  537. if (m_config.GetVaryRadius())
  538. {
  539. if (ScriptableImGui::SliderFloat2("Min/Max Radius", m_config.m_radius, 0.0f, 1.0f))
  540. {
  541. lightsNeedUpdate = true;
  542. }
  543. }
  544. else if (ScriptableImGui::SliderFloat("Radius", &m_config.m_radius[0], 0.0f, 2.0f))
  545. {
  546. lightsNeedUpdate = true;
  547. }
  548. }
  549. // Capsule Height
  550. if (m_config.m_lightType == Capsule)
  551. {
  552. if (ScriptableImGui::SliderFloat("Capsule Height", &m_config.m_capsuleHeight, 0.0f, 10.0f))
  553. {
  554. lightsNeedUpdate = true;
  555. }
  556. }
  557. if (m_config.m_lightType == Quad)
  558. {
  559. if (ScriptableImGui::SliderFloat2("Quad Dimensions", m_config.m_quadSize, 0.0f, 10.0f))
  560. {
  561. lightsNeedUpdate = true;
  562. }
  563. if (ScriptableImGui::Checkbox("Use Fast Approximation", &m_config.m_fastApproximation))
  564. {
  565. lightsNeedUpdate = true;
  566. }
  567. }
  568. if (m_config.m_lightType == Polygon)
  569. {
  570. if (ScriptableImGui::SliderInt("Star Points", &m_config.m_polyStarCount, 2, 32))
  571. {
  572. lightsNeedUpdate = true;
  573. }
  574. if (ScriptableImGui::SliderFloat2("Star Min-Max Radius", m_config.m_polyMinMaxRadius, 0.0f, 4.0))
  575. {
  576. lightsNeedUpdate = true;
  577. }
  578. }
  579. if (m_config.m_lightType == Quad || m_config.m_lightType == Polygon)
  580. {
  581. if (ScriptableImGui::Checkbox("Emit Both Directions", &m_config.m_emitsBothDirections))
  582. {
  583. lightsNeedUpdate = true;
  584. }
  585. }
  586. if (ScriptableImGui::Checkbox("Multiscattering", &m_config.m_multiScattering))
  587. {
  588. m_materialsNeedUpdate = true;
  589. }
  590. ScriptableImGui::End();
  591. if (m_imguiSidebar.Begin())
  592. {
  593. if (m_modelBrowser.Tick(m_modelBrowserSettings))
  594. {
  595. AZ::Data::AssetId selectedModelAssetId = m_modelBrowser.GetSelectedAssetId();
  596. if (selectedModelAssetId.IsValid())
  597. {
  598. AZ::Data::Asset<AZ::RPI::ModelAsset> modelAsset;
  599. modelAsset.Create(selectedModelAssetId);
  600. UpdateModels(modelAsset);
  601. modelsNeedUpdate = false;
  602. }
  603. }
  604. ImGui::Spacing();
  605. if (m_materialBrowser.Tick(m_materialBrowserSettings))
  606. {
  607. AZ::Data::AssetId selectedMaterialAssetId = m_materialBrowser.GetSelectedAssetId();
  608. if (selectedMaterialAssetId.IsValid())
  609. {
  610. AZ::Data::Asset<AZ::RPI::MaterialAsset> materialAsset = AZ::Data::AssetManager::Instance().GetAsset<AZ::RPI::MaterialAsset>(
  611. selectedMaterialAssetId, AZ::Data::AssetLoadBehavior::PreLoad);
  612. materialAsset.BlockUntilLoadComplete();
  613. if (materialAsset.IsReady())
  614. {
  615. InitializeMaterials(materialAsset);
  616. ReleaseModels();
  617. modelsNeedUpdate = true;
  618. }
  619. }
  620. }
  621. m_imguiSidebar.End();
  622. }
  623. if (modelsNeedUpdate)
  624. {
  625. UpdateModels(m_modelAsset);
  626. }
  627. if (m_materialsNeedUpdate || modelsNeedUpdate)
  628. {
  629. UpdateMaterials();
  630. }
  631. if (lightsNeedUpdate)
  632. {
  633. UpdateLights();
  634. }
  635. }
  636. void AreaLightExampleComponent::DrawAuxGeom()
  637. {
  638. // Lights need to add support for rendering their emissive surfaces to the regular forward pass which will replace the below.
  639. // Draw AuxGeom for the lights themselves
  640. AZ::Matrix3x3 rotationMatrix = m_config.GetRotationMatrix();
  641. for (uint32_t i = 0; i < m_config.m_count; ++i)
  642. {
  643. float radius = GetLerpValue(m_config.m_radius, i, m_config.GetVaryRadius());
  644. AZ::Vector3 lightPos = GetLightPosition(i);
  645. float area = 0.0f;
  646. switch (m_config.m_lightType)
  647. {
  648. case Point:
  649. area = 4.0f * AZ::Constants::Pi * radius * radius;
  650. break;
  651. case Disk:
  652. area = AZ::Constants::Pi * radius * radius;
  653. break;
  654. case Capsule:
  655. {
  656. float cylinderArea = 2.0f * AZ::Constants::Pi * m_config.m_capsuleHeight * radius;
  657. float capArea = 4.0f * AZ::Constants::Pi * radius * radius;
  658. area = cylinderArea + capArea;
  659. break;
  660. }
  661. case Quad:
  662. area = m_config.m_quadSize[0] * m_config.m_quadSize[1];
  663. break;
  664. case Polygon:
  665. area = CalculatePolygonArea(GetPolygonVertices(m_config.m_polyStarCount, m_config.m_polyMinMaxRadius));
  666. break;
  667. }
  668. float luxIntensity = m_config.m_intensity / area;
  669. float nitsIntensity = luxIntensity / AZ::Constants::Pi;
  670. // The aux geom pass happens after display mapper pass, so do basic gamma correction so the surface of the light's brightness is closer to everything else.
  671. nitsIntensity = pow(nitsIntensity, 1.0f / 2.2f);
  672. AZ::Color nitsColor = AZ::Color(nitsIntensity * m_config.m_color[0], nitsIntensity * m_config.m_color[1], nitsIntensity * m_config.m_color[2], 1.0f);
  673. AZ::RPI::AuxGeomDraw::DrawStyle drawStyle = AZ::RPI::AuxGeomDraw::DrawStyle::Solid;
  674. switch (m_config.m_lightType)
  675. {
  676. case Point:
  677. m_auxGeom->DrawSphere(lightPos, radius, nitsColor, drawStyle);
  678. break;
  679. case Disk:
  680. m_auxGeom->DrawDisk(lightPos, rotationMatrix.GetBasisZ(), radius, nitsColor, drawStyle);
  681. break;
  682. case Capsule:
  683. {
  684. m_auxGeom->DrawCylinder(lightPos, rotationMatrix.GetBasisZ(), radius, m_config.m_capsuleHeight, nitsColor, drawStyle);
  685. // Draw cylinder caps as spheres
  686. AZ::Vector3 startPos = lightPos - rotationMatrix.GetBasisZ() * m_config.m_capsuleHeight * 0.5f;
  687. AZ::Vector3 endPos = lightPos + rotationMatrix.GetBasisZ() * m_config.m_capsuleHeight * 0.5f;
  688. m_auxGeom->DrawSphere(startPos, radius, nitsColor, drawStyle);
  689. m_auxGeom->DrawSphere(endPos, radius, nitsColor, drawStyle);
  690. break;
  691. }
  692. case Quad:
  693. {
  694. AZ::Transform transform = AZ::Transform::CreateIdentity();
  695. transform.SetRotation(AZ::ConvertEulerRadiansToQuaternion(AZ::Vector3(m_config.m_rotations[0], -m_config.m_rotations[1], -m_config.m_rotations[2])));
  696. transform.SetTranslation(lightPos);
  697. transform *= AZ::Transform::CreateFromQuaternion(AZ::ConvertEulerRadiansToQuaternion(AZ::Vector3(AZ::Constants::Pi * 0.5f, 0.0f, 0.0f)));
  698. m_auxGeom->DrawQuad(m_config.m_quadSize[0], m_config.m_quadSize[1], AZ::Matrix3x4::CreateFromTransform(transform), nitsColor, drawStyle);
  699. break;
  700. }
  701. case Polygon:
  702. {
  703. // Sadly DrawTriangles() only supports 8 bit color, so nitsColor must be capped at 1.0f.
  704. nitsIntensity = AZ::GetMin(1.0f, nitsIntensity);
  705. nitsColor = AZ::Color(nitsIntensity * m_config.m_color[0], nitsIntensity * m_config.m_color[1], nitsIntensity * m_config.m_color[2], 1.0f);
  706. AZStd::vector<AZ::Vector3> tris = GetPolygonTriangles(m_config.m_polyStarCount, m_config.m_polyMinMaxRadius);
  707. TransformVertices(tris, m_config.GetRotationQuaternion(), lightPos);
  708. AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments args;
  709. args.m_colorCount = 1;
  710. args.m_colors = &nitsColor;
  711. args.m_vertCount = static_cast<uint32_t>(tris.size());
  712. args.m_verts = tris.data();
  713. m_auxGeom->DrawTriangles(args);
  714. break;
  715. }
  716. }
  717. }
  718. }
  719. float AreaLightExampleComponent::CalculatePolygonArea(const AZStd::vector<AZ::Vector3>& vertices)
  720. {
  721. // See https://en.wikipedia.org/wiki/Shoelace_formula
  722. float twiceArea = 0.0f;
  723. for (size_t i = 0; i < vertices.size(); ++i)
  724. {
  725. size_t j = (i + 1) % vertices.size();
  726. twiceArea += vertices.at(i).GetX() * vertices.at(j).GetY();
  727. twiceArea -= vertices.at(i).GetY() * vertices.at(j).GetX();
  728. }
  729. return AZ::GetAbs(twiceArea * 0.5f);
  730. }
  731. }