AreaLightExampleComponent.cpp 34 KB

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