From d9c646062b0521cc24cb54b120c1a17a9a726072 Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Fri, 28 Jan 2022 13:45:58 -0800 Subject: [PATCH 001/133] Instrumented support for the JSON importer for material type files. I also noticed that JsonFileLoadContext was no longer used (see https://github.com/o3de/o3de/pull/7010) so I was able to remove all that code. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../RPI.Edit/Common/JsonFileLoadContext.h | 36 ----------- .../Include/Atom/RPI.Edit/Common/JsonUtils.h | 5 -- .../Atom/RPI.Edit/Material/MaterialUtils.h | 8 +-- .../RPI.Builders/Material/MaterialBuilder.cpp | 6 -- .../RPI.Edit/Common/JsonFileLoadContext.cpp | 39 ----------- .../MaterialFunctorSourceDataSerializer.cpp | 1 - .../RPI.Edit/Material/MaterialSourceData.cpp | 1 - .../RPI.Edit/Material/MaterialUtils.cpp | 25 ++++---- .../RPI/Code/Tests/Common/JsonTestUtils.h | 12 +--- .../Material/MaterialTypeSourceDataTests.cpp | 64 ++++++++++++++++++- Gems/Atom/RPI/Code/atom_rpi_edit_files.cmake | 2 - 11 files changed, 84 insertions(+), 115 deletions(-) delete mode 100644 Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonFileLoadContext.h delete mode 100644 Gems/Atom/RPI/Code/Source/RPI.Edit/Common/JsonFileLoadContext.cpp diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonFileLoadContext.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonFileLoadContext.h deleted file mode 100644 index 90267010a7..0000000000 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonFileLoadContext.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include -#include -#include - -namespace AZ -{ - namespace RPI - { - //! Settings for custom JSON serializers to get context about loading a file - class JsonFileLoadContext final - { - public: - AZ_TYPE_INFO(JsonFileLoadContext, "{314942B3-A74A-49D2-822D-CD56F8E3C0F8}"); - - void PushFilePath(AZStd::string path); - AZStd::string_view GetFilePath() const; - void PopFilePath(); - - private: - // Using vector instead of stack because stack doesn't have a copy constructor - AZStd::vector m_thisFilePath; - }; - - } // namespace RPI -} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h index 9f4cdcf31b..5550013038 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h @@ -11,7 +11,6 @@ #include #include #include -#include #include namespace AZ @@ -52,13 +51,9 @@ namespace AZ rapidjson::Document& document = loadOutcome.GetValue(); - AZ::RPI::JsonFileLoadContext fileLoadContext; - fileLoadContext.PushFilePath(path); - AZ::JsonDeserializerSettings jsonSettings; AZ::RPI::JsonReportingHelper reportingHelper; reportingHelper.Attach(jsonSettings); - jsonSettings.m_metadata.Add(AZStd::move(fileLoadContext)); AZ::JsonSerialization::Load(objectData, document, jsonSettings); if (reportingHelper.ErrorsReported()) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h index 2fb55e5f40..6ab7132109 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h @@ -48,11 +48,11 @@ namespace AZ //! @return if resolving is successful. An error will be reported if it fails. bool ResolveMaterialPropertyEnumValue(const MaterialPropertyDescriptor* propertyDescriptor, const AZ::Name& enumName, MaterialPropertyValue& outResolvedValue); - //! Load material type from a json file. If the file path is relative, the loaded json document must be provided. + //! Load material type from a json file or document. //! Otherwise, it will use the passed in document first if not null, or load the json document from the path. - //! @param filePath a relative path if document is provided, an absolute path if document is not provided. - //! @param document the loaded json document. - AZ::Outcome LoadMaterialTypeSourceData(const AZStd::string& filePath, const rapidjson::Value* document = nullptr); + //! @param filePath path to the JSON file to load, unless the @document is already provided. In either case, this path will be used to resolve any relative file references. + //! @param document an optional already loaded json document. + AZ::Outcome LoadMaterialTypeSourceData(const AZStd::string& filePath, rapidjson::Document* document = nullptr); //! Utility function for custom JSON serializers to report results as "Skipped" when encountering keys that aren't recognized //! as part of the custom format. diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp index d55f202c03..c81b91d777 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -139,11 +138,6 @@ namespace AZ JsonReportingHelper reportingHelper; reportingHelper.Attach(settings); - // This is required by some custom material serializers to support relative path references. - JsonFileLoadContext fileLoadContext; - fileLoadContext.PushFilePath(filePath); - settings.m_metadata.Add(fileLoadContext); - JsonSerialization::Load(material, value, settings); if (reportingHelper.ErrorsReported()) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Common/JsonFileLoadContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Common/JsonFileLoadContext.cpp deleted file mode 100644 index fb5f7b09a9..0000000000 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Common/JsonFileLoadContext.cpp +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include - -namespace AZ -{ - namespace RPI - { - // Note, we use string not string_view on purpose because m_thisFilePath.push_back() will make a new string anyway. - void JsonFileLoadContext::PushFilePath(AZStd::string path) - { - m_thisFilePath.push_back(AZStd::move(path)); - } - - AZStd::string_view JsonFileLoadContext::GetFilePath() const - { - if (m_thisFilePath.empty()) - { - return ""; - } - else - { - return m_thisFilePath.back(); - } - } - - void JsonFileLoadContext::PopFilePath() - { - m_thisFilePath.pop_back(); - } - - } // namespace RPI -} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceDataSerializer.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceDataSerializer.cpp index a944a35162..ceb7093362 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceDataSerializer.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceDataSerializer.cpp @@ -9,7 +9,6 @@ #include #include #include -#include #include #include diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp index ae7889aa93..857e518e4e 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp @@ -14,7 +14,6 @@ #include #include -#include #include #include diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp index b03771173f..be5feccb80 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp @@ -14,11 +14,11 @@ #include #include #include -#include #include #include #include #include +#include #include #include @@ -73,21 +73,29 @@ namespace AZ outResolvedValue = enumValue; return true; } - - AZ::Outcome LoadMaterialTypeSourceData(const AZStd::string& filePath, const rapidjson::Value* document) + + AZ::Outcome LoadMaterialTypeSourceData(const AZStd::string& filePath, rapidjson::Document* document) { - AZ::Outcome loadOutcome; + rapidjson::Document localDocument; + if (document == nullptr) { - loadOutcome = AZ::JsonSerializationUtils::ReadJsonFile(filePath, AZ::RPI::JsonUtils::DefaultMaxFileSize); + AZ::Outcome loadOutcome = AZ::JsonSerializationUtils::ReadJsonFile(filePath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!loadOutcome.IsSuccess()) { AZ_Error("AZ::RPI::JsonUtils", false, "%s", loadOutcome.GetError().c_str()); return AZ::Failure(); } - document = &loadOutcome.GetValue(); + localDocument = loadOutcome.TakeValue(); + document = &localDocument; } + + AZ::BaseJsonImporter jsonImporter; + AZ::JsonImportSettings importSettings; + importSettings.m_importer = &jsonImporter; + importSettings.m_loadedJsonPath = filePath; + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ResolveImports(document->GetObject(), document->GetAllocator(), importSettings); MaterialTypeSourceData materialType; @@ -96,11 +104,6 @@ namespace AZ JsonReportingHelper reportingHelper; reportingHelper.Attach(settings); - // This is required by some custom material serializers to support relative path references. - JsonFileLoadContext fileLoadContext; - fileLoadContext.PushFilePath(filePath); - settings.m_metadata.Add(fileLoadContext); - JsonSerialization::Load(materialType, *document, settings); materialType.ConvertToNewDataFormat(); materialType.ResolveUvEnums(); diff --git a/Gems/Atom/RPI/Code/Tests/Common/JsonTestUtils.h b/Gems/Atom/RPI/Code/Tests/Common/JsonTestUtils.h index 56d537f236..94616b23e9 100644 --- a/Gems/Atom/RPI/Code/Tests/Common/JsonTestUtils.h +++ b/Gems/Atom/RPI/Code/Tests/Common/JsonTestUtils.h @@ -16,7 +16,6 @@ #include #include #include -#include namespace UnitTest { @@ -46,17 +45,12 @@ namespace UnitTest //! Uses JsonSerialization to load JSON data into a reflected object template - JsonTestResult LoadTestDataFromJson(T& object, rapidjson::Value& json, AZ::RPI::JsonFileLoadContext* jsonFileLoadContext = nullptr) + JsonTestResult LoadTestDataFromJson(T& object, rapidjson::Value& json) { JsonTestResult result; AZ::JsonDeserializerSettings settings; - if (jsonFileLoadContext) - { - settings.m_metadata.Add(*jsonFileLoadContext); - } - settings.m_reporting = [&result](AZStd::string_view message, AZ::JsonSerializationResult::ResultCode resultCode, AZStd::string_view path) { JsonTestResult::Report report; @@ -74,14 +68,14 @@ namespace UnitTest //! Uses JsonSerialization to load JSON data from a string into a reflected object template - JsonTestResult LoadTestDataFromJson(T& object, AZStd::string_view jsonText, AZ::RPI::JsonFileLoadContext* jsonFileLoadContext = nullptr) + JsonTestResult LoadTestDataFromJson(T& object, AZStd::string_view jsonText) { auto parseResult = AZ::JsonSerializationUtils::ReadJsonString(jsonText); EXPECT_TRUE(parseResult.IsSuccess()) << parseResult.GetError().c_str(); if (parseResult.IsSuccess()) { - return LoadTestDataFromJson(object, parseResult.GetValue(), jsonFileLoadContext); + return LoadTestDataFromJson(object, parseResult.GetValue()); } else { diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp index 206073e96a..e0fa16c5f4 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp @@ -16,11 +16,13 @@ #include #include #include +#include #include #include #include #include +#include #include #include #include @@ -35,6 +37,7 @@ namespace UnitTest { protected: + AZ::IO::FixedMaxPath m_tempFolder; RHI::Ptr m_testMaterialSrgLayout; Data::Asset m_testShaderAsset; Data::Asset m_testShaderAsset2; @@ -329,6 +332,9 @@ namespace UnitTest AZStd::string testImageFilepathAbsolute(TestImageFilepathAbsolute); AzFramework::StringFunc::Path::Normalize(testImageFilepathAbsolute); m_assetSystemStub.RegisterSourceInfo(testImageFilepathAbsolute.c_str(), testImageAssetInfo2, ""); + + m_tempFolder = AZ::Utils::GetExecutableDirectory(); + m_tempFolder = m_tempFolder/"temp"/"MaterialTypeSourceDataTest"; } void TearDown() override @@ -1473,6 +1479,8 @@ namespace UnitTest { // Note that serialization of individual fields within material properties is thoroughly tested in // MaterialPropertySerializerTests, so the sample property data used here is cursory. + // We also don't cover fields related to providing name contexts for nested property groups, like + // "shaderInputPrefix" and "shaderOptionPrefix" as those are covered in CreateMaterialTypeAsset_NestedGroups*. const AZStd::string inputJson = R"( { @@ -1701,7 +1709,7 @@ namespace UnitTest JsonTestResult storeResult = StoreTestDataToJson(material, outputJson); ExpectSimilarJson(inputJson, outputJson); } - + TEST_F(MaterialTypeSourceDataTests, LoadAllFieldsUsingOldFormat) { // The content of this test was copied from LoadAndStoreJson_AllFields to prove backward compatibility. @@ -1963,4 +1971,58 @@ namespace UnitTest errorMessageFinder.CheckExpectedErrorsFound(); } + + TEST_F(MaterialTypeSourceDataTests, LoadWithImportedJson) + { + const AZStd::string propertyGroupJson = R"( + { + "name": "myGroup", + "displayName": "My Group", + "description": "This group is defined in a separate JSON file", + "properties": [ + { + "name": "foo", + "type": "Bool" + }, + { + "name": "bar", + "type": "Float" + } + ] + } + )"; + + IO::FixedMaxPath propertyGroupJsonFilePath = m_tempFolder/"MyPropertyGroup.json"; + AZ::Utils::WriteFile(propertyGroupJson, propertyGroupJsonFilePath.c_str()); + + const AZStd::string materialTypeJson = R"( + { + "propertyLayout": { + "propertyGroups": [ + { "$import": "MyPropertyGroup.json" } + ] + } + } + )"; + + IO::FixedMaxPath materialTypeJsonFilePath = m_tempFolder/"TestImport.materialtype"; + AZ::Utils::WriteFile(materialTypeJson, materialTypeJsonFilePath.c_str()); + + auto loadMaterialTypeResult = MaterialUtils::LoadMaterialTypeSourceData(materialTypeJsonFilePath.c_str()); + EXPECT_TRUE(loadMaterialTypeResult); + MaterialTypeSourceData materialType = loadMaterialTypeResult.TakeValue(); + + EXPECT_EQ(materialType.GetPropertyLayout().m_propertyGroups.size(), 1); + EXPECT_TRUE(materialType.FindPropertyGroup("myGroup") != nullptr); + EXPECT_EQ(materialType.FindPropertyGroup("myGroup")->GetDisplayName(), "My Group"); + EXPECT_EQ(materialType.FindPropertyGroup("myGroup")->GetDescription(), "This group is defined in a separate JSON file"); + EXPECT_EQ(materialType.FindPropertyGroup("myGroup")->GetProperties().size(), 2); + EXPECT_NE(materialType.FindProperty("myGroup.foo"), nullptr); + EXPECT_NE(materialType.FindProperty("myGroup.bar"), nullptr); + EXPECT_EQ(materialType.FindProperty("myGroup.foo")->GetName(), "foo"); + EXPECT_EQ(materialType.FindProperty("myGroup.bar")->GetName(), "bar"); + EXPECT_EQ(materialType.FindProperty("myGroup.foo")->m_dataType, MaterialPropertyDataType::Bool); + EXPECT_EQ(materialType.FindProperty("myGroup.bar")->m_dataType, MaterialPropertyDataType::Float); + } + } diff --git a/Gems/Atom/RPI/Code/atom_rpi_edit_files.cmake b/Gems/Atom/RPI/Code/atom_rpi_edit_files.cmake index 3c345cc00b..84d423127a 100644 --- a/Gems/Atom/RPI/Code/atom_rpi_edit_files.cmake +++ b/Gems/Atom/RPI/Code/atom_rpi_edit_files.cmake @@ -11,7 +11,6 @@ set(FILES Include/Atom/RPI.Edit/Common/AssetAliasesSourceData.h Include/Atom/RPI.Edit/Common/ColorUtils.h Include/Atom/RPI.Edit/Common/ConvertibleSource.h - Include/Atom/RPI.Edit/Common/JsonFileLoadContext.h Include/Atom/RPI.Edit/Common/JsonReportingHelper.h Include/Atom/RPI.Edit/Common/JsonUtils.h Include/Atom/RPI.Edit/Material/LuaMaterialFunctorSourceData.h @@ -56,7 +55,6 @@ set(FILES Source/RPI.Edit/Common/AssetAliasesSourceData.cpp Source/RPI.Edit/Common/ColorUtils.cpp Source/RPI.Edit/Common/ConvertibleSource.cpp - Source/RPI.Edit/Common/JsonFileLoadContext.cpp Source/RPI.Edit/Common/JsonReportingHelper.cpp Source/RPI.Edit/Common/JsonUtils.cpp ) From 90e34e86496ff5540fad191da102bd2b8ea3f743 Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Fri, 28 Jan 2022 13:51:42 -0800 Subject: [PATCH 002/133] Fixed a couple places where we had variables called 'propertyNameContext' instead of 'propertyIdContext' which was inconsistent Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../Material/MaterialTypeSourceData.h | 4 +-- .../Material/MaterialTypeSourceData.cpp | 32 +++++++++---------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h index 40f82c8ec7..df8b7c4997 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h @@ -320,13 +320,13 @@ namespace AZ //! Recursively populates a material asset with properties from the tree of material property groups. //! @param materialTypeSourceFilePath path to the material type file that is being processed, used to look up relative paths - //! @param propertyNameContext the accumulated prefix that should be applied to any property names encountered in the current @propertyGroup + //! @param propertyIdContext the accumulated prefix that should be applied to any property names encountered in the current @propertyGroup //! @param propertyGroup the current PropertyGroup that is being processed //! @return false if errors are detected and processing should abort bool BuildPropertyList( const AZStd::string& materialTypeSourceFilePath, MaterialTypeAssetCreator& materialTypeAssetCreator, - AZStd::vector& propertyNameContext, + AZStd::vector& propertyIdContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) const; //! Construct a complete list of group definitions, including implicit groups, arranged in the same order as the source data. diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp index b9a5754732..b7808abf17 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp @@ -376,18 +376,18 @@ namespace AZ return parts; } - bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, AZStd::string propertyNameContext, const AZStd::vector>& inPropertyGroupList) const + bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, AZStd::string propertyIdContext, const AZStd::vector>& inPropertyGroupList) const { for (auto& propertyGroup : inPropertyGroupList) { - if (!callback(propertyNameContext, propertyGroup.get())) + if (!callback(propertyIdContext, propertyGroup.get())) { return false; // Stop processing } - const AZStd::string propertyNameContext2 = propertyNameContext + propertyGroup->m_name + "."; + const AZStd::string propertyIdContext2 = propertyIdContext + propertyGroup->m_name + "."; - if (!EnumeratePropertyGroups(callback, propertyNameContext2, propertyGroup->m_propertyGroups)) + if (!EnumeratePropertyGroups(callback, propertyIdContext2, propertyGroup->m_propertyGroups)) { return false; // Stop processing } @@ -406,22 +406,22 @@ namespace AZ return EnumeratePropertyGroups(callback, {}, m_propertyLayout.m_propertyGroups); } - bool MaterialTypeSourceData::EnumerateProperties(const EnumeratePropertiesCallback& callback, AZStd::string propertyNameContext, const AZStd::vector>& inPropertyGroupList) const + bool MaterialTypeSourceData::EnumerateProperties(const EnumeratePropertiesCallback& callback, AZStd::string propertyIdContext, const AZStd::vector>& inPropertyGroupList) const { for (auto& propertyGroup : inPropertyGroupList) { - const AZStd::string propertyNameContext2 = propertyNameContext + propertyGroup->m_name + "."; + const AZStd::string propertyIdContext2 = propertyIdContext + propertyGroup->m_name + "."; for (auto& property : propertyGroup->m_properties) { - if (!callback(propertyNameContext2, property.get())) + if (!callback(propertyIdContext2, property.get())) { return false; // Stop processing } } - if (!EnumerateProperties(callback, propertyNameContext2, propertyGroup->m_propertyGroups)) + if (!EnumerateProperties(callback, propertyIdContext2, propertyGroup->m_propertyGroups)) { return false; // Stop processing } @@ -532,14 +532,14 @@ namespace AZ bool MaterialTypeSourceData::BuildPropertyList( const AZStd::string& materialTypeSourceFilePath, MaterialTypeAssetCreator& materialTypeAssetCreator, - AZStd::vector& propertyNameContext, + AZStd::vector& propertyIdContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) const { for (const AZStd::unique_ptr& property : propertyGroup->m_properties) { // Register the property... - MaterialPropertyId propertyId{propertyNameContext, property->GetName()}; + MaterialPropertyId propertyId{propertyIdContext, property->GetName()}; if (!propertyId.IsValid()) { @@ -652,15 +652,15 @@ namespace AZ for (const AZStd::unique_ptr& propertySubset : propertyGroup->m_propertyGroups) { - propertyNameContext.push_back(propertySubset->m_name); + propertyIdContext.push_back(propertySubset->m_name); bool success = BuildPropertyList( materialTypeSourceFilePath, materialTypeAssetCreator, - propertyNameContext, + propertyIdContext, propertySubset.get()); - propertyNameContext.pop_back(); + propertyIdContext.pop_back(); if (!success) { @@ -797,9 +797,9 @@ namespace AZ for (const AZStd::unique_ptr& propertyGroup : m_propertyLayout.m_propertyGroups) { - AZStd::vector propertyNameContext; - propertyNameContext.push_back(propertyGroup->m_name); - bool success = BuildPropertyList(materialTypeSourceFilePath, materialTypeAssetCreator, propertyNameContext, propertyGroup.get()); + AZStd::vector propertyIdContext; + propertyIdContext.push_back(propertyGroup->m_name); + bool success = BuildPropertyList(materialTypeSourceFilePath, materialTypeAssetCreator, propertyIdContext, propertyGroup.get()); if (!success) { From a352807c87c891139bb57c396b2613504c1fef3f Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Tue, 1 Feb 2022 09:56:27 -0800 Subject: [PATCH 003/133] Renamed MaterialFunctor code to use propertyId instead of propertyName, because 'name' is us for the short name of a property and 'ID' is for the full name including groups. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../RPI.Reflect/Material/MaterialFunctor.h | 28 ++--- .../RPI.Reflect/Material/MaterialFunctor.cpp | 106 +++++++++--------- 2 files changed, 67 insertions(+), 67 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialFunctor.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialFunctor.h index 09d10bf538..92a9ab789a 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialFunctor.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialFunctor.h @@ -91,11 +91,11 @@ namespace AZ //! Get the property value. The type must be one of those in MaterialPropertyValue. //! Otherwise, a compile error will be reported. template - const Type& GetMaterialPropertyValue(const Name& propertyName) const; + const Type& GetMaterialPropertyValue(const Name& propertyId) const; template const Type& GetMaterialPropertyValue(const MaterialPropertyIndex& index) const; //! Get the property value. GetMaterialPropertyValue() is equivalent to GetMaterialPropertyValue().GetValue(). - const MaterialPropertyValue& GetMaterialPropertyValue(const Name& propertyName) const; + const MaterialPropertyValue& GetMaterialPropertyValue(const Name& propertyId) const; const MaterialPropertyValue& GetMaterialPropertyValue(const MaterialPropertyIndex& index) const; const MaterialPropertiesLayout* GetMaterialPropertiesLayout() const { return m_materialPropertiesLayout.get(); } @@ -164,19 +164,19 @@ namespace AZ { friend class LuaMaterialFunctorEditorContext; public: - const MaterialPropertyDynamicMetadata* GetMaterialPropertyMetadata(const Name& propertyName) const; + const MaterialPropertyDynamicMetadata* GetMaterialPropertyMetadata(const Name& propertyId) const; const MaterialPropertyDynamicMetadata* GetMaterialPropertyMetadata(const MaterialPropertyIndex& index) const; - const MaterialPropertyGroupDynamicMetadata* GetMaterialPropertyGroupMetadata(const Name& propertyName) const; + const MaterialPropertyGroupDynamicMetadata* GetMaterialPropertyGroupMetadata(const Name& propertyId) const; //! Get the property value. The type must be one of those in MaterialPropertyValue. //! Otherwise, a compile error will be reported. template - const Type& GetMaterialPropertyValue(const Name& propertyName) const; + const Type& GetMaterialPropertyValue(const Name& propertyId) const; template const Type& GetMaterialPropertyValue(const MaterialPropertyIndex& index) const; //! Get the property value. GetMaterialPropertyValue() is equivalent to GetMaterialPropertyValue().GetValue(). - const MaterialPropertyValue& GetMaterialPropertyValue(const Name& propertyName) const; + const MaterialPropertyValue& GetMaterialPropertyValue(const Name& propertyId) const; const MaterialPropertyValue& GetMaterialPropertyValue(const MaterialPropertyIndex& index) const; const MaterialPropertiesLayout* GetMaterialPropertiesLayout() const { return m_materialPropertiesLayout.get(); } @@ -184,22 +184,22 @@ namespace AZ MaterialPropertyPsoHandling GetMaterialPropertyPsoHandling() const { return MaterialPropertyPsoHandling::Allowed; } //! Set the visibility dynamic metadata of a material property. - bool SetMaterialPropertyVisibility(const Name& propertyName, MaterialPropertyVisibility visibility); + bool SetMaterialPropertyVisibility(const Name& propertyId, MaterialPropertyVisibility visibility); bool SetMaterialPropertyVisibility(const MaterialPropertyIndex& index, MaterialPropertyVisibility visibility); - bool SetMaterialPropertyDescription(const Name& propertyName, AZStd::string description); + bool SetMaterialPropertyDescription(const Name& propertyId, AZStd::string description); bool SetMaterialPropertyDescription(const MaterialPropertyIndex& index, AZStd::string description); - bool SetMaterialPropertyMinValue(const Name& propertyName, const MaterialPropertyValue& min); + bool SetMaterialPropertyMinValue(const Name& propertyId, const MaterialPropertyValue& min); bool SetMaterialPropertyMinValue(const MaterialPropertyIndex& index, const MaterialPropertyValue& min); - bool SetMaterialPropertyMaxValue(const Name& propertyName, const MaterialPropertyValue& max); + bool SetMaterialPropertyMaxValue(const Name& propertyId, const MaterialPropertyValue& max); bool SetMaterialPropertyMaxValue(const MaterialPropertyIndex& index, const MaterialPropertyValue& max); - bool SetMaterialPropertySoftMinValue(const Name& propertyName, const MaterialPropertyValue& min); + bool SetMaterialPropertySoftMinValue(const Name& propertyId, const MaterialPropertyValue& min); bool SetMaterialPropertySoftMinValue(const MaterialPropertyIndex& index, const MaterialPropertyValue& min); - bool SetMaterialPropertySoftMaxValue(const Name& propertyName, const MaterialPropertyValue& max); + bool SetMaterialPropertySoftMaxValue(const Name& propertyId, const MaterialPropertyValue& max); bool SetMaterialPropertySoftMaxValue(const MaterialPropertyIndex& index, const MaterialPropertyValue& max); bool SetMaterialPropertyGroupVisibility(const Name& propertyGroupName, MaterialPropertyGroupVisibility visibility); @@ -218,8 +218,8 @@ namespace AZ ); private: - MaterialPropertyDynamicMetadata* QueryMaterialPropertyMetadata(const Name& propertyName) const; - MaterialPropertyGroupDynamicMetadata* QueryMaterialPropertyGroupMetadata(const Name& propertyGroupName) const; + MaterialPropertyDynamicMetadata* QueryMaterialPropertyMetadata(const Name& propertyId) const; + MaterialPropertyGroupDynamicMetadata* QueryMaterialPropertyGroupMetadata(const Name& propertyGroupId) const; const AZStd::vector& m_materialPropertyValues; RHI::ConstPtr m_materialPropertiesLayout; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialFunctor.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialFunctor.cpp index 52b6349ca0..3d280b8d60 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialFunctor.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialFunctor.cpp @@ -155,9 +155,9 @@ namespace AZ , m_materialPropertyDependencies(materialPropertyDependencies) {} - const MaterialPropertyDynamicMetadata* MaterialFunctor::EditorContext::GetMaterialPropertyMetadata(const Name& propertyName) const + const MaterialPropertyDynamicMetadata* MaterialFunctor::EditorContext::GetMaterialPropertyMetadata(const Name& propertyId) const { - return QueryMaterialPropertyMetadata(propertyName); + return QueryMaterialPropertyMetadata(propertyId); } const MaterialPropertyDynamicMetadata* MaterialFunctor::EditorContext::GetMaterialPropertyMetadata(const MaterialPropertyIndex& index) const @@ -166,9 +166,9 @@ namespace AZ return GetMaterialPropertyMetadata(name); } - const MaterialPropertyGroupDynamicMetadata* MaterialFunctor::EditorContext::GetMaterialPropertyGroupMetadata(const Name& propertyName) const + const MaterialPropertyGroupDynamicMetadata* MaterialFunctor::EditorContext::GetMaterialPropertyGroupMetadata(const Name& propertyId) const { - return QueryMaterialPropertyGroupMetadata(propertyName); + return QueryMaterialPropertyGroupMetadata(propertyId); } bool MaterialFunctor::EditorContext::SetMaterialPropertyGroupVisibility(const Name& propertyGroupName, MaterialPropertyGroupVisibility visibility) @@ -188,9 +188,9 @@ namespace AZ return true; } - bool MaterialFunctor::EditorContext::SetMaterialPropertyVisibility(const Name& propertyName, MaterialPropertyVisibility visibility) + bool MaterialFunctor::EditorContext::SetMaterialPropertyVisibility(const Name& propertyId, MaterialPropertyVisibility visibility) { - MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyName); + MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyId); if (!metadata) { return false; @@ -199,7 +199,7 @@ namespace AZ if (metadata->m_visibility != visibility) { metadata->m_visibility = visibility; - m_updatedPropertiesOut.insert(propertyName); + m_updatedPropertiesOut.insert(propertyId); } return true; @@ -211,9 +211,9 @@ namespace AZ return SetMaterialPropertyVisibility(name, visibility); } - bool MaterialFunctor::EditorContext::SetMaterialPropertyDescription(const Name& propertyName, AZStd::string description) + bool MaterialFunctor::EditorContext::SetMaterialPropertyDescription(const Name& propertyId, AZStd::string description) { - MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyName); + MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyId); if (!metadata) { return false; @@ -222,7 +222,7 @@ namespace AZ if (metadata->m_description != description) { metadata->m_description = description; - m_updatedPropertiesOut.insert(propertyName); + m_updatedPropertiesOut.insert(propertyId); } return true; @@ -234,9 +234,9 @@ namespace AZ return SetMaterialPropertyDescription(name, description); } - bool MaterialFunctor::EditorContext::SetMaterialPropertyMinValue(const Name& propertyName, const MaterialPropertyValue& min) + bool MaterialFunctor::EditorContext::SetMaterialPropertyMinValue(const Name& propertyId, const MaterialPropertyValue& min) { - MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyName); + MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyId); if (!metadata) { return false; @@ -245,7 +245,7 @@ namespace AZ if(metadata->m_propertyRange.m_min != min) { metadata->m_propertyRange.m_min = min; - m_updatedPropertiesOut.insert(propertyName); + m_updatedPropertiesOut.insert(propertyId); } return true; @@ -257,9 +257,9 @@ namespace AZ return SetMaterialPropertyMinValue(name, min); } - bool MaterialFunctor::EditorContext::SetMaterialPropertyMaxValue(const Name& propertyName, const MaterialPropertyValue& max) + bool MaterialFunctor::EditorContext::SetMaterialPropertyMaxValue(const Name& propertyId, const MaterialPropertyValue& max) { - MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyName); + MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyId); if (!metadata) { return false; @@ -268,7 +268,7 @@ namespace AZ if (metadata->m_propertyRange.m_max != max) { metadata->m_propertyRange.m_max = max; - m_updatedPropertiesOut.insert(propertyName); + m_updatedPropertiesOut.insert(propertyId); } return true; @@ -280,9 +280,9 @@ namespace AZ return SetMaterialPropertyMaxValue(name, max); } - bool MaterialFunctor::EditorContext::SetMaterialPropertySoftMinValue(const Name& propertyName, const MaterialPropertyValue& min) + bool MaterialFunctor::EditorContext::SetMaterialPropertySoftMinValue(const Name& propertyId, const MaterialPropertyValue& min) { - MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyName); + MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyId); if (!metadata) { return false; @@ -291,7 +291,7 @@ namespace AZ if (metadata->m_propertyRange.m_softMin != min) { metadata->m_propertyRange.m_softMin = min; - m_updatedPropertiesOut.insert(propertyName); + m_updatedPropertiesOut.insert(propertyId); } return true; @@ -303,9 +303,9 @@ namespace AZ return SetMaterialPropertySoftMinValue(name, min); } - bool MaterialFunctor::EditorContext::SetMaterialPropertySoftMaxValue(const Name& propertyName, const MaterialPropertyValue& max) + bool MaterialFunctor::EditorContext::SetMaterialPropertySoftMaxValue(const Name& propertyId, const MaterialPropertyValue& max) { - MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyName); + MaterialPropertyDynamicMetadata* metadata = QueryMaterialPropertyMetadata(propertyId); if (!metadata) { return false; @@ -314,7 +314,7 @@ namespace AZ if (metadata->m_propertyRange.m_softMax != max) { metadata->m_propertyRange.m_softMax = max; - m_updatedPropertiesOut.insert(propertyName); + m_updatedPropertiesOut.insert(propertyId); } return true; @@ -326,24 +326,24 @@ namespace AZ return SetMaterialPropertySoftMaxValue(name, max); } - MaterialPropertyDynamicMetadata* MaterialFunctor::EditorContext::QueryMaterialPropertyMetadata(const Name& propertyName) const + MaterialPropertyDynamicMetadata* MaterialFunctor::EditorContext::QueryMaterialPropertyMetadata(const Name& propertyId) const { - auto it = m_propertyMetadata.find(propertyName); + auto it = m_propertyMetadata.find(propertyId); if (it == m_propertyMetadata.end()) { - AZ_Error("MaterialFunctor", false, "Couldn't find metadata for material property: %s.", propertyName.GetCStr()); + AZ_Error("MaterialFunctor", false, "Couldn't find metadata for material property: %s.", propertyId.GetCStr()); return nullptr; } return &it->second; } - MaterialPropertyGroupDynamicMetadata* MaterialFunctor::EditorContext::QueryMaterialPropertyGroupMetadata(const Name& propertyGroupName) const + MaterialPropertyGroupDynamicMetadata* MaterialFunctor::EditorContext::QueryMaterialPropertyGroupMetadata(const Name& propertyGroupId) const { - auto it = m_propertyGroupMetadata.find(propertyGroupName); + auto it = m_propertyGroupMetadata.find(propertyGroupId); if (it == m_propertyGroupMetadata.end()) { - AZ_Error("MaterialFunctor", false, "Couldn't find metadata for material property group: %s.", propertyGroupName.GetCStr()); + AZ_Error("MaterialFunctor", false, "Couldn't find metadata for material property group: %s.", propertyGroupId.GetCStr()); return nullptr; } @@ -357,20 +357,20 @@ namespace AZ } // explicit template instantiation - template const bool& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const int32_t& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const uint32_t& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const float& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Vector2& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Vector3& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Vector4& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Color& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Data::Instance& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue>(const Name& propertyName) const; + template const bool& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const int32_t& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const uint32_t& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const float& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Vector2& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Vector3& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Vector4& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Color& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Data::Instance& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue>(const Name& propertyId) const; template - const Type& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue(const Name& propertyName) const + const Type& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue(const Name& propertyId) const { - return GetMaterialPropertyValue(propertyName).GetValue(); + return GetMaterialPropertyValue(propertyId).GetValue(); } // explicit template instantiation @@ -391,19 +391,19 @@ namespace AZ } // explicit template instantiation - template const bool& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const int32_t& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const uint32_t& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const float& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Vector2& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Vector3& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Vector4& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyName) const; - template const Color& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyName) const; + template const bool& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const int32_t& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const uint32_t& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const float& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Vector2& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Vector3& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Vector4& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyId) const; + template const Color& MaterialFunctor::EditorContext::GetMaterialPropertyValue (const Name& propertyId) const; template - const Type& MaterialFunctor::EditorContext::GetMaterialPropertyValue(const Name& propertyName) const + const Type& MaterialFunctor::EditorContext::GetMaterialPropertyValue(const Name& propertyId) const { - return GetMaterialPropertyValue(propertyName).GetValue(); + return GetMaterialPropertyValue(propertyId).GetValue(); } // explicit template instantiation @@ -436,9 +436,9 @@ namespace AZ return m_materialPropertyValues[index.GetIndex()]; } - const MaterialPropertyValue& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue(const Name& propertyName) const + const MaterialPropertyValue& MaterialFunctor::RuntimeContext::GetMaterialPropertyValue(const Name& propertyId) const { - MaterialPropertyIndex index = m_materialPropertiesLayout->FindPropertyIndex(propertyName); + MaterialPropertyIndex index = m_materialPropertiesLayout->FindPropertyIndex(propertyId); return GetMaterialPropertyValue(index); } @@ -449,9 +449,9 @@ namespace AZ return m_materialPropertyValues[index.GetIndex()]; } - const MaterialPropertyValue& MaterialFunctor::EditorContext::GetMaterialPropertyValue(const Name& propertyName) const + const MaterialPropertyValue& MaterialFunctor::EditorContext::GetMaterialPropertyValue(const Name& propertyId) const { - MaterialPropertyIndex index = m_materialPropertiesLayout->FindPropertyIndex(propertyName); + MaterialPropertyIndex index = m_materialPropertiesLayout->FindPropertyIndex(propertyId); return GetMaterialPropertyValue(index); } From 2c59f1b8a47c312f9cd69b48023703fe994c8c36 Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Tue, 1 Feb 2022 16:35:42 -0800 Subject: [PATCH 004/133] Added support for deeply nested material property groups. The main addition here is the MaterialNameContext class which represents the concept of a namespace for properties, shader options, and SRG fields. This concept was already somewhat supported in LuaMaterialFunctor through bespoke "prefix" fields, but I have generalized it be available for all material functors. Note that I have not yet updated the other material functor types to ensure they take advantage of this feature, that will be in another commit. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../Material/LuaMaterialFunctorSourceData.h | 5 +- .../Material/MaterialFunctorSourceData.h | 48 +++- .../RPI.Edit/Material/MaterialPropertyId.h | 7 +- .../Material/MaterialTypeSourceData.h | 16 +- .../RPI.Reflect/Material/LuaMaterialFunctor.h | 31 +-- .../RPI.Reflect/Material/MaterialFunctor.h | 4 +- .../Material/MaterialNameContext.h | 59 +++++ .../RPI.Builders/Material/MaterialBuilder.cpp | 4 +- .../Material/LuaMaterialFunctorSourceData.cpp | 24 +- .../Material/MaterialFunctorSourceData.cpp | 36 ++- .../RPI.Edit/Material/MaterialPropertyId.cpp | 24 +- .../Material/MaterialTypeSourceData.cpp | 124 +++++----- .../RPI.Public/Material/MaterialSystem.cpp | 1 + .../Material/LuaMaterialFunctor.cpp | 57 +++-- .../Material/MaterialNameContext.cpp | 89 +++++++ .../Material/LuaMaterialFunctorTests.cpp | 5 +- .../Tests/Material/MaterialFunctorTests.cpp | 172 +++++++++++++- .../MaterialPropertyValueSourceDataTests.cpp | 6 +- .../Material/MaterialTypeSourceDataTests.cpp | 218 +++++++++++++++++- .../RPI/Code/atom_rpi_reflect_files.cmake | 2 + .../Code/Source/Document/MaterialDocument.cpp | 20 +- .../EditorMaterialComponentInspector.cpp | 6 +- .../Material/EditorMaterialComponentUtil.cpp | 7 +- 23 files changed, 801 insertions(+), 164 deletions(-) create mode 100644 Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h create mode 100644 Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/LuaMaterialFunctorSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/LuaMaterialFunctorSourceData.h index 7deda73c05..e08ee90fda 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/LuaMaterialFunctorSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/LuaMaterialFunctorSourceData.h @@ -41,7 +41,10 @@ namespace AZ // Calls a lua function that returns a list of strings. Outcome, void> GetNameListFromLuaScript(AZ::ScriptContext& scriptContext, const char* luaFunctionName) const; - FunctorResult CreateFunctor(const AZStd::string& materialTypeSourceFilePath, const MaterialPropertiesLayout* propertiesLayout) const; + FunctorResult CreateFunctor( + const AZStd::string& materialTypeSourceFilePath, + const MaterialPropertiesLayout* propertiesLayout, + const MaterialNameContext* materialNameContext) const; // Only one of these should have data AZStd::string m_luaSourceFile; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceData.h index a8f4f4c524..8bf88342c3 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceData.h @@ -31,6 +31,7 @@ namespace AZ class MaterialPropertiesLayout; class ShaderOptionGroupLayout; class JsonMaterialFunctorSourceDataSerializer; + class MaterialNameContext; //! This is an abstract base class for initializing MaterialFunctor objects. //! Material functors provide custom logic and calculations to configure shaders, render states, and more. @@ -54,11 +55,17 @@ namespace AZ struct RuntimeContext { public: - RuntimeContext(const AZStd::string& materialTypeFilePath, const MaterialPropertiesLayout* materialPropertiesLayout, const RHI::ShaderResourceGroupLayout* shaderResourceGroupLayout, const ShaderCollection* shaderCollection) + RuntimeContext( + const AZStd::string& materialTypeFilePath, + const MaterialPropertiesLayout* materialPropertiesLayout, + const RHI::ShaderResourceGroupLayout* shaderResourceGroupLayout, + const ShaderCollection* shaderCollection, + const MaterialNameContext* materialNameContext) : m_materialTypeFilePath(materialTypeFilePath) , m_materialPropertiesLayout(materialPropertiesLayout) , m_shaderResourceGroupLayout(shaderResourceGroupLayout) , m_shaderCollection(shaderCollection) + , m_materialNameContext(materialNameContext) {} const AZStd::string& GetMaterialTypeSourceFilePath() const { return m_materialTypeFilePath; } @@ -66,6 +73,10 @@ namespace AZ const MaterialPropertiesLayout* GetMaterialPropertiesLayout() const; const RHI::ShaderResourceGroupLayout* GetShaderResourceGroupLayout() const; + //! Find the index of a ShaderResourceGroup input. This will automatically apply the MaterialNameContext. + RHI::ShaderInputConstantIndex FindShaderInputConstantIndex(Name inputName) const; + RHI::ShaderInputImageIndex FindShaderInputImageIndex(Name inputName) const; + //! Returns the number of shaders available in this material type. AZStd::size_t GetShaderCount() const; @@ -77,16 +88,18 @@ namespace AZ AZStd::vector GetShaderTags() const; //! Find a property's index by its name. It will report error and return a Null index if it fails. - MaterialPropertyIndex FindMaterialPropertyIndex(const Name& propertyName) const; + //! This will also automatically apply the MaterialNameContext. + MaterialPropertyIndex FindMaterialPropertyIndex(Name propertyId) const; //! Find a shader option index using an option name from the shader by index or tag. + //! This will also automatically apply the MaterialNameContext. //! @param shaderIndex index into the material type's list of shader options //! @param shaderTag tag name to index into the material type's list of shader options //! @param optionName the name of the option to find //! @param reportErrors if true, report an error message when if the option name was not found. //! @return the found index, or an empty handle if the option could not be found - ShaderOptionIndex FindShaderOptionIndex(AZStd::size_t shaderIndex, const Name& optionName, bool reportErrors = true) const; - ShaderOptionIndex FindShaderOptionIndex(const AZ::Name& shaderTag, const Name& optionName, bool reportErrors = true) const; + ShaderOptionIndex FindShaderOptionIndex(AZStd::size_t shaderIndex, Name optionName, bool reportErrors = true) const; + ShaderOptionIndex FindShaderOptionIndex(const AZ::Name& shaderTag, Name optionName, bool reportErrors = true) const; //! Return true if a shaderIndex is within the range of the number of shaders defined in this material. //! And also report an error message if the index is invalid. @@ -96,19 +109,32 @@ namespace AZ //! And also report an error message if shaderTag is invalid. bool CheckShaderTagValid(const AZ::Name& shaderTag) const; + //! Returns the name context for the functor. + //! It acts like a namespace for any names that the MaterialFunctorSourceData might reference. The namespace + //! is automatically applied by the other relevant functions of this RuntimeContext class. + //! Not that by default the MaterialNameContext is not saved as part of the final MaterialFunctor class + //! (most CreateFunctor() implementations should convert names to indexes anyway) but CreateFunctor() can + //! copy it to the created MaterialFunctor for use at runtime if needed. + const MaterialNameContext* GetNameContext() const { return m_materialNameContext; } + private: const AZStd::string m_materialTypeFilePath; const MaterialPropertiesLayout* m_materialPropertiesLayout; const RHI::ShaderResourceGroupLayout* m_shaderResourceGroupLayout; const ShaderCollection* m_shaderCollection; + const MaterialNameContext* m_materialNameContext; }; struct EditorContext { public: - EditorContext(const AZStd::string& materialTypeFilePath, const MaterialPropertiesLayout* materialPropertiesLayout) + EditorContext( + const AZStd::string& materialTypeFilePath, + const MaterialPropertiesLayout* materialPropertiesLayout, + const MaterialNameContext* materialNameContext) : m_materialTypeFilePath(materialTypeFilePath) , m_materialPropertiesLayout(materialPropertiesLayout) + , m_materialNameContext(materialNameContext) {} const AZStd::string& GetMaterialTypeSourceFilePath() const { return m_materialTypeFilePath; } @@ -116,11 +142,21 @@ namespace AZ const MaterialPropertiesLayout* GetMaterialPropertiesLayout() const; //! Find a property's index by its name. It will report error and return a Null index if it fails. - MaterialPropertyIndex FindMaterialPropertyIndex(const Name& propertyName) const; + //! This will also automatically apply the MaterialNameContext. + MaterialPropertyIndex FindMaterialPropertyIndex(Name propertyId) const; + + //! Returns the name context for the functor. + //! It acts like a namespace for any names that the MaterialFunctorSourceData might reference. The namespace + //! is automatically applied by the other relevant functions of this RuntimeContext class. + //! Not that by default the MaterialNameContext is not saved as part of the final MaterialFunctor class + //! (most CreateFunctor() implementations should convert names to indexes anyway) but CreateFunctor() can + //! copy it to the created MaterialFunctor for use at runtime if needed. + const MaterialNameContext* GetNameContext() const { return m_materialNameContext; } private: const AZStd::string m_materialTypeFilePath; const MaterialPropertiesLayout* m_materialPropertiesLayout; + const MaterialNameContext* m_materialNameContext; }; //! Creates a fully initialized MaterialFunctor object that is ready to be serialized to the cache. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialPropertyId.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialPropertyId.h index 8c78d4b491..424a3a187a 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialPropertyId.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialPropertyId.h @@ -22,9 +22,14 @@ namespace AZ //! The groups are optional, in which case the full property ID will just be like "propertyName". class MaterialPropertyId { - public: + public: + //! Returns whether the name is a valid C-style identifier static bool IsValidName(AZStd::string_view name); static bool IsValidName(const AZ::Name& name); + + //! Returns whether the name is a valid C-style identifier, and reports errors if it is not. + static bool CheckIsValidName(AZStd::string_view name); + static bool CheckIsValidName(const AZ::Name& name); //! Creates a MaterialPropertyId from a full name string like "groupA.groupB.[...].propertyName" or just "propertyName". //! Also checks the name for validity. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h index 400556bf2f..70d92ffccf 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h @@ -158,6 +158,8 @@ namespace AZ AZStd::string m_name; AZStd::string m_displayName; AZStd::string m_description; + AZStd::string m_shaderInputsPrefix; //!< The name of all SRG inputs under this group will get this prefix. + AZStd::string m_shaderOptionsPrefix; //!< The name of all shader options under this group will get this prefix. PropertyList m_properties; AZStd::vector> m_propertyGroups; AZStd::vector> m_materialFunctorSourceData; @@ -282,7 +284,7 @@ namespace AZ //! Call back function type used with the enumeration functions. //! Return false to terminate the traversal. using EnumeratePropertyGroupsCallback = AZStd::function; @@ -293,7 +295,7 @@ namespace AZ //! Call back function type used with the numeration functions. //! Return false to terminate the traversal. using EnumeratePropertiesCallback = AZStd::function; @@ -316,10 +318,12 @@ namespace AZ PropertyDefinition* FindProperty(AZStd::span parsedPropertyId, AZStd::span> inPropertyGroupList); // Function overloads for recursion, returns false to indicate that recursion should end. - bool EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, AZStd::string propertyIdContext, const AZStd::vector>& inPropertyGroupList) const; - bool EnumerateProperties(const EnumeratePropertiesCallback& callback, AZStd::string propertyIdContext, const AZStd::vector>& inPropertyGroupList) const; + bool EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, MaterialNameContext materialNameContext, const AZStd::vector>& inPropertyGroupList) const; + bool EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext materialNameContext, const AZStd::vector>& inPropertyGroupList) const; + + static MaterialNameContext ExtendNameContext(MaterialNameContext nameContext, const MaterialTypeSourceData::PropertyGroup& propertyGroup); - //! Recursively populates a material asset with properties from the tree of material property groups. + //! Recursively populates a material type asset with properties from the tree of material property groups. //! @param materialTypeSourceFilePath path to the material type file that is being processed, used to look up relative paths //! @param propertyIdContext the accumulated prefix that should be applied to any property names encountered in the current @propertyGroup //! @param propertyGroup the current PropertyGroup that is being processed @@ -327,7 +331,7 @@ namespace AZ bool BuildPropertyList( const AZStd::string& materialTypeSourceFilePath, MaterialTypeAssetCreator& materialTypeAssetCreator, - AZStd::vector& propertyIdContext, + MaterialNameContext materialNameContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) const; //! Construct a complete list of group definitions, including implicit groups, arranged in the same order as the source data. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/LuaMaterialFunctor.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/LuaMaterialFunctor.h index 5f4dce40e5..1bce036c73 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/LuaMaterialFunctor.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/LuaMaterialFunctor.h @@ -10,6 +10,7 @@ #include #include +#include #include namespace UnitTest @@ -60,12 +61,8 @@ namespace AZ AZStd::unique_ptr m_sriptBehaviorContext; AZStd::unique_ptr m_scriptContext; - // These are prefix strings that will be applied to every name lookup in the lua functor. - // This allows the lua script to be reused in different contexts. - AZStd::string m_propertyNamePrefix; - AZStd::string m_srgNamePrefix; - AZStd::string m_optionsNamePrefix; - + MaterialNameContext m_materialNameContext; + enum class ScriptStatus { Uninitialized, @@ -84,15 +81,11 @@ namespace AZ explicit LuaMaterialFunctorCommonContext(MaterialFunctor::RuntimeContext* runtimeContextImpl, const MaterialPropertyFlags* materialPropertyDependencies, - const AZStd::string& propertyNamePrefix, - const AZStd::string& srgNamePrefix, - const AZStd::string& optionsNamePrefix); + const MaterialNameContext &materialNameContext); explicit LuaMaterialFunctorCommonContext(MaterialFunctor::EditorContext* editorContextImpl, const MaterialPropertyFlags* materialPropertyDependencies, - const AZStd::string& propertyNamePrefix, - const AZStd::string& srgNamePrefix, - const AZStd::string& optionsNamePrefix); + const MaterialNameContext &materialNameContext); //! Returns false if PSO changes are not allowed, and may report errors or warnings bool CheckPsoChangesAllowed(); @@ -112,11 +105,7 @@ namespace AZ AZStd::string GetMaterialPropertyDependenciesString() const; - // These are prefix strings that will be applied to every name lookup in the lua functor. - // This allows the lua script to be reused in different contexts. - const AZStd::string& m_propertyNamePrefix; - const AZStd::string& m_srgNamePrefix; - const AZStd::string& m_optionsNamePrefix; + const MaterialNameContext &m_materialNameContext; private: @@ -284,9 +273,7 @@ namespace AZ explicit LuaMaterialFunctorRuntimeContext(MaterialFunctor::RuntimeContext* runtimeContextImpl, const MaterialPropertyFlags* materialPropertyDependencies, - const AZStd::string& propertyNamePrefix, - const AZStd::string& srgNamePrefix, - const AZStd::string& optionsNamePrefix); + const MaterialNameContext &materialNameContext); template Type GetMaterialPropertyValue(const char* name) const; @@ -324,9 +311,7 @@ namespace AZ explicit LuaMaterialFunctorEditorContext(MaterialFunctor::EditorContext* editorContextImpl, const MaterialPropertyFlags* materialPropertyDependencies, - const AZStd::string& propertyNamePrefix, - const AZStd::string& srgNamePrefix, - const AZStd::string& optionsNamePrefix); + const MaterialNameContext &materialNameContext); template Type GetMaterialPropertyValue(const char* name) const; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialFunctor.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialFunctor.h index 92a9ab789a..459dd601f9 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialFunctor.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialFunctor.h @@ -49,8 +49,8 @@ namespace AZ //! MaterialFunctor objects provide custom logic and calculations to configure shaders, render states, //! editor metadata, and more. - //! Atom will provide an implementation of this class that uses a script to define the custom logic - //! for a convenient workflow. Clients may also provide their own custom hard-coded implementations + //! Atom provides a LuaMaterialFunctor subclass that uses a script to define the custom logic + //! for a convenient workflow. Developers may also provide their own custom hard-coded implementations //! as an optimization rather than taking the scripted approach. //! Any custom subclasses of MaterialFunctor will also need a corresponding MaterialFunctorSourceData subclass //! to create the functor at build-time. Depending on the builder context, clients can choose to create a runtime diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h new file mode 100644 index 0000000000..3ecdfeb449 --- /dev/null +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include + +namespace AZ +{ + class ReflectContext; + class Name; + + namespace RPI + { + //! This acts like a namespace description for various types of identifiers that appear in .materialtype files. + //! When reusable property groups are nested inside other property groups, they usually need alternate naming + //! to connect to the appropriate shader inputs. For example, a baseColor property group inside a "layer1" group + //! needs to connect to "m_layer1_baseColor_texture" and the same property definition is repeated inside a "layer2" + //! group where it connects to "m_layer2_baseColor_texture". This data structure provides the name context, like + //! "m_layer1_" or "m_layer2_". + class MaterialNameContext + { + public: + AZ_TYPE_INFO(MaterialNameContext, "{AAC9BB28-F463-455D-8467-F877E50E1FA7}") + + static void Reflect(ReflectContext* context); + + MaterialNameContext() = default; + + //! Extends the name context to a deeper property group. + void ExtendPropertyIdContext(AZStd::string_view nameContext, bool insertDelimiter=true); + void ExtendSrgInputContext(AZStd::string_view nameContext); + void ExtendShaderOptionContext(AZStd::string_view nameContext); + + //! Applies the name context to a given leaf name. + bool ContextualizeProperty(Name& propertyName) const; + bool ContextualizeSrgInput(Name& srgInputName) const; + bool ContextualizeShaderOption(Name& shaderOptionName) const; + + //! Returns true if there is some non-default name context. + bool HasContextForProperties() const { return !m_propertyIdContext.empty(); } + bool HasContextForSrgInputs() const { return !m_srgInputNameContext.empty(); } + bool HasContextForShaderOptions() const { return !m_shaderOptionNameContext.empty(); } + + //! Returns true if the name context is empty. + bool IsDefault() const; + + private: + AZStd::string m_propertyIdContext; + AZStd::string m_srgInputNameContext; + AZStd::string m_shaderOptionNameContext; + }; + + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp index c81b91d777..bf65a09cef 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp @@ -51,7 +51,7 @@ namespace AZ { AssetBuilderSDK::AssetBuilderDesc materialBuilderDescriptor; materialBuilderDescriptor.m_name = JobKey; - materialBuilderDescriptor.m_version = 117; // new material type file format + materialBuilderDescriptor.m_version = 122; // nested property layers materialBuilderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern("*.material", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); materialBuilderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern("*.materialtype", AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); materialBuilderDescriptor.m_busId = azrtti_typeid(); @@ -269,7 +269,7 @@ namespace AZ response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; } - AZ::Data::Asset CreateMaterialTypeAsset(AZStd::string_view materialTypeSourceFilePath, const rapidjson::Value& json) + AZ::Data::Asset CreateMaterialTypeAsset(AZStd::string_view materialTypeSourceFilePath, rapidjson::Document& json) { auto materialType = MaterialUtils::LoadMaterialTypeSourceData(materialTypeSourceFilePath, &json); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp index 14ef3bb17d..c614222ee6 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp @@ -115,16 +115,26 @@ namespace AZ RPI::LuaMaterialFunctorSourceData::FunctorResult LuaMaterialFunctorSourceData::CreateFunctor( const AZStd::string& materialTypeSourceFilePath, - const MaterialPropertiesLayout* propertiesLayout + const MaterialPropertiesLayout* propertiesLayout, + const MaterialNameContext* materialNameContext ) const { using namespace RPI; RPI::Ptr functor = aznew LuaMaterialFunctor; - functor->m_propertyNamePrefix = m_propertyNamePrefix; - functor->m_srgNamePrefix = m_srgNamePrefix; - functor->m_optionsNamePrefix = m_optionsNamePrefix; + if (materialNameContext->IsDefault()) + { + // This is a legacy feature that was used for a while to support reusing the same functor for multiple layers in StandardMultilayerPbr.materialtype. + // Now that we have support for nested property groups, this functionality is only supported for functors at the top level, for backward compatibility. + functor->m_materialNameContext.ExtendPropertyIdContext(m_propertyNamePrefix, false); + functor->m_materialNameContext.ExtendSrgInputContext(m_srgNamePrefix); + functor->m_materialNameContext.ExtendShaderOptionContext(m_optionsNamePrefix); + } + else + { + functor->m_materialNameContext = *materialNameContext; + } if (!m_luaScript.empty() && !m_luaSourceFile.empty()) { @@ -205,14 +215,16 @@ namespace AZ { return CreateFunctor( context.GetMaterialTypeSourceFilePath(), - context.GetMaterialPropertiesLayout()); + context.GetMaterialPropertiesLayout(), + context.GetNameContext()); } RPI::LuaMaterialFunctorSourceData::FunctorResult LuaMaterialFunctorSourceData::CreateFunctor(const EditorContext& context) const { return CreateFunctor( context.GetMaterialTypeSourceFilePath(), - context.GetMaterialPropertiesLayout()); + context.GetMaterialPropertiesLayout(), + context.GetNameContext()); } } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceData.cpp index 36217af1b6..cdc75b8c05 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialFunctorSourceData.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -66,17 +67,20 @@ namespace AZ return m_shaderResourceGroupLayout; } - MaterialPropertyIndex MaterialFunctorSourceData::RuntimeContext::FindMaterialPropertyIndex(const Name& propertyName) const + MaterialPropertyIndex MaterialFunctorSourceData::RuntimeContext::FindMaterialPropertyIndex(Name propertyId) const { - MaterialPropertyIndex propertyIndex = m_materialPropertiesLayout->FindPropertyIndex(propertyName); + m_materialNameContext->ContextualizeProperty(propertyId); + MaterialPropertyIndex propertyIndex = m_materialPropertiesLayout->FindPropertyIndex(propertyId); - AZ_Error("MaterialFunctorSourceData", propertyIndex.IsValid(), "Could not find property '%s'.", propertyName.GetCStr()); + AZ_Error("MaterialFunctorSourceData", propertyIndex.IsValid(), "Could not find property '%s'.", propertyId.GetCStr()); return propertyIndex; } - ShaderOptionIndex MaterialFunctorSourceData::RuntimeContext::FindShaderOptionIndex(AZStd::size_t shaderIndex, const Name& optionName, bool reportErrors) const + ShaderOptionIndex MaterialFunctorSourceData::RuntimeContext::FindShaderOptionIndex(AZStd::size_t shaderIndex, Name optionName, bool reportErrors) const { + m_materialNameContext->ContextualizeShaderOption(optionName); + const ShaderOptionGroupLayout* shaderOptionGroupLayout = GetShaderOptionGroupLayout(shaderIndex); if (shaderOptionGroupLayout) @@ -92,8 +96,10 @@ namespace AZ return ShaderOptionIndex(); } - AZ::RPI::ShaderOptionIndex MaterialFunctorSourceData::RuntimeContext::FindShaderOptionIndex(const AZ::Name& shaderTag, const Name& optionName, bool reportErrors /*= true*/) const + AZ::RPI::ShaderOptionIndex MaterialFunctorSourceData::RuntimeContext::FindShaderOptionIndex(const AZ::Name& shaderTag, Name optionName, bool reportErrors /*= true*/) const { + m_materialNameContext->ContextualizeShaderOption(optionName); + const ShaderOptionGroupLayout* shaderOptionGroupLayout = GetShaderOptionGroupLayout(shaderTag); if (shaderOptionGroupLayout) @@ -122,19 +128,33 @@ namespace AZ AZ_Error("MaterialFunctorSourceData", valid, "Shader tag '%s' is invalid", shaderTag.GetCStr()); return valid; } + + RHI::ShaderInputConstantIndex MaterialFunctorSourceData::RuntimeContext::FindShaderInputConstantIndex(Name inputName) const + { + m_materialNameContext->ContextualizeSrgInput(inputName); + return m_shaderResourceGroupLayout->FindShaderInputConstantIndex(inputName); + } + + RHI::ShaderInputImageIndex MaterialFunctorSourceData::RuntimeContext::FindShaderInputImageIndex(Name inputName) const + { + m_materialNameContext->ContextualizeSrgInput(inputName); + return m_shaderResourceGroupLayout->FindShaderInputImageIndex(inputName); + } const MaterialPropertiesLayout* MaterialFunctorSourceData::EditorContext::GetMaterialPropertiesLayout() const { return m_materialPropertiesLayout; } - MaterialPropertyIndex MaterialFunctorSourceData::EditorContext::FindMaterialPropertyIndex(const Name& propertyName) const + MaterialPropertyIndex MaterialFunctorSourceData::EditorContext::FindMaterialPropertyIndex(Name propertyId) const { - MaterialPropertyIndex propertyIndex = m_materialPropertiesLayout->FindPropertyIndex(propertyName); + m_materialNameContext->ContextualizeProperty(propertyId); + MaterialPropertyIndex propertyIndex = m_materialPropertiesLayout->FindPropertyIndex(propertyId); - AZ_Error("MaterialFunctorSourceData", propertyIndex.IsValid(), "Could not find property '%s'", propertyName.GetCStr()); + AZ_Error("MaterialFunctorSourceData", propertyIndex.IsValid(), "Could not find property '%s'", propertyId.GetCStr()); return propertyIndex; } + } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialPropertyId.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialPropertyId.cpp index 1f5581e417..843fa44dd7 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialPropertyId.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialPropertyId.cpp @@ -25,11 +25,29 @@ namespace AZ return IsValidName(name.GetStringView()); } + bool MaterialPropertyId::CheckIsValidName(AZStd::string_view name) + { + if (IsValidName(name)) + { + return true; + } + else + { + AZ_Error("MaterialPropertyId", false, "'%.*s' is not a valid identifier", AZ_STRING_ARG(name)); + return false; + } + } + + bool MaterialPropertyId::CheckIsValidName(const AZ::Name& name) + { + return CheckIsValidName(name.GetStringView()); + } + bool MaterialPropertyId::IsValid() const { return !m_fullName.IsEmpty(); } - + MaterialPropertyId MaterialPropertyId::Parse(AZStd::string_view fullPropertyId) { AZStd::vector tokens; @@ -94,14 +112,14 @@ namespace AZ { if (!IsValidName(name)) { - AZ_Error("MaterialPropertyId", false, "'%s' is not a valid identifier.", name.c_str()); + AZ_Error("MaterialPropertyId", false, "Group name '%s' is not a valid identifier.", name.c_str()); return; } } if (!IsValidName(propertyName)) { - AZ_Error("MaterialPropertyId", false, "'%.*s' is not a valid identifier.", AZ_STRING_ARG(propertyName)); + AZ_Error("MaterialPropertyId", false, "Property name '%.*s' is not a valid identifier.", AZ_STRING_ARG(propertyName)); return; } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp index b7808abf17..9b251213fe 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -89,10 +90,12 @@ namespace AZ ; serializeContext->Class() - ->Version(1) + ->Version(2) ->Field("name", &PropertyGroup::m_name) ->Field("displayName", &PropertyGroup::m_displayName) ->Field("description", &PropertyGroup::m_description) + ->Field("shaderInputsPrefix", &PropertyGroup::m_shaderInputsPrefix) + ->Field("shaderOptionsPrefix", &PropertyGroup::m_shaderOptionsPrefix) ->Field("properties", &PropertyGroup::m_properties) ->Field("propertyGroups", &PropertyGroup::m_propertyGroups) ->Field("functors", &PropertyGroup::m_materialFunctorSourceData) @@ -134,22 +137,21 @@ namespace AZ /*static*/ MaterialTypeSourceData::PropertyGroup* MaterialTypeSourceData::PropertyGroup::AddPropertyGroup(AZStd::string_view name, AZStd::vector>& toPropertyGroupList) { + if (!MaterialPropertyId::CheckIsValidName(name)) + { + return nullptr; + } + auto iter = AZStd::find_if(toPropertyGroupList.begin(), toPropertyGroupList.end(), [name](const AZStd::unique_ptr& existingPropertyGroup) { return existingPropertyGroup->m_name == name; }); - + if (iter != toPropertyGroupList.end()) { AZ_Error("Material source data", false, "PropertyGroup named '%.*s' already exists", AZ_STRING_ARG(name)); return nullptr; } - - if (!MaterialPropertyId::IsValidName(name)) - { - AZ_Error("Material source data", false, "'%.*s' is not a valid identifier", AZ_STRING_ARG(name)); - return nullptr; - } toPropertyGroupList.push_back(AZStd::make_unique()); toPropertyGroupList.back()->m_name = name; @@ -158,6 +160,11 @@ namespace AZ MaterialTypeSourceData::PropertyDefinition* MaterialTypeSourceData::PropertyGroup::AddProperty(AZStd::string_view name) { + if (!MaterialPropertyId::CheckIsValidName(name)) + { + return nullptr; + } + auto propertyIter = AZStd::find_if(m_properties.begin(), m_properties.end(), [name](const AZStd::unique_ptr& existingProperty) { return existingProperty->GetName() == name; @@ -180,12 +187,6 @@ namespace AZ return nullptr; } - if (!MaterialPropertyId::IsValidName(name)) - { - AZ_Error("Material source data", false, "'%.*s' is not a valid identifier", AZ_STRING_ARG(name)); - return nullptr; - } - m_properties.emplace_back(AZStd::make_unique(name)); return m_properties.back().get(); } @@ -265,10 +266,10 @@ namespace AZ if (!subPath.empty()) { - const MaterialTypeSourceData::PropertyGroup* propertySubset = FindPropertyGroup(subPath, propertyGroup->m_propertyGroups); - if (propertySubset) + const MaterialTypeSourceData::PropertyGroup* propertySubgroup = FindPropertyGroup(subPath, propertyGroup->m_propertyGroups); + if (propertySubgroup) { - return propertySubset; + return propertySubgroup; } } } @@ -376,18 +377,18 @@ namespace AZ return parts; } - bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, AZStd::string propertyIdContext, const AZStd::vector>& inPropertyGroupList) const + bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, MaterialNameContext materialNameContext, const AZStd::vector>& inPropertyGroupList) const { for (auto& propertyGroup : inPropertyGroupList) { - if (!callback(propertyIdContext, propertyGroup.get())) + if (!callback(materialNameContext, propertyGroup.get())) { return false; // Stop processing } + + MaterialNameContext materialNameContext2 = ExtendNameContext(materialNameContext, *propertyGroup); - const AZStd::string propertyIdContext2 = propertyIdContext + propertyGroup->m_name + "."; - - if (!EnumeratePropertyGroups(callback, propertyIdContext2, propertyGroup->m_propertyGroups)) + if (!EnumeratePropertyGroups(callback, materialNameContext2, propertyGroup->m_propertyGroups)) { return false; // Stop processing } @@ -406,22 +407,21 @@ namespace AZ return EnumeratePropertyGroups(callback, {}, m_propertyLayout.m_propertyGroups); } - bool MaterialTypeSourceData::EnumerateProperties(const EnumeratePropertiesCallback& callback, AZStd::string propertyIdContext, const AZStd::vector>& inPropertyGroupList) const + bool MaterialTypeSourceData::EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext materialNameContext, const AZStd::vector>& inPropertyGroupList) const { - for (auto& propertyGroup : inPropertyGroupList) { - const AZStd::string propertyIdContext2 = propertyIdContext + propertyGroup->m_name + "."; + MaterialNameContext materialNameContext2 = ExtendNameContext(materialNameContext, *propertyGroup); for (auto& property : propertyGroup->m_properties) { - if (!callback(propertyIdContext2, property.get())) + if (!callback(materialNameContext2, property.get())) { return false; // Stop processing } } - if (!EnumerateProperties(callback, propertyIdContext2, propertyGroup->m_propertyGroups)) + if (!EnumerateProperties(callback, materialNameContext2, propertyGroup->m_propertyGroups)) { return false; // Stop processing } @@ -483,7 +483,7 @@ namespace AZ enumValues.push_back(uvNamePair.second); } - EnumerateProperties([&enumValues](const AZStd::string&, const MaterialTypeSourceData::PropertyDefinition* property) + EnumerateProperties([&enumValues](const MaterialNameContext&, const MaterialTypeSourceData::PropertyDefinition* property) { if (property->m_dataType == AZ::RPI::MaterialPropertyDataType::Enum && property->m_enumIsUv) { @@ -529,24 +529,40 @@ namespace AZ return groupDefinitions; } + MaterialNameContext MaterialTypeSourceData::ExtendNameContext(MaterialNameContext nameContext, const MaterialTypeSourceData::PropertyGroup& propertyGroup) + { + MaterialNameContext materialNameContext2 = nameContext; + materialNameContext2.ExtendPropertyIdContext(propertyGroup.m_name); + materialNameContext2.ExtendShaderOptionContext(propertyGroup.m_shaderOptionsPrefix); + materialNameContext2.ExtendSrgInputContext(propertyGroup.m_shaderInputsPrefix); + return materialNameContext2; + } + bool MaterialTypeSourceData::BuildPropertyList( const AZStd::string& materialTypeSourceFilePath, MaterialTypeAssetCreator& materialTypeAssetCreator, - AZStd::vector& propertyIdContext, + MaterialNameContext materialNameContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) const - { + { + if (!MaterialPropertyId::CheckIsValidName(propertyGroup->m_name)) + { + return false; + } + + materialNameContext = ExtendNameContext(materialNameContext, *propertyGroup); + for (const AZStd::unique_ptr& property : propertyGroup->m_properties) { // Register the property... - MaterialPropertyId propertyId{propertyIdContext, property->GetName()}; - - if (!propertyId.IsValid()) + if (!MaterialPropertyId::CheckIsValidName(property->GetName())) { - // MaterialPropertyId reports an error message return false; } + Name propertyId{property->GetName()}; + materialNameContext.ContextualizeProperty(propertyId); + auto propertyGroupIter = AZStd::find_if(propertyGroup->GetPropertyGroups().begin(), propertyGroup->GetPropertyGroups().end(), [&property](const AZStd::unique_ptr& existingPropertyGroup) { @@ -572,18 +588,23 @@ namespace AZ { case MaterialPropertyOutputType::ShaderInput: { - materialTypeAssetCreator.ConnectMaterialPropertyToShaderInput(Name{output.m_fieldName}); + Name fieldName{output.m_fieldName}; + materialNameContext.ContextualizeSrgInput(fieldName); + materialTypeAssetCreator.ConnectMaterialPropertyToShaderInput(fieldName); break; } case MaterialPropertyOutputType::ShaderOption: { + Name fieldName{output.m_fieldName}; + materialNameContext.ContextualizeShaderOption(fieldName); + if (output.m_shaderIndex >= 0) { - materialTypeAssetCreator.ConnectMaterialPropertyToShaderOption(Name{output.m_fieldName}, output.m_shaderIndex); + materialTypeAssetCreator.ConnectMaterialPropertyToShaderOption(fieldName, output.m_shaderIndex); } else { - materialTypeAssetCreator.ConnectMaterialPropertyToShaderOptions(Name{output.m_fieldName}); + materialTypeAssetCreator.ConnectMaterialPropertyToShaderOptions(fieldName); } break; } @@ -650,17 +671,13 @@ namespace AZ } } - for (const AZStd::unique_ptr& propertySubset : propertyGroup->m_propertyGroups) + for (const AZStd::unique_ptr& propertySubgroup : propertyGroup->m_propertyGroups) { - propertyIdContext.push_back(propertySubset->m_name); - bool success = BuildPropertyList( materialTypeSourceFilePath, materialTypeAssetCreator, - propertyIdContext, - propertySubset.get()); - - propertyIdContext.pop_back(); + materialNameContext, + propertySubgroup.get()); if (!success) { @@ -677,7 +694,8 @@ namespace AZ materialTypeSourceFilePath, materialTypeAssetCreator.GetMaterialPropertiesLayout(), materialTypeAssetCreator.GetMaterialShaderResourceGroupLayout(), - materialTypeAssetCreator.GetShaderCollection() + materialTypeAssetCreator.GetShaderCollection(), + &materialNameContext ) ); @@ -688,9 +706,10 @@ namespace AZ { materialTypeAssetCreator.AddMaterialFunctor(functor); - for (const AZ::Name& optionName : functorData->GetActualSourceData()->GetShaderOptionDependencies()) + for (AZ::Name optionName : functorData->GetActualSourceData()->GetShaderOptionDependencies()) { - materialTypeAssetCreator.ClaimShaderOptionOwnership(Name{optionName.GetCStr()}); + materialNameContext.ContextualizeShaderOption(optionName); + materialTypeAssetCreator.ClaimShaderOptionOwnership(optionName); } } } @@ -795,11 +814,9 @@ namespace AZ } } - for (const AZStd::unique_ptr& propertyGroup : m_propertyLayout.m_propertyGroups) + for (const AZStd::unique_ptr& propertyGroup : m_propertyLayout.m_propertyGroups) { - AZStd::vector propertyIdContext; - propertyIdContext.push_back(propertyGroup->m_name); - bool success = BuildPropertyList(materialTypeSourceFilePath, materialTypeAssetCreator, propertyIdContext, propertyGroup.get()); + bool success = BuildPropertyList(materialTypeSourceFilePath, materialTypeAssetCreator, MaterialNameContext{}, propertyGroup.get()); if (!success) { @@ -807,6 +824,8 @@ namespace AZ } } + MaterialNameContext nameContext; + // We cannot create the MaterialFunctor until after all the properties are added because // CreateFunctor() may need to look up properties in the MaterialPropertiesLayout for (auto& functorData : m_materialFunctorSourceData) @@ -816,7 +835,8 @@ namespace AZ materialTypeSourceFilePath, materialTypeAssetCreator.GetMaterialPropertiesLayout(), materialTypeAssetCreator.GetMaterialShaderResourceGroupLayout(), - materialTypeAssetCreator.GetShaderCollection() + materialTypeAssetCreator.GetShaderCollection(), + &nameContext ) ); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Material/MaterialSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Material/MaterialSystem.cpp index b76fa9d676..ae7fe6cc60 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Material/MaterialSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Material/MaterialSystem.cpp @@ -27,6 +27,7 @@ namespace AZ MaterialAsset::Reflect(context); MaterialPropertiesLayout::Reflect(context); MaterialFunctor::Reflect(context); + MaterialNameContext::Reflect(context); LuaMaterialFunctor::Reflect(context); ReflectMaterialDynamicMetadata(context); } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp index 4212583e60..7eedb82ecc 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp @@ -29,9 +29,7 @@ namespace AZ serializeContext->Class() ->Version(1) ->Field("scriptAsset", &LuaMaterialFunctor::m_scriptAsset) - ->Field("propertyNamePrefix", &LuaMaterialFunctor::m_propertyNamePrefix) - ->Field("srgNamePrefix", &LuaMaterialFunctor::m_srgNamePrefix) - ->Field("optionsNamePrefix", &LuaMaterialFunctor::m_optionsNamePrefix) + ->Field("materialNameContext", &LuaMaterialFunctor::m_materialNameContext) ; } } @@ -127,7 +125,7 @@ namespace AZ if (m_scriptStatus == ScriptStatus::Ready) { - LuaMaterialFunctorRuntimeContext luaContext{&context, &GetMaterialPropertyDependencies(), m_propertyNamePrefix, m_srgNamePrefix, m_optionsNamePrefix}; + LuaMaterialFunctorRuntimeContext luaContext{&context, &GetMaterialPropertyDependencies(), m_materialNameContext}; AZ::ScriptDataContext call; if (m_scriptContext->Call("Process", call)) { @@ -145,7 +143,7 @@ namespace AZ if (m_scriptStatus == ScriptStatus::Ready) { - LuaMaterialFunctorEditorContext luaContext{&context, &GetMaterialPropertyDependencies(), m_propertyNamePrefix, m_srgNamePrefix, m_optionsNamePrefix}; + LuaMaterialFunctorEditorContext luaContext{&context, &GetMaterialPropertyDependencies(), m_materialNameContext}; AZ::ScriptDataContext call; if (m_scriptContext->Call("ProcessEditor", call)) { @@ -157,27 +155,19 @@ namespace AZ LuaMaterialFunctorCommonContext::LuaMaterialFunctorCommonContext(MaterialFunctor::RuntimeContext* runtimeContextImpl, const MaterialPropertyFlags* materialPropertyDependencies, - const AZStd::string& propertyNamePrefix, - const AZStd::string& srgNamePrefix, - const AZStd::string& optionsNamePrefix) + const MaterialNameContext& materialNameContext) : m_runtimeContextImpl(runtimeContextImpl) , m_materialPropertyDependencies(materialPropertyDependencies) - , m_propertyNamePrefix(propertyNamePrefix) - , m_srgNamePrefix(srgNamePrefix) - , m_optionsNamePrefix(optionsNamePrefix) + , m_materialNameContext(materialNameContext) { } LuaMaterialFunctorCommonContext::LuaMaterialFunctorCommonContext(MaterialFunctor::EditorContext* editorContextImpl, const MaterialPropertyFlags* materialPropertyDependencies, - const AZStd::string& propertyNamePrefix, - const AZStd::string& srgNamePrefix, - const AZStd::string& optionsNamePrefix) + const MaterialNameContext& materialNameContext) : m_editorContextImpl(editorContextImpl) , m_materialPropertyDependencies(materialPropertyDependencies) - , m_propertyNamePrefix(propertyNamePrefix) - , m_srgNamePrefix(srgNamePrefix) - , m_optionsNamePrefix(optionsNamePrefix) + , m_materialNameContext(materialNameContext) { } @@ -256,7 +246,8 @@ namespace AZ { MaterialPropertyIndex propertyIndex; - Name propertyFullName{m_propertyNamePrefix + name}; + Name propertyFullName{name}; + m_materialNameContext.ContextualizeProperty(propertyFullName); propertyIndex = GetMaterialPropertiesLayout()->FindPropertyIndex(propertyFullName); @@ -361,10 +352,8 @@ namespace AZ LuaMaterialFunctorRuntimeContext::LuaMaterialFunctorRuntimeContext(MaterialFunctor::RuntimeContext* runtimeContextImpl, const MaterialPropertyFlags* materialPropertyDependencies, - const AZStd::string& propertyNamePrefix, - const AZStd::string& srgNamePrefix, - const AZStd::string& optionsNamePrefix) - : LuaMaterialFunctorCommonContext(runtimeContextImpl, materialPropertyDependencies, propertyNamePrefix, srgNamePrefix, optionsNamePrefix) + const MaterialNameContext& materialNameContext) + : LuaMaterialFunctorCommonContext(runtimeContextImpl, materialPropertyDependencies, materialNameContext) , m_runtimeContextImpl(runtimeContextImpl) { } @@ -379,7 +368,8 @@ namespace AZ { bool didSetOne = false; - Name fullOptionName{m_optionsNamePrefix + name}; + Name fullOptionName{name}; + m_materialNameContext.ContextualizeShaderOption(fullOptionName); for (AZStd::size_t i = 0; i < m_runtimeContextImpl->m_shaderCollection->size(); ++i) { @@ -429,7 +419,8 @@ namespace AZ RHI::ShaderInputConstantIndex LuaMaterialFunctorRuntimeContext::GetShaderInputConstantIndex(const char* name, const char* functionName) const { - Name fullInputName{m_srgNamePrefix + name}; + Name fullInputName{name}; + m_materialNameContext.ContextualizeSrgInput(fullInputName); RHI::ShaderInputConstantIndex index = m_runtimeContextImpl->m_shaderResourceGroup->FindShaderInputConstantIndex(fullInputName); @@ -524,10 +515,8 @@ namespace AZ LuaMaterialFunctorEditorContext::LuaMaterialFunctorEditorContext(MaterialFunctor::EditorContext* editorContextImpl, const MaterialPropertyFlags* materialPropertyDependencies, - const AZStd::string& propertyNamePrefix, - const AZStd::string& srgNamePrefix, - const AZStd::string& optionsNamePrefix) - : LuaMaterialFunctorCommonContext(editorContextImpl, materialPropertyDependencies, propertyNamePrefix, srgNamePrefix, optionsNamePrefix) + const MaterialNameContext& materialNameContext) + : LuaMaterialFunctorCommonContext(editorContextImpl, materialPropertyDependencies, materialNameContext) , m_editorContextImpl(editorContextImpl) { } @@ -598,7 +587,9 @@ namespace AZ { if (m_editorContextImpl) { - return m_editorContextImpl->SetMaterialPropertyGroupVisibility(Name{m_propertyNamePrefix + name}, visibility); + Name fullName{name}; + m_materialNameContext.ContextualizeProperty(fullName); + return m_editorContextImpl->SetMaterialPropertyGroupVisibility(fullName, visibility); } return false; } @@ -607,7 +598,9 @@ namespace AZ { if (m_editorContextImpl) { - return m_editorContextImpl->SetMaterialPropertyVisibility(Name{m_propertyNamePrefix + name}, visibility); + Name fullName{name}; + m_materialNameContext.ContextualizeProperty(fullName); + return m_editorContextImpl->SetMaterialPropertyVisibility(fullName, visibility); } return false; } @@ -616,7 +609,9 @@ namespace AZ { if (m_editorContextImpl) { - return m_editorContextImpl->SetMaterialPropertyDescription(Name{m_propertyNamePrefix + name}, description); + Name fullName{name}; + m_materialNameContext.ContextualizeProperty(fullName); + return m_editorContextImpl->SetMaterialPropertyDescription(fullName, description); } return false; } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp new file mode 100644 index 0000000000..bf457a0a93 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp @@ -0,0 +1,89 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include + +namespace AZ +{ + namespace RPI + { + void MaterialNameContext::Reflect(ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("propertyIdContext", &MaterialNameContext::m_propertyIdContext) + ->Field("srgInputNameContext", &MaterialNameContext::m_srgInputNameContext) + ->Field("shaderOptionNameContext", &MaterialNameContext::m_shaderOptionNameContext) + ; + } + } + + bool MaterialNameContext::IsDefault() const + { + return m_propertyIdContext.empty() && m_srgInputNameContext.empty() && m_shaderOptionNameContext.empty(); + } + + void MaterialNameContext::ExtendPropertyIdContext(AZStd::string_view nameContext, bool insertDelimiter) + { + m_propertyIdContext += nameContext; + if (insertDelimiter && !nameContext.empty() && !nameContext.ends_with(".")) + { + m_propertyIdContext += "."; + } + } + + void MaterialNameContext::ExtendSrgInputContext(AZStd::string_view nameContext) + { + m_srgInputNameContext += nameContext; + } + + void MaterialNameContext::ExtendShaderOptionContext(AZStd::string_view nameContext) + { + m_shaderOptionNameContext += nameContext; + } + + bool MaterialNameContext::ContextualizeProperty(Name& propertyName) const + { + if (m_propertyIdContext.empty()) + { + return false; + } + + propertyName = m_propertyIdContext + propertyName.GetCStr(); + return true; + } + + bool MaterialNameContext::ContextualizeSrgInput(Name& srgInputName) const + { + if (m_srgInputNameContext.empty()) + { + return false; + } + + srgInputName = m_srgInputNameContext + srgInputName.GetCStr(); + return true; + } + + bool MaterialNameContext::ContextualizeShaderOption(Name& shaderOptionName) const + { + if (m_shaderOptionNameContext.empty()) + { + return false; + } + + shaderOptionName = m_shaderOptionNameContext + shaderOptionName.GetCStr(); + return true; + } + + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Tests/Material/LuaMaterialFunctorTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/LuaMaterialFunctorTests.cpp index 15f66916a6..1ed920ebc0 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/LuaMaterialFunctorTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/LuaMaterialFunctorTests.cpp @@ -35,11 +35,14 @@ namespace UnitTest LuaMaterialFunctorSourceData functorSourceData; functorSourceData.m_luaScript = script; + MaterialNameContext nameContext; + MaterialFunctorSourceData::RuntimeContext createFunctorContext{ "Dummy.materialtype", materialTypeCreator.GetMaterialPropertiesLayout(), materialTypeCreator.GetMaterialShaderResourceGroupLayout(), - materialTypeCreator.GetShaderCollection() + materialTypeCreator.GetShaderCollection(), + &nameContext }; MaterialFunctorSourceData::FunctorResult result = functorSourceData.CreateFunctor(createFunctorContext); diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialFunctorTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialFunctorTests.cpp index 08049f3393..dbf911b09a 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialFunctorTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialFunctorTests.cpp @@ -15,6 +15,8 @@ #include #include #include +#include +#include #include #include #include @@ -256,12 +258,15 @@ namespace UnitTest functorSourceData.m_registedPropertyName = registedPropertyName.GetStringView(); functorSourceData.m_unregistedPropertyName = unregistedPropertyName.GetStringView(); + MaterialNameContext nameContext; + MaterialFunctorSourceData::FunctorResult result = functorSourceData.CreateFunctor( MaterialFunctorSourceData::RuntimeContext( "Dummy.materialtype", materialTypeCreator.GetMaterialPropertiesLayout(), materialTypeCreator.GetMaterialShaderResourceGroupLayout(), - materialTypeCreator.GetShaderCollection() + materialTypeCreator.GetShaderCollection(), + &nameContext ) ); @@ -310,4 +315,169 @@ namespace UnitTest m_testMaterialTypeAsset = {}; m_testMaterialAsset = {}; } + + TEST_F(MaterialFunctorTests, UseNameContextInFunctorSourceData_PropertyLookup) + { + class FindPropertyIndexTestFunctor : public MaterialFunctor + { + public: + MaterialPropertyIndex m_foundIndex; + }; + + class FindPropertyIndexTestFunctorSourceData : public MaterialFunctorSourceData + { + public: + Name m_materialPropertyName; + + using MaterialFunctorSourceData::CreateFunctor; + FunctorResult CreateFunctor(const RuntimeContext& runtimeContext) const override + { + RPI::Ptr functor = aznew FindPropertyIndexTestFunctor; + functor->m_foundIndex = runtimeContext.FindMaterialPropertyIndex(m_materialPropertyName); + return Success(RPI::Ptr(functor)); + } + }; + + Data::Asset materialTypeAsset; + MaterialTypeAssetCreator materialTypeCreator; + materialTypeCreator.Begin(Uuid::CreateRandom()); + materialTypeCreator.BeginMaterialProperty(Name{"layer1.baseColor.factor"}, MaterialPropertyDataType::Float); + materialTypeCreator.EndMaterialProperty(); + materialTypeCreator.End(materialTypeAsset); + + FindPropertyIndexTestFunctorSourceData sourceData; + sourceData.m_materialPropertyName = "factor"; + + MaterialNameContext nameContext; + nameContext.ExtendPropertyIdContext("layer1"); + nameContext.ExtendPropertyIdContext("baseColor"); + + MaterialFunctorSourceData::RuntimeContext createFunctorContext( + "", + materialTypeAsset->GetMaterialPropertiesLayout(), + nullptr, + nullptr, + &nameContext); + + RPI::Ptr functor = sourceData.CreateFunctor(createFunctorContext).TakeValue(); + + EXPECT_TRUE(reinterpret_cast(functor.get())->m_foundIndex.IsValid()); + } + + TEST_F(MaterialFunctorTests, UseNameContextInFunctorSourceData_ShaderOptionLookup) + { + class FindShaderOptionIndexTestFunctor : public MaterialFunctor + { + public: + ShaderOptionIndex m_foundIndex; + }; + + class FindShaderOptionIndexTestFunctorSourceData : public MaterialFunctorSourceData + { + public: + Name m_shaderOptionName; + + using MaterialFunctorSourceData::CreateFunctor; + FunctorResult CreateFunctor(const RuntimeContext& runtimeContext) const override + { + RPI::Ptr functor = aznew FindShaderOptionIndexTestFunctor; + functor->m_foundIndex = runtimeContext.FindShaderOptionIndex(0, m_shaderOptionName); + return Success(RPI::Ptr(functor)); + } + }; + + RPI::Ptr shaderOptionLayout = RPI::ShaderOptionGroupLayout::Create(); + shaderOptionLayout->AddShaderOption( + RPI::ShaderOptionDescriptor{Name("o_layer1_baseColor_useTexture"), RPI::ShaderOptionType::Boolean, 0, 0, CreateBoolShaderOptionValues()}); + shaderOptionLayout->Finalize(); + + Data::Asset shaderAsset = CreateTestShaderAsset(Uuid::CreateRandom(), nullptr, shaderOptionLayout); + + Data::Asset materialTypeAsset; + MaterialTypeAssetCreator materialTypeCreator; + materialTypeCreator.Begin(Uuid::CreateRandom()); + materialTypeCreator.AddShader(shaderAsset); + materialTypeCreator.End(materialTypeAsset); + + FindShaderOptionIndexTestFunctorSourceData sourceData; + sourceData.m_shaderOptionName = "useTexture"; + + MaterialNameContext nameContext; + nameContext.ExtendShaderOptionContext("o_layer1_baseColor_"); + + MaterialFunctorSourceData::RuntimeContext createFunctorContext( + "", + nullptr, + nullptr, + &materialTypeAsset->GetShaderCollection(), + &nameContext); + + RPI::Ptr functor = sourceData.CreateFunctor(createFunctorContext).TakeValue(); + + EXPECT_TRUE(reinterpret_cast(functor.get())->m_foundIndex.IsValid()); + } + + TEST_F(MaterialFunctorTests, UseNameContextInFunctorSourceData_ShaderConstantLookup) + { + class FindShaderInputIndexTestFunctor : public MaterialFunctor + { + public: + RHI::ShaderInputConstantIndex m_foundConstantIndex; + RHI::ShaderInputImageIndex m_foundImageIndex; + }; + + class FindShaderInputIndexTestFunctorSourceData : public MaterialFunctorSourceData + { + public: + Name m_shaderConstantName; + Name m_shaderImageName; + + using MaterialFunctorSourceData::CreateFunctor; + FunctorResult CreateFunctor(const RuntimeContext& runtimeContext) const override + { + RPI::Ptr functor = aznew FindShaderInputIndexTestFunctor; + functor->m_foundConstantIndex = runtimeContext.FindShaderInputConstantIndex(m_shaderConstantName); + functor->m_foundImageIndex = runtimeContext.FindShaderInputImageIndex(m_shaderImageName); + return Success(RPI::Ptr(functor)); + } + }; + + AZ::RHI::Ptr srgLayout = RHI::ShaderResourceGroupLayout::Create(); + srgLayout->SetName(Name("MaterialSrg")); + srgLayout->SetUniqueId(Uuid::CreateRandom().ToString()); // Any random string will suffice. + srgLayout->SetBindingSlot(SrgBindingSlot::Material); + srgLayout->AddShaderInput(RHI::ShaderInputConstantDescriptor{Name{ "m_layer1_baseColor_factor" }, 0, 4, 0}); + srgLayout->AddShaderInput(RHI::ShaderInputImageDescriptor{Name{ "m_layer1_baseColor_texture" }, RHI::ShaderInputImageAccess::Read, RHI::ShaderInputImageType::Image2D, 1, 1}); + srgLayout->Finalize(); + + Data::Asset shaderAsset = CreateTestShaderAsset(Uuid::CreateRandom(), srgLayout); + + Data::Asset materialTypeAsset; + MaterialTypeAssetCreator materialTypeCreator; + materialTypeCreator.Begin(Uuid::CreateRandom()); + materialTypeCreator.AddShader(shaderAsset); + materialTypeCreator.End(materialTypeAsset); + + FindShaderInputIndexTestFunctorSourceData sourceData; + sourceData.m_shaderConstantName = "factor"; + sourceData.m_shaderImageName = "texture"; + + MaterialNameContext nameContext; + nameContext.ExtendSrgInputContext("m_layer1_baseColor_"); + + MaterialFunctorSourceData::RuntimeContext createFunctorContext( + "", + nullptr, + srgLayout.get(), + nullptr, + &nameContext); + + RPI::Ptr functor = sourceData.CreateFunctor(createFunctorContext).TakeValue(); + + EXPECT_TRUE(reinterpret_cast(functor.get())->m_foundConstantIndex.IsValid()); + EXPECT_TRUE(reinterpret_cast(functor.get())->m_foundImageIndex.IsValid()); + } + + + } diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialPropertyValueSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialPropertyValueSourceDataTests.cpp index 5dde21ece1..f67a58cf97 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialPropertyValueSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialPropertyValueSourceDataTests.cpp @@ -19,6 +19,7 @@ #include #include #include +#include namespace JsonSerializationTests { @@ -256,13 +257,16 @@ namespace UnitTest JsonTestResult loadResult = LoadTestDataFromJson(*functorData, inputJson); + MaterialNameContext nameContext; + // Where type resolving happens. MaterialFunctorSourceData::FunctorResult functorResult = functorData->CreateFunctor( MaterialFunctorSourceData::RuntimeContext( "Dummy.materialtype", m_materialTypeCreator.GetMaterialPropertiesLayout(), m_materialTypeCreator.GetMaterialShaderResourceGroupLayout(), - m_materialTypeCreator.GetShaderCollection() + m_materialTypeCreator.GetShaderCollection(), + &nameContext ) ); diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp index 5be02df935..98a86fe9ce 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -252,6 +253,57 @@ namespace UnitTest AZStd::string m_enablePropertyName; }; + // All this functor does is save the MaterialNameContext + class SaveNameContextTestFunctor final + : public AZ::RPI::MaterialFunctor + { + public: + AZ_RTTI(SaveNameContextTestFunctor, "{FD680069-B430-4278-9E5B-A2B9617627D5}", AZ::RPI::MaterialFunctor); + + static void Reflect(AZ::ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("nameContext", &SaveNameContextTestFunctor::m_nameContext); + } + } + + using AZ::RPI::MaterialFunctor::Process; + void Process(AZ::RPI::MaterialFunctor::RuntimeContext&) override + { + } + + MaterialNameContext m_nameContext; + }; + + // All this functor does is save the MaterialNameContext + class SaveNameContextTestFunctorSourceData final + : public MaterialFunctorSourceData + { + public: + AZ_RTTI(SaveNameContextTestFunctorSourceData, "{4261A2EC-4AB6-420E-884A-18D1A36500BE}", MaterialFunctorSourceData); + + static void Reflect(AZ::ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ; + } + } + + using MaterialFunctorSourceData::CreateFunctor; + FunctorResult CreateFunctor([[maybe_unused]] const RuntimeContext& context) const override + { + Ptr functor = aznew SaveNameContextTestFunctor; + functor->m_nameContext = *context.GetNameContext(); + return Success(Ptr(functor)); + } + }; + ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Reflect(ReflectContext* context) override @@ -265,6 +317,7 @@ namespace UnitTest Splat3FunctorSourceData::Reflect(context); EnableShaderFunctorSourceData::Reflect(context); SetShaderOptionFunctorSourceData::Reflect(context); + SaveNameContextTestFunctorSourceData::Reflect(context); } void SetUp() override @@ -276,6 +329,7 @@ namespace UnitTest AZ::RPI::MaterialFunctorSourceDataRegistration::Get()->RegisterMaterialFunctor("Splat3", azrtti_typeid()); AZ::RPI::MaterialFunctorSourceDataRegistration::Get()->RegisterMaterialFunctor("EnableShader", azrtti_typeid()); AZ::RPI::MaterialFunctorSourceDataRegistration::Get()->RegisterMaterialFunctor("SetShaderOption", azrtti_typeid()); + AZ::RPI::MaterialFunctorSourceDataRegistration::Get()->RegisterMaterialFunctor("SaveNameContext", azrtti_typeid()); const Name materialSrgId{"MaterialSrg"}; m_testMaterialSrgLayout = RHI::ShaderResourceGroupLayout::Create(); @@ -432,20 +486,25 @@ namespace UnitTest struct EnumeratePropertyGroupsResult { - AZStd::string m_propertyIdContext; + MaterialNameContext m_materialNameContext; const MaterialTypeSourceData::PropertyGroup* m_propertyGroup; void Check(AZStd::string expectedIdContext, const MaterialTypeSourceData::PropertyGroup* expectedPropertyGroup) { - EXPECT_EQ(expectedIdContext, m_propertyIdContext); + Name groupFullId{m_propertyGroup->GetName()}; + m_materialNameContext.ContextualizeProperty(groupFullId); + + AZStd::string expectedPropertyId = expectedIdContext + expectedPropertyGroup->GetName(); + + EXPECT_EQ(expectedPropertyId, groupFullId.GetStringView()); EXPECT_EQ(expectedPropertyGroup, m_propertyGroup); } }; AZStd::vector enumeratePropertyGroupsResults; - sourceData.EnumeratePropertyGroups([&enumeratePropertyGroupsResults](const AZStd::string& propertyIdContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) + sourceData.EnumeratePropertyGroups([&enumeratePropertyGroupsResults](const MaterialNameContext& materialNameContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) { - enumeratePropertyGroupsResults.push_back(EnumeratePropertyGroupsResult{propertyIdContext, propertyGroup}); + enumeratePropertyGroupsResults.push_back(EnumeratePropertyGroupsResult{materialNameContext, propertyGroup}); return true; }); @@ -466,20 +525,25 @@ namespace UnitTest struct EnumeratePropertiesResult { - AZStd::string m_propertyIdContext; + MaterialNameContext m_materialNameContext; const MaterialTypeSourceData::PropertyDefinition* m_propertyDefinition; void Check(AZStd::string expectedIdContext, const MaterialTypeSourceData::PropertyDefinition* expectedPropertyDefinition) { - EXPECT_EQ(expectedIdContext, m_propertyIdContext); + Name propertyFullId{m_propertyDefinition->GetName()}; + m_materialNameContext.ContextualizeProperty(propertyFullId); + + AZStd::string expectedPropertyId = expectedIdContext + expectedPropertyDefinition->GetName(); + + EXPECT_EQ(expectedPropertyId, propertyFullId.GetStringView()); EXPECT_EQ(expectedPropertyDefinition, m_propertyDefinition); } }; AZStd::vector enumeratePropertiesResults; - sourceData.EnumerateProperties([&enumeratePropertiesResults](const AZStd::string& propertyIdContext, const MaterialTypeSourceData::PropertyDefinition* propertyDefinition) + sourceData.EnumerateProperties([&enumeratePropertiesResults](const MaterialNameContext& materialNameContext, const MaterialTypeSourceData::PropertyDefinition* propertyDefinition) { - enumeratePropertiesResults.push_back(EnumeratePropertiesResult{propertyIdContext, propertyDefinition}); + enumeratePropertiesResults.push_back(EnumeratePropertiesResult{materialNameContext, propertyDefinition}); return true; }); @@ -1469,7 +1533,7 @@ namespace UnitTest // Note that serialization of individual fields within material properties is thoroughly tested in // MaterialPropertySerializerTests, so the sample property data used here is cursory. // We also don't cover fields related to providing name contexts for nested property groups, like - // "shaderInputPrefix" and "shaderOptionPrefix" as those are covered in CreateMaterialTypeAsset_NestedGroups*. + // "shaderInputsPrefix" and "shaderOptionsPrefix" as those are covered in CreateMaterialTypeAsset_NestedGroups*. const AZStd::string inputJson = R"( { @@ -2014,4 +2078,140 @@ namespace UnitTest EXPECT_EQ(materialType.FindProperty("myGroup.bar")->m_dataType, MaterialPropertyDataType::Float); } + TEST_F(MaterialTypeSourceDataTests, CreateMaterialTypeAsset_NestedGroupNameContext) + { + const Name materialSrgId{"MaterialSrg"}; + RHI::Ptr materialSrgLayout = RHI::ShaderResourceGroupLayout::Create(); + materialSrgLayout->SetName(materialSrgId); + materialSrgLayout->SetBindingSlot(SrgBindingSlot::Material); + materialSrgLayout->AddShaderInput(RHI::ShaderInputImageDescriptor{ Name{ "m_unused1" }, RHI::ShaderInputImageAccess::Read, RHI::ShaderInputImageType::Image2D, 1, 1 }); + materialSrgLayout->AddShaderInput(RHI::ShaderInputImageDescriptor{ Name{ "m_unused2" }, RHI::ShaderInputImageAccess::Read, RHI::ShaderInputImageType::Image2D, 1, 1 }); + materialSrgLayout->AddShaderInput(RHI::ShaderInputImageDescriptor{ Name{ "m_groupA_m_groupB_m_texture" }, RHI::ShaderInputImageAccess::Read, RHI::ShaderInputImageType::Image2D, 1, 1 }); + EXPECT_TRUE(materialSrgLayout->Finalize()); + + Ptr shaderOptions = ShaderOptionGroupLayout::Create(); + shaderOptions->AddShaderOption(ShaderOptionDescriptor{Name{"o_unused"}, ShaderOptionType::Boolean, 0, 0, CreateBoolShaderOptionValues()}); + shaderOptions->AddShaderOption(ShaderOptionDescriptor{Name{"o_groupA_o_groupB_o_useTexture"}, ShaderOptionType::Boolean, 1, 1, CreateBoolShaderOptionValues()}); + shaderOptions->AddShaderOption(ShaderOptionDescriptor{Name{"o_groupA_o_groupB_o_useTextureAlt"}, ShaderOptionType::Boolean, 2, 2, CreateBoolShaderOptionValues()}); + shaderOptions->Finalize(); + + Data::Asset shaderAsset = CreateTestShaderAsset(Uuid::CreateRandom(), materialSrgLayout, shaderOptions); + + Data::AssetInfo testShaderAssetInfo; + testShaderAssetInfo.m_assetId = shaderAsset.GetId(); + m_assetSystemStub.RegisterSourceInfo("NestedGroupNameContext.shader", testShaderAssetInfo, ""); + + const AZStd::string materialTypeJson = R"( + { + "propertyLayout": { + "propertyGroups": [ + { + "name": "groupA", + "shaderInputsPrefix": "m_groupA_", + "shaderOptionsPrefix": "o_groupA_", + "propertyGroups": [ + { + "name": "groupB", + "shaderInputsPrefix": "m_groupB_", + "shaderOptionsPrefix": "o_groupB_", + "propertyGroups": [ + { + "name": "groupC", + "properties": [ + { + "name": "textureMap", + "type": "Image", + "connection": { + "type": "ShaderInput", + "name": "m_texture" + } + }, + { + "name": "useTextureMap", + "type": "Bool", + "connection": [ + { + "type": "ShaderOption", + "name": "o_useTexture" + }, + { + "type": "ShaderOption", + "name": "o_useTextureAlt", + "shaderIndex": 0 // Having a specific shaderIndex traverses a different code path + } + ] + } + ], + "functors": [ + { + "type": "SaveNameContext" + } + ] + } + ] + } + ] + } + ] + }, + "shaders": [ + { + "file": "NestedGroupNameContext.shader" + } + ] + } + )"; + + MaterialTypeSourceData materialTypeSourceData; + JsonTestResult loadResult = LoadTestDataFromJson(materialTypeSourceData, materialTypeJson); + + auto materialTypeAssetOutcome = materialTypeSourceData.CreateMaterialTypeAsset(Uuid::CreateRandom()); + EXPECT_TRUE(materialTypeAssetOutcome.IsSuccess()); + + Data::Asset materialTypeAsset = materialTypeAssetOutcome.TakeValue(); + const MaterialPropertiesLayout* propertiesLayout = materialTypeAsset->GetMaterialPropertiesLayout(); + + EXPECT_EQ(2, propertiesLayout->GetPropertyCount()); + + EXPECT_EQ(0, propertiesLayout->FindPropertyIndex(Name("groupA.groupB.groupC.textureMap")).GetIndex()); + EXPECT_EQ(1, propertiesLayout->FindPropertyIndex(Name("groupA.groupB.groupC.useTextureMap")).GetIndex()); + + // groupA.gropuB.groupC.textureMap has a connection to m_groupA_m_groupB_m_texture + MaterialPropertyIndex texturePropertyIndex{0}; + EXPECT_EQ(1, propertiesLayout->GetPropertyDescriptor(texturePropertyIndex)->GetOutputConnections().size()); + EXPECT_EQ(materialSrgLayout->FindShaderInputImageIndex(Name("m_groupA_m_groupB_m_texture")).GetIndex(), + propertiesLayout->GetPropertyDescriptor(texturePropertyIndex)->GetOutputConnections()[0].m_itemIndex.GetIndex()); + + // groupA.gropuB.groupC.useTextureMap has a connection to o_groupA_o_groupB_o_useTexture and o_groupA_o_groupB_o_useTextureAlt + MaterialPropertyIndex useTexturePropertyIndex{1}; + EXPECT_EQ(2, propertiesLayout->GetPropertyDescriptor(useTexturePropertyIndex)->GetOutputConnections().size()); + EXPECT_EQ(shaderOptions->FindShaderOptionIndex(Name("o_groupA_o_groupB_o_useTexture")).GetIndex(), + propertiesLayout->GetPropertyDescriptor(useTexturePropertyIndex)->GetOutputConnections()[0].m_itemIndex.GetIndex()); + EXPECT_EQ(shaderOptions->FindShaderOptionIndex(Name("o_groupA_o_groupB_o_useTextureAlt")).GetIndex(), + propertiesLayout->GetPropertyDescriptor(useTexturePropertyIndex)->GetOutputConnections()[1].m_itemIndex.GetIndex()); + + // There should be one functor, which processes useTextureMap, and it should have the appropriate name context for constructing the correct full names. + EXPECT_EQ(1, materialTypeAsset->GetMaterialFunctors().size()); + + EXPECT_TRUE(azrtti_istypeof(materialTypeAsset->GetMaterialFunctors()[0].get())); + + auto saveNameContextFunctor = azrtti_cast(materialTypeAsset->GetMaterialFunctors()[0].get()); + const MaterialNameContext& nameContext = saveNameContextFunctor->m_nameContext; + + Name textureMapProperty{"textureMap"}; + Name textureMapShaderInput{"m_texture"}; + Name useTextureMapProperty{"useTextureMap"}; + Name useTextureShaderOption{"o_useTexture"}; + + nameContext.ContextualizeProperty(textureMapProperty); + nameContext.ContextualizeProperty(useTextureMapProperty); + nameContext.ContextualizeSrgInput(textureMapShaderInput); + nameContext.ContextualizeShaderOption(useTextureShaderOption); + + EXPECT_EQ("groupA.groupB.groupC.useTextureMap", useTextureMapProperty.GetStringView()); + EXPECT_EQ("o_groupA_o_groupB_o_useTexture", useTextureShaderOption.GetStringView()); + EXPECT_EQ("groupA.groupB.groupC.textureMap", textureMapProperty.GetStringView()); + EXPECT_EQ("m_groupA_m_groupB_m_texture", textureMapShaderInput.GetStringView()); + } + } diff --git a/Gems/Atom/RPI/Code/atom_rpi_reflect_files.cmake b/Gems/Atom/RPI/Code/atom_rpi_reflect_files.cmake index 6e9cdfeb4e..c28911f4af 100644 --- a/Gems/Atom/RPI/Code/atom_rpi_reflect_files.cmake +++ b/Gems/Atom/RPI/Code/atom_rpi_reflect_files.cmake @@ -53,6 +53,7 @@ set(FILES Include/Atom/RPI.Reflect/Material/MaterialAsset.h Include/Atom/RPI.Reflect/Material/MaterialAssetCreator.h Include/Atom/RPI.Reflect/Material/MaterialDynamicMetadata.h + Include/Atom/RPI.Reflect/Material/MaterialNameContext.h Include/Atom/RPI.Reflect/Material/MaterialPropertyDescriptor.h Include/Atom/RPI.Reflect/Material/MaterialPropertiesLayout.h Include/Atom/RPI.Reflect/Material/MaterialPropertyValue.h @@ -133,6 +134,7 @@ set(FILES Source/RPI.Reflect/Material/MaterialPropertyValue.cpp Source/RPI.Reflect/Material/MaterialAsset.cpp Source/RPI.Reflect/Material/MaterialAssetCreator.cpp + Source/RPI.Reflect/Material/MaterialNameContext.cpp Source/RPI.Reflect/Material/LuaMaterialFunctor.cpp Source/RPI.Reflect/Material/MaterialDynamicMetadata.cpp Source/RPI.Reflect/Material/MaterialPropertyDescriptor.cpp diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index c441762710..aaad77266c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -585,9 +586,10 @@ namespace MaterialEditor bool result = true; // populate sourceData with properties that meet the filter - m_materialTypeSourceData.EnumerateProperties([&](const AZStd::string& propertyIdContext, const auto& propertyDefinition) { + m_materialTypeSourceData.EnumerateProperties([&](const MaterialNameContext& materialNameContext, const auto& propertyDefinition) { - Name propertyId{propertyIdContext + propertyDefinition->GetName()}; + Name propertyId{propertyDefinition->GetName()}; + materialNameContext.ContextualizeProperty(propertyId); const auto it = m_properties.find(propertyId); if (it != m_properties.end() && propertyFilter(it->second)) @@ -781,14 +783,17 @@ namespace MaterialEditor // Populate the property map from a combination of source data and assets // Assets must still be used for now because they contain the final accumulated value after all other materials // in the hierarchy are applied - m_materialTypeSourceData.EnumeratePropertyGroups([this, &parentPropertyValues](const AZStd::string& propertyIdContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) + m_materialTypeSourceData.EnumeratePropertyGroups([this, &parentPropertyValues](const MaterialNameContext& materialNameContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) { AtomToolsFramework::DynamicPropertyConfig propertyConfig; for (const auto& propertyDefinition : propertyGroup->GetProperties()) { // Assign id before conversion so it can be used in dynamic description - propertyConfig.m_id = propertyIdContext + propertyGroup->GetName() + "." + propertyDefinition->GetName(); + MaterialNameContext groupNameContext = materialNameContext; + groupNameContext.ExtendPropertyIdContext(propertyGroup->GetName()); + propertyConfig.m_id = propertyDefinition->GetName(); + groupNameContext.ContextualizeProperty(propertyConfig.m_id); const auto& propertyIndex = m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); const bool propertyIndexInBounds = propertyIndex.IsValid() && propertyIndex.GetIndex() < m_materialAsset->GetPropertyValues().size(); @@ -878,8 +883,9 @@ namespace MaterialEditor } // Add material functors that are in the top-level functors list. + AZ::RPI::MaterialNameContext materialNameContext; // There is no name context for top-level functors, only functors inside PropertyGroups const MaterialFunctorSourceData::EditorContext editorContext = - MaterialFunctorSourceData::EditorContext(m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout()); + MaterialFunctorSourceData::EditorContext(m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout(), &materialNameContext); for (Ptr functorData : m_materialTypeSourceData.m_materialFunctorSourceData) { MaterialFunctorSourceData::FunctorResult result2 = functorData->CreateFunctor(editorContext); @@ -901,10 +907,10 @@ namespace MaterialEditor // Add any material functors that are located inside each property group. bool enumerateResult = m_materialTypeSourceData.EnumeratePropertyGroups( - [this](const AZStd::string&, const MaterialTypeSourceData::PropertyGroup* propertyGroup) + [this](const MaterialNameContext& nameContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) { const MaterialFunctorSourceData::EditorContext editorContext = MaterialFunctorSourceData::EditorContext( - m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout()); + m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout(), &nameContext); for (Ptr functorData : propertyGroup->GetFunctors()) { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index dde81e77b5..376aba2208 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -80,7 +81,7 @@ namespace AZ m_materialAssignmentId); } - if (!materialAssetId.IsValid()) + if (!materialAssetId.IsValid()) { UnloadMaterial(); return false; @@ -104,8 +105,9 @@ namespace AZ // Get a list of all the editor functors to be used for property editor states auto propertyLayout = m_editData.m_materialAsset->GetMaterialPropertiesLayout(); + AZ::RPI::MaterialNameContext materialNameContext; // There is no name context for top-level functors, only functors inside PropertyGroups const AZ::RPI::MaterialFunctorSourceData::EditorContext editorContext = - AZ::RPI::MaterialFunctorSourceData::EditorContext(m_editData.m_materialTypeSourcePath, propertyLayout); + AZ::RPI::MaterialFunctorSourceData::EditorContext(m_editData.m_materialTypeSourcePath, propertyLayout, &materialNameContext); for (AZ::RPI::Ptr functorData : m_editData.m_materialTypeSourceData.m_materialFunctorSourceData) { AZ::RPI::MaterialFunctorSourceData::FunctorResult createResult = functorData->CreateFunctor(editorContext); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp index dde9644c50..320d5e2e08 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -113,9 +114,11 @@ namespace AZ // Copy all of the properties from the material asset to the source data that will be exported bool result = true; - editData.m_materialTypeSourceData.EnumerateProperties([&](const AZStd::string& propertyIdContext, const AZ::RPI::MaterialTypeSourceData::PropertyDefinition* propertyDefinition) + editData.m_materialTypeSourceData.EnumerateProperties([&](const AZ::RPI::MaterialNameContext& materialNameContext, const AZ::RPI::MaterialTypeSourceData::PropertyDefinition* propertyDefinition) { - AZ::Name propertyId(propertyIdContext + propertyDefinition->GetName()); + AZ::Name propertyId{propertyDefinition->GetName()}; + materialNameContext.ContextualizeProperty(propertyId); + const AZ::RPI::MaterialPropertyIndex propertyIndex = editData.m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyId); From a7bdb05d661e9f3dca0b353926c0737d144980bc Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Tue, 1 Feb 2022 22:37:47 -0800 Subject: [PATCH 005/133] Tied up some loose ends with nested property group support. Fixed the MaterialBuilder to report source dependencies on imported JSON files, so the material type will rebuild when you edit an imported file that contains shared property data. Fixed a spot in LuaMaterialFunctorSourceData where it was only applying the old "prefix" feature and not the new name context. Updated a couple built-in material functors to take advantage of the name context (they were using RuntimeContext::GetShaderResourceGroupLayout instead of the RuntimeContext::FindShaderInputConstantIndex wrapper utility function). Fixed an issue with EnumeratePropertyGroups where it wasn't passing the right name context, so Material Editor wasn't able to load some material types. Reordered the parameters in the MaterialTypeSourceData enumerate callback functions, I felt this order was more natural. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- ...surfaceTransmissionParameterFunctorSourceData.cpp | 6 +++--- .../Source/Material/Transform2DFunctorSourceData.cpp | 4 ++-- .../Atom/RPI.Edit/Material/MaterialTypeSourceData.h | 8 ++++---- .../Include/Atom/RPI.Edit/Material/MaterialUtils.h | 5 ++++- .../Source/RPI.Builders/Material/MaterialBuilder.cpp | 10 +++++++++- .../Material/LuaMaterialFunctorSourceData.cpp | 5 ++++- .../RPI.Edit/Material/MaterialTypeSourceData.cpp | 10 +++++----- .../Code/Source/RPI.Edit/Material/MaterialUtils.cpp | 6 +++++- .../Tests/Material/MaterialTypeSourceDataTests.cpp | 12 ++++++------ .../Code/Source/Document/MaterialDocument.cpp | 12 +++++------- .../Source/Material/EditorMaterialComponentUtil.cpp | 4 ++-- 11 files changed, 49 insertions(+), 33 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/SubsurfaceTransmissionParameterFunctorSourceData.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/SubsurfaceTransmissionParameterFunctorSourceData.cpp index a8ba40fb7f..ea447a422b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/SubsurfaceTransmissionParameterFunctorSourceData.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/SubsurfaceTransmissionParameterFunctorSourceData.cpp @@ -72,9 +72,9 @@ namespace AZ AddMaterialPropertyDependency(functor, functor->m_scatterDistanceColor); AddMaterialPropertyDependency(functor, functor->m_scatterDistanceIntensity); - functor->m_scatterDistance = context.GetShaderResourceGroupLayout()->FindShaderInputConstantIndex(Name{ m_scatterDistance }); - functor->m_transmissionParams = context.GetShaderResourceGroupLayout()->FindShaderInputConstantIndex(Name{ m_transmissionParams }); - functor->m_transmissionTintThickness = context.GetShaderResourceGroupLayout()->FindShaderInputConstantIndex(Name{ m_transmissionTintThickness }); + functor->m_scatterDistance = context.FindShaderInputConstantIndex(Name{ m_scatterDistance }); + functor->m_transmissionParams = context.FindShaderInputConstantIndex(Name{ m_transmissionParams }); + functor->m_transmissionTintThickness = context.FindShaderInputConstantIndex(Name{ m_transmissionTintThickness }); if (functor->m_scatterDistance.IsNull()) { diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/Transform2DFunctorSourceData.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/Transform2DFunctorSourceData.cpp index 26e7983a4b..dd7b9b891a 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/Transform2DFunctorSourceData.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/Transform2DFunctorSourceData.cpp @@ -62,7 +62,7 @@ namespace AZ AddMaterialPropertyDependency(functor, functor->m_translateY); AddMaterialPropertyDependency(functor, functor->m_rotateDegrees); - functor->m_transformMatrix = context.GetShaderResourceGroupLayout()->FindShaderInputConstantIndex(Name{m_transformMatrix}); + functor->m_transformMatrix = context.FindShaderInputConstantIndex(Name{m_transformMatrix}); if (functor->m_transformMatrix.IsNull()) { @@ -74,7 +74,7 @@ namespace AZ // In that case, the.materialtype file will not provide the name of an inverse matrix because it doesn't have one. if (!m_transformMatrixInverse.empty()) { - functor->m_transformMatrixInverse = context.GetShaderResourceGroupLayout()->FindShaderInputConstantIndex(Name{m_transformMatrixInverse}); + functor->m_transformMatrixInverse = context.FindShaderInputConstantIndex(Name{m_transformMatrixInverse}); if (functor->m_transformMatrixInverse.IsNull()) { diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h index 70d92ffccf..9aa31af97a 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h @@ -284,8 +284,8 @@ namespace AZ //! Call back function type used with the enumeration functions. //! Return false to terminate the traversal. using EnumeratePropertyGroupsCallback = AZStd::function; //! Recursively traverses all of the property groups contained in the material type, executing a callback function for each. @@ -295,8 +295,8 @@ namespace AZ //! Call back function type used with the numeration functions. //! Return false to terminate the traversal. using EnumeratePropertiesCallback = AZStd::function; //! Recursively traverses all of the properties contained in the material type, executing a callback function for each. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h index 6ab7132109..4d1c61146d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialUtils.h @@ -28,6 +28,8 @@ namespace AZ namespace MaterialUtils { + using ImportedJsonFiles = AZStd::unordered_set; + enum class GetImageAssetResult { Empty, //! No image was actually requested, the path was empty @@ -52,7 +54,8 @@ namespace AZ //! Otherwise, it will use the passed in document first if not null, or load the json document from the path. //! @param filePath path to the JSON file to load, unless the @document is already provided. In either case, this path will be used to resolve any relative file references. //! @param document an optional already loaded json document. - AZ::Outcome LoadMaterialTypeSourceData(const AZStd::string& filePath, rapidjson::Document* document = nullptr); + //! @param importedFiles receives the list of files that were imported by the JSON serializer + AZ::Outcome LoadMaterialTypeSourceData(const AZStd::string& filePath, rapidjson::Document* document = nullptr, ImportedJsonFiles* importedFiles = nullptr); //! Utility function for custom JSON serializers to report results as "Skipped" when encountering keys that aren't recognized //! as part of the custom format. diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp index bf65a09cef..5858c3e675 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp @@ -187,13 +187,21 @@ namespace AZ const bool isMaterialTypeFile = AzFramework::StringFunc::Path::IsExtension(request.m_sourceFile.c_str(), MaterialTypeSourceData::Extension); if (isMaterialTypeFile) { - auto materialTypeSourceData = MaterialUtils::LoadMaterialTypeSourceData(fullSourcePath, &document); + MaterialUtils::ImportedJsonFiles importedJsonFiles; + auto materialTypeSourceData = MaterialUtils::LoadMaterialTypeSourceData(fullSourcePath, &document, &importedJsonFiles); if (!materialTypeSourceData.IsSuccess()) { return; } + for (auto& importedJsonFile : importedJsonFiles) + { + AssetBuilderSDK::SourceFileDependency sourceDependency; + sourceDependency.m_sourceFileDependencyPath = importedJsonFile; + response.m_sourceFileDependencyList.push_back(sourceDependency); + } + for (auto& shader : materialTypeSourceData.GetValue().m_shaderCollection) { AddPossibleDependencies(request.m_sourceFile, diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp index c614222ee6..2477360b8c 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp @@ -198,7 +198,10 @@ namespace AZ for (const Name& materialProperty : materialPropertyDependencies.GetValue()) { - MaterialPropertyIndex index = propertiesLayout->FindPropertyIndex(Name{m_propertyNamePrefix + materialProperty.GetCStr()}); + Name propertyName{materialProperty.GetCStr()}; + functor->m_materialNameContext.ContextualizeProperty(propertyName); + + MaterialPropertyIndex index = propertiesLayout->FindPropertyIndex(propertyName); if (!index.IsValid()) { AZ_Error("LuaMaterialFunctorSourceData", false, "Property '%s' is not found in material type.", materialProperty.GetCStr()); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp index 9b251213fe..725041eab4 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp @@ -381,13 +381,13 @@ namespace AZ { for (auto& propertyGroup : inPropertyGroupList) { - if (!callback(materialNameContext, propertyGroup.get())) + MaterialNameContext materialNameContext2 = ExtendNameContext(materialNameContext, *propertyGroup); + + if (!callback(propertyGroup.get(), materialNameContext2)) { return false; // Stop processing } - MaterialNameContext materialNameContext2 = ExtendNameContext(materialNameContext, *propertyGroup); - if (!EnumeratePropertyGroups(callback, materialNameContext2, propertyGroup->m_propertyGroups)) { return false; // Stop processing @@ -415,7 +415,7 @@ namespace AZ for (auto& property : propertyGroup->m_properties) { - if (!callback(materialNameContext2, property.get())) + if (!callback(property.get(), materialNameContext2)) { return false; // Stop processing } @@ -483,7 +483,7 @@ namespace AZ enumValues.push_back(uvNamePair.second); } - EnumerateProperties([&enumValues](const MaterialNameContext&, const MaterialTypeSourceData::PropertyDefinition* property) + EnumerateProperties([&enumValues](const MaterialTypeSourceData::PropertyDefinition* property, const MaterialNameContext&) { if (property->m_dataType == AZ::RPI::MaterialPropertyDataType::Enum && property->m_enumIsUv) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp index be5feccb80..926d9abb74 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp @@ -74,7 +74,7 @@ namespace AZ return true; } - AZ::Outcome LoadMaterialTypeSourceData(const AZStd::string& filePath, rapidjson::Document* document) + AZ::Outcome LoadMaterialTypeSourceData(const AZStd::string& filePath, rapidjson::Document* document, ImportedJsonFiles* importedFiles) { rapidjson::Document localDocument; @@ -96,6 +96,10 @@ namespace AZ importSettings.m_importer = &jsonImporter; importSettings.m_loadedJsonPath = filePath; AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ResolveImports(document->GetObject(), document->GetAllocator(), importSettings); + if (importedFiles) + { + *importedFiles = importSettings.m_importer->GetImportedFiles(); + } MaterialTypeSourceData materialType; diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp index 98a86fe9ce..04b55b3aaf 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp @@ -486,8 +486,8 @@ namespace UnitTest struct EnumeratePropertyGroupsResult { - MaterialNameContext m_materialNameContext; const MaterialTypeSourceData::PropertyGroup* m_propertyGroup; + MaterialNameContext m_materialNameContext; void Check(AZStd::string expectedIdContext, const MaterialTypeSourceData::PropertyGroup* expectedPropertyGroup) { @@ -502,9 +502,9 @@ namespace UnitTest }; AZStd::vector enumeratePropertyGroupsResults; - sourceData.EnumeratePropertyGroups([&enumeratePropertyGroupsResults](const MaterialNameContext& materialNameContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) + sourceData.EnumeratePropertyGroups([&enumeratePropertyGroupsResults](const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& nameContext) { - enumeratePropertyGroupsResults.push_back(EnumeratePropertyGroupsResult{materialNameContext, propertyGroup}); + enumeratePropertyGroupsResults.push_back(EnumeratePropertyGroupsResult{propertyGroup, nameContext}); return true; }); @@ -525,8 +525,8 @@ namespace UnitTest struct EnumeratePropertiesResult { - MaterialNameContext m_materialNameContext; const MaterialTypeSourceData::PropertyDefinition* m_propertyDefinition; + MaterialNameContext m_materialNameContext; void Check(AZStd::string expectedIdContext, const MaterialTypeSourceData::PropertyDefinition* expectedPropertyDefinition) { @@ -541,9 +541,9 @@ namespace UnitTest }; AZStd::vector enumeratePropertiesResults; - sourceData.EnumerateProperties([&enumeratePropertiesResults](const MaterialNameContext& materialNameContext, const MaterialTypeSourceData::PropertyDefinition* propertyDefinition) + sourceData.EnumerateProperties([&enumeratePropertiesResults](const MaterialTypeSourceData::PropertyDefinition* propertyDefinition, const MaterialNameContext& nameContext) { - enumeratePropertiesResults.push_back(EnumeratePropertiesResult{materialNameContext, propertyDefinition}); + enumeratePropertiesResults.push_back(EnumeratePropertiesResult{propertyDefinition, nameContext}); return true; }); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index aaad77266c..9349ad4dc9 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -586,10 +586,10 @@ namespace MaterialEditor bool result = true; // populate sourceData with properties that meet the filter - m_materialTypeSourceData.EnumerateProperties([&](const MaterialNameContext& materialNameContext, const auto& propertyDefinition) { + m_materialTypeSourceData.EnumerateProperties([&](const auto& propertyDefinition, const MaterialNameContext& nameContext) { Name propertyId{propertyDefinition->GetName()}; - materialNameContext.ContextualizeProperty(propertyId); + nameContext.ContextualizeProperty(propertyId); const auto it = m_properties.find(propertyId); if (it != m_properties.end() && propertyFilter(it->second)) @@ -783,17 +783,15 @@ namespace MaterialEditor // Populate the property map from a combination of source data and assets // Assets must still be used for now because they contain the final accumulated value after all other materials // in the hierarchy are applied - m_materialTypeSourceData.EnumeratePropertyGroups([this, &parentPropertyValues](const MaterialNameContext& materialNameContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) + m_materialTypeSourceData.EnumeratePropertyGroups([this, &parentPropertyValues](const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& nameContext) { AtomToolsFramework::DynamicPropertyConfig propertyConfig; for (const auto& propertyDefinition : propertyGroup->GetProperties()) { // Assign id before conversion so it can be used in dynamic description - MaterialNameContext groupNameContext = materialNameContext; - groupNameContext.ExtendPropertyIdContext(propertyGroup->GetName()); propertyConfig.m_id = propertyDefinition->GetName(); - groupNameContext.ContextualizeProperty(propertyConfig.m_id); + nameContext.ContextualizeProperty(propertyConfig.m_id); const auto& propertyIndex = m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); const bool propertyIndexInBounds = propertyIndex.IsValid() && propertyIndex.GetIndex() < m_materialAsset->GetPropertyValues().size(); @@ -907,7 +905,7 @@ namespace MaterialEditor // Add any material functors that are located inside each property group. bool enumerateResult = m_materialTypeSourceData.EnumeratePropertyGroups( - [this](const MaterialNameContext& nameContext, const MaterialTypeSourceData::PropertyGroup* propertyGroup) + [this](const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& nameContext) { const MaterialFunctorSourceData::EditorContext editorContext = MaterialFunctorSourceData::EditorContext( m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout(), &nameContext); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp index 320d5e2e08..fd66243cdc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp @@ -114,10 +114,10 @@ namespace AZ // Copy all of the properties from the material asset to the source data that will be exported bool result = true; - editData.m_materialTypeSourceData.EnumerateProperties([&](const AZ::RPI::MaterialNameContext& materialNameContext, const AZ::RPI::MaterialTypeSourceData::PropertyDefinition* propertyDefinition) + editData.m_materialTypeSourceData.EnumerateProperties([&](const AZ::RPI::MaterialTypeSourceData::PropertyDefinition* propertyDefinition, const AZ::RPI::MaterialNameContext& nameContext) { AZ::Name propertyId{propertyDefinition->GetName()}; - materialNameContext.ContextualizeProperty(propertyId); + nameContext.ContextualizeProperty(propertyId); const AZ::RPI::MaterialPropertyIndex propertyIndex = editData.m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyId); From 466e388f6000ca93a5911a976d2ebf58eecc3051 Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Thu, 3 Feb 2022 10:28:43 -0800 Subject: [PATCH 006/133] Fixed a unit test that broke in my last commit. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../RPI.Edit/Material/MaterialTypeSourceData.h | 9 +++++---- .../Material/MaterialTypeSourceData.cpp | 18 +++++++++--------- .../Material/MaterialTypeSourceDataTests.cpp | 14 ++++++++++---- .../Code/Source/Document/MaterialDocument.cpp | 9 +++++---- 4 files changed, 29 insertions(+), 21 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h index 9aa31af97a..ef14555061 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h @@ -285,7 +285,8 @@ namespace AZ //! Return false to terminate the traversal. using EnumeratePropertyGroupsCallback = AZStd::function; //! Recursively traverses all of the property groups contained in the material type, executing a callback function for each. @@ -296,7 +297,7 @@ namespace AZ //! Return false to terminate the traversal. using EnumeratePropertiesCallback = AZStd::function; //! Recursively traverses all of the properties contained in the material type, executing a callback function for each. @@ -318,8 +319,8 @@ namespace AZ PropertyDefinition* FindProperty(AZStd::span parsedPropertyId, AZStd::span> inPropertyGroupList); // Function overloads for recursion, returns false to indicate that recursion should end. - bool EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, MaterialNameContext materialNameContext, const AZStd::vector>& inPropertyGroupList) const; - bool EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext materialNameContext, const AZStd::vector>& inPropertyGroupList) const; + bool EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const; + bool EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const; static MaterialNameContext ExtendNameContext(MaterialNameContext nameContext, const MaterialTypeSourceData::PropertyGroup& propertyGroup); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp index 725041eab4..874039d605 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp @@ -377,18 +377,18 @@ namespace AZ return parts; } - bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, MaterialNameContext materialNameContext, const AZStd::vector>& inPropertyGroupList) const + bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const { for (auto& propertyGroup : inPropertyGroupList) { - MaterialNameContext materialNameContext2 = ExtendNameContext(materialNameContext, *propertyGroup); + MaterialNameContext groupNameContext = ExtendNameContext(nameContext, *propertyGroup); - if (!callback(propertyGroup.get(), materialNameContext2)) + if (!callback(propertyGroup.get(), groupNameContext, nameContext)) { - return false; // Stop processing + return false; // Stop processing } - if (!EnumeratePropertyGroups(callback, materialNameContext2, propertyGroup->m_propertyGroups)) + if (!EnumeratePropertyGroups(callback, groupNameContext, propertyGroup->m_propertyGroups)) { return false; // Stop processing } @@ -407,21 +407,21 @@ namespace AZ return EnumeratePropertyGroups(callback, {}, m_propertyLayout.m_propertyGroups); } - bool MaterialTypeSourceData::EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext materialNameContext, const AZStd::vector>& inPropertyGroupList) const + bool MaterialTypeSourceData::EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const { for (auto& propertyGroup : inPropertyGroupList) { - MaterialNameContext materialNameContext2 = ExtendNameContext(materialNameContext, *propertyGroup); + MaterialNameContext groupNameContext = ExtendNameContext(nameContext, *propertyGroup); for (auto& property : propertyGroup->m_properties) { - if (!callback(property.get(), materialNameContext2)) + if (!callback(property.get(), groupNameContext)) { return false; // Stop processing } } - if (!EnumerateProperties(callback, materialNameContext2, propertyGroup->m_propertyGroups)) + if (!EnumerateProperties(callback, groupNameContext, propertyGroup->m_propertyGroups)) { return false; // Stop processing } diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp index 04b55b3aaf..46cbb1ac46 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp @@ -487,24 +487,30 @@ namespace UnitTest struct EnumeratePropertyGroupsResult { const MaterialTypeSourceData::PropertyGroup* m_propertyGroup; - MaterialNameContext m_materialNameContext; + MaterialNameContext m_groupNameContext; + MaterialNameContext m_parentNameContext; void Check(AZStd::string expectedIdContext, const MaterialTypeSourceData::PropertyGroup* expectedPropertyGroup) { Name groupFullId{m_propertyGroup->GetName()}; - m_materialNameContext.ContextualizeProperty(groupFullId); + m_parentNameContext.ContextualizeProperty(groupFullId); AZStd::string expectedPropertyId = expectedIdContext + expectedPropertyGroup->GetName(); EXPECT_EQ(expectedPropertyId, groupFullId.GetStringView()); EXPECT_EQ(expectedPropertyGroup, m_propertyGroup); + + Name imaginaryPropertyName{"someChildProperty"}; + m_groupNameContext.ContextualizeProperty(imaginaryPropertyName); + EXPECT_EQ(AZStd::string(groupFullId.GetStringView()) + ".someChildProperty", imaginaryPropertyName.GetStringView()); } }; AZStd::vector enumeratePropertyGroupsResults; - sourceData.EnumeratePropertyGroups([&enumeratePropertyGroupsResults](const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& nameContext) + sourceData.EnumeratePropertyGroups([&enumeratePropertyGroupsResults]( + const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& groupNameContext, const MaterialNameContext& parentNameContext) { - enumeratePropertyGroupsResults.push_back(EnumeratePropertyGroupsResult{propertyGroup, nameContext}); + enumeratePropertyGroupsResults.push_back(EnumeratePropertyGroupsResult{propertyGroup, groupNameContext, parentNameContext}); return true; }); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index 9349ad4dc9..e4a99b73ed 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -783,7 +783,8 @@ namespace MaterialEditor // Populate the property map from a combination of source data and assets // Assets must still be used for now because they contain the final accumulated value after all other materials // in the hierarchy are applied - m_materialTypeSourceData.EnumeratePropertyGroups([this, &parentPropertyValues](const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& nameContext) + m_materialTypeSourceData.EnumeratePropertyGroups([this, &parentPropertyValues]( + const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& groupNameContext, const MaterialNameContext& /*parentNameContext*/) { AtomToolsFramework::DynamicPropertyConfig propertyConfig; @@ -791,7 +792,7 @@ namespace MaterialEditor { // Assign id before conversion so it can be used in dynamic description propertyConfig.m_id = propertyDefinition->GetName(); - nameContext.ContextualizeProperty(propertyConfig.m_id); + groupNameContext.ContextualizeProperty(propertyConfig.m_id); const auto& propertyIndex = m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); const bool propertyIndexInBounds = propertyIndex.IsValid() && propertyIndex.GetIndex() < m_materialAsset->GetPropertyValues().size(); @@ -905,10 +906,10 @@ namespace MaterialEditor // Add any material functors that are located inside each property group. bool enumerateResult = m_materialTypeSourceData.EnumeratePropertyGroups( - [this](const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& nameContext) + [this](const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& groupNameContext, const MaterialNameContext& /*parentNameContext*/) { const MaterialFunctorSourceData::EditorContext editorContext = MaterialFunctorSourceData::EditorContext( - m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout(), &nameContext); + m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout(), &groupNameContext); for (Ptr functorData : propertyGroup->GetFunctors()) { From 6322dd5397d2a91c86bed2f2b8b1c378da549c03 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 3 Feb 2022 12:29:18 -0600 Subject: [PATCH 007/133] Updated the image gradient component to use a streaming image asset Signed-off-by: Chris Galvan --- .../BuilderSettings/ImageProcessingDefines.h | 14 --- .../Code/Source/ImageBuilderComponent.cpp | 5 +- .../Source/ImageProcessingSystemComponent.cpp | 5 +- .../Include/Atom/RPI.Reflect/Image/Image.h | 14 +++ .../RPI/Code/Source/RPI.Public/RPIUtils.cpp | 12 +-- Gems/GradientSignal/Code/CMakeLists.txt | 3 + .../Components/ImageGradientComponent.h | 18 +++- .../Code/Include/GradientSignal/ImageAsset.h | 3 +- .../Components/ImageGradientComponent.cpp | 92 ++++++++++++++++++- .../GradientSignal/Code/Source/ImageAsset.cpp | 27 +++--- 10 files changed, 150 insertions(+), 43 deletions(-) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h index 7c35a0634e..dcd95c7fb6 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h @@ -49,20 +49,6 @@ namespace ImageProcessingAtom static const unsigned int s_MinReduceLevel = 0; static const unsigned int s_MaxReduceLevel = 5; - static const int s_TotalSupportedImageExtensions = 10; - static const char* s_SupportedImageExtensions[s_TotalSupportedImageExtensions] = { - "*.tif", - "*.tiff", - "*.png", - "*.bmp", - "*.jpg", - "*.jpeg", - "*.tga", - "*.gif", - "*.dds", - "*.exr" - }; - enum class RGBWeight : AZ::u32 { uniform, // uniform weights (1.0, 1.0, 1.0) (default) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp index 55a6c1ea8f..8c2e61ff6d 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp @@ -27,6 +27,7 @@ #include #include +#include #include namespace ImageProcessingAtom @@ -66,9 +67,9 @@ namespace ImageProcessingAtom AssetBuilderSDK::AssetBuilderDesc builderDescriptor; builderDescriptor.m_name = "Atom Image Builder"; - for (int i = 0; i < s_TotalSupportedImageExtensions; i++) + for (int i = 0; i < AZ::RPI::s_TotalSupportedImageExtensions; i++) { - builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern(s_SupportedImageExtensions[i], AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); + builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern(AZ::RPI::s_SupportedImageExtensions[i], AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); } builderDescriptor.m_busId = azrtti_typeid(); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessingSystemComponent.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessingSystemComponent.cpp index 665d08b3ae..f0d881c416 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessingSystemComponent.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessingSystemComponent.cpp @@ -7,6 +7,7 @@ */ +#include #include #include @@ -223,9 +224,9 @@ namespace ImageProcessingAtom { AZStd::string targetExtension = entry->GetExtension(); - for (int i = 0; i < s_TotalSupportedImageExtensions; i++) + for (int i = 0; i < AZ::RPI::s_TotalSupportedImageExtensions; i++) { - if (AZStd::wildcard_match(s_SupportedImageExtensions[i], targetExtension.c_str())) + if (AZStd::wildcard_match(AZ::RPI::s_SupportedImageExtensions[i], targetExtension.c_str())) { return true; } diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Image/Image.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Image/Image.h index 185666626c..66c91e92cf 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Image/Image.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Image/Image.h @@ -22,6 +22,20 @@ namespace AZ { class ImageAsset; + static const int s_TotalSupportedImageExtensions = 10; + static const char* s_SupportedImageExtensions[s_TotalSupportedImageExtensions] = { + "*.tif", + "*.tiff", + "*.png", + "*.bmp", + "*.jpg", + "*.jpeg", + "*.tga", + "*.gif", + "*.dds", + "*.exr" + }; + //! A base class for images providing access to common image information. class Image : public Data::InstanceData diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp index e13db253f3..9ff26f0d3a 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp @@ -133,7 +133,8 @@ namespace AZ case AZ::RHI::Format::R16G16_UNORM: case AZ::RHI::Format::R16G16B16A16_UNORM: { - return mem[index] / static_cast(std::numeric_limits::max()); + auto actualMem = reinterpret_cast(mem); + return actualMem[index] / static_cast(std::numeric_limits::max()); } case AZ::RHI::Format::R16_SNORM: case AZ::RHI::Format::R16G16_SNORM: @@ -480,14 +481,13 @@ namespace AZ const AZ::RHI::ImageDescriptor imageDescriptor = imageAsset->GetImageDescriptor(); auto width = imageDescriptor.m_size.m_width; const uint32_t numComponents = AZ::RHI::GetFormatComponentCount(imageDescriptor.m_format); - const uint32_t pixelSize = AZ::RHI::GetFormatSize(imageDescriptor.m_format) / numComponents; size_t outValuesIndex = 0; for (uint32_t y = topLeft.second; y < bottomRight.second; ++y) { for (uint32_t x = topLeft.first; x < bottomRight.first; ++x) { - size_t imageDataIndex = (y * width + x) * pixelSize + componentIndex; + size_t imageDataIndex = (y * width + x) * numComponents + componentIndex; auto& outValue = outValues[outValuesIndex++]; outValue = Internal::RetrieveFloatValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); @@ -513,14 +513,13 @@ namespace AZ const AZ::RHI::ImageDescriptor imageDescriptor = imageAsset->GetImageDescriptor(); auto width = imageDescriptor.m_size.m_width; const uint32_t numComponents = AZ::RHI::GetFormatComponentCount(imageDescriptor.m_format); - const uint32_t pixelSize = AZ::RHI::GetFormatSize(imageDescriptor.m_format) / numComponents; size_t outValuesIndex = 0; for (uint32_t y = topLeft.second; y < bottomRight.second; ++y) { for (uint32_t x = topLeft.first; x < bottomRight.first; ++x) { - size_t imageDataIndex = (y * width + x) * pixelSize + componentIndex; + size_t imageDataIndex = (y * width + x) * numComponents + componentIndex; auto& outValue = outValues[outValuesIndex++]; outValue = Internal::RetrieveUintValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); @@ -546,14 +545,13 @@ namespace AZ const AZ::RHI::ImageDescriptor imageDescriptor = imageAsset->GetImageDescriptor(); auto width = imageDescriptor.m_size.m_width; const uint32_t numComponents = AZ::RHI::GetFormatComponentCount(imageDescriptor.m_format); - const uint32_t pixelSize = AZ::RHI::GetFormatSize(imageDescriptor.m_format) / numComponents; size_t outValuesIndex = 0; for (uint32_t y = topLeft.second; y < bottomRight.second; ++y) { for (uint32_t x = topLeft.first; x < bottomRight.first; ++x) { - size_t imageDataIndex = (y * width + x) * pixelSize + componentIndex; + size_t imageDataIndex = (y * width + x) * numComponents + componentIndex; auto& outValue = outValues[outValuesIndex++]; outValue = Internal::RetrieveIntValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); diff --git a/Gems/GradientSignal/Code/CMakeLists.txt b/Gems/GradientSignal/Code/CMakeLists.txt index d2d8f8c696..febf7d9cd4 100644 --- a/Gems/GradientSignal/Code/CMakeLists.txt +++ b/Gems/GradientSignal/Code/CMakeLists.txt @@ -17,9 +17,12 @@ ly_add_target( PUBLIC Include BUILD_DEPENDENCIES + PRIVATE + AZ::AtomCore PUBLIC AZ::AzCore AZ::AzFramework + Gem::Atom_RPI.Public Gem::SurfaceData Gem::ImageProcessingAtom.Headers Gem::LmbrCentral diff --git a/Gems/GradientSignal/Code/Include/GradientSignal/Components/ImageGradientComponent.h b/Gems/GradientSignal/Code/Include/GradientSignal/Components/ImageGradientComponent.h index 044e9d91b1..0cbd8bd4c7 100644 --- a/Gems/GradientSignal/Code/Include/GradientSignal/Components/ImageGradientComponent.h +++ b/Gems/GradientSignal/Code/Include/GradientSignal/Components/ImageGradientComponent.h @@ -8,8 +8,11 @@ #pragma once +#include #include #include +#include +#include #include #include #include @@ -25,6 +28,19 @@ namespace LmbrCentral namespace GradientSignal { + // Custom JSON serializer for ImageGradientConfig to handle version conversion + class JsonImageGradientConfigSerializer + : public AZ::BaseJsonSerializer + { + public: + AZ_RTTI(GradientSignal::JsonImageGradientConfigSerializer, "{C5B982C8-2E81-45C3-8932-B6F54B28F493}", AZ::BaseJsonSerializer); + AZ_CLASS_ALLOCATOR_DECL; + + AZ::JsonSerializationResult::Result Load( + void* outputValue, const AZ::Uuid& outputValueTypeId, const rapidjson::Value& inputValue, + AZ::JsonDeserializerContext& context) override; + }; + class ImageGradientConfig : public AZ::ComponentConfig { @@ -32,7 +48,7 @@ namespace GradientSignal AZ_CLASS_ALLOCATOR(ImageGradientConfig, AZ::SystemAllocator, 0); AZ_RTTI(ImageGradientConfig, "{1BDB5DA4-A4A8-452B-BE6D-6BD451D4E7CD}", AZ::ComponentConfig); static void Reflect(AZ::ReflectContext* context); - AZ::Data::Asset m_imageAsset = { AZ::Data::AssetLoadBehavior::QueueLoad }; + AZ::Data::Asset m_imageAsset = { AZ::Data::AssetLoadBehavior::QueueLoad }; float m_tilingX = 1.0f; float m_tilingY = 1.0f; }; diff --git a/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h b/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h index 4ffab0b4b4..811d74082d 100644 --- a/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h +++ b/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h @@ -12,6 +12,7 @@ #include #include #include +#include namespace AZ { @@ -61,6 +62,6 @@ namespace GradientSignal } }; - float GetValueFromImageAsset(const AZ::Data::Asset& imageAsset, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue); + float GetValueFromImageAsset(const AZ::Data::Asset& imageAsset, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue); } // namespace GradientSignal diff --git a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp index 3639d5c6df..e3f128ec95 100644 --- a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp @@ -7,6 +7,7 @@ */ #include +#include #include #include #include @@ -18,13 +19,100 @@ namespace GradientSignal { + AZ::JsonSerializationResult::Result JsonImageGradientConfigSerializer::Load( + void* outputValue, [[maybe_unused]] const AZ::Uuid& outputValueTypeId, + const rapidjson::Value& inputValue, AZ::JsonDeserializerContext& context) + { + namespace JSR = AZ::JsonSerializationResult; + + auto configInstance = reinterpret_cast(outputValue); + AZ_Assert(configInstance, "Output value for JsonImageGradientConfigSerializer can't be null."); + + JSR::ResultCode result(JSR::Tasks::ReadField); + + rapidjson::Value::ConstMemberIterator itr = inputValue.FindMember("ImageAsset"); + if (itr != inputValue.MemberEnd()) + { + // Version 1 stored a custom GradientSignal::ImageAsset as the image asset. + // In Version 2, we changed the image asset to use the generic AZ::RPI::StreamingImageAsset, + // so they are both AZ::Data::Asset but reference different types. + // Using the assetHint, which will be something like "my_test_image.gradimage", + // we need to find the valid streaming image asset product from the same source, + // which will be something like "my_test_image.png.streamingimage" + AZStd::string assetHint; + AZ::Data::AssetId fixedAssetId; + auto it = itr->value.FindMember("assetHint"); + if (it != itr->value.MemberEnd()) + { + AZ::ScopedContextPath subPath(context, "assetHint"); + result.Combine(ContinueLoading(&assetHint, azrtti_typeid(), it->value, context)); + + if (assetHint.ends_with(".gradimage")) + { + // We don't know what image format the original source was, so we need to loop through + // all the supported image extensions to check if they have a valid corresponding + // streaming image asset + for (int i = 0; i < AZ::RPI::s_TotalSupportedImageExtensions; i++) + { + AZStd::string imageExtension(AZ::RPI::s_SupportedImageExtensions[i]); + + // The image extensions are stored with a wildcard (e.g. *.png) so we need to strip that off first + AZ::StringFunc::Replace(imageExtension, "*", ""); + + // Form potential streaming image path (e.g. my_test_image.png.streamingimage) + AZStd::string potentialStreamingImagePath(assetHint); + AZ::StringFunc::Replace(potentialStreamingImagePath, ".gradimage", ""); + potentialStreamingImagePath += imageExtension + ".streamingimage"; + + // Check if there is a valid streaming image asset for this path + AZ::Data::AssetCatalogRequestBus::BroadcastResult(fixedAssetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, potentialStreamingImagePath.c_str(), azrtti_typeid>(), false); + if (fixedAssetId.IsValid()) + { + break; + } + } + } + } + + // Replace the old gradimage with new AssetId for streaming image asset (if we needed to replace) + if (fixedAssetId.IsValid()) + { + configInstance->m_imageAsset = AZ::Data::AssetManager::Instance().GetAsset(fixedAssetId, AZ::Data::AssetLoadBehavior::QueueLoad); + } + // Otherwise, this was already a streaming image asset, so just load it like normal + else + { + result.Combine(ContinueLoadingFromJsonObjectField( + &configInstance->m_imageAsset, azrtti_typeidm_imageAsset)>(), inputValue, "ImageAsset", context)); + } + } + + result.Combine(ContinueLoadingFromJsonObjectField( + &configInstance->m_tilingX, azrtti_typeidm_tilingX)>(), inputValue, "TilingX", context)); + + result.Combine(ContinueLoadingFromJsonObjectField( + &configInstance->m_tilingY, azrtti_typeidm_tilingY)>(), inputValue, "TilingY", context)); + + return context.Report(result, + result.GetProcessing() != JSR::Processing::Halted ? + "Successfully loaded ImageGradientConfig information." : + "Failed to load ImageGradientConfig information."); + } + + AZ_CLASS_ALLOCATOR_IMPL(JsonImageGradientConfigSerializer, AZ::SystemAllocator, 0); + void ImageGradientConfig::Reflect(AZ::ReflectContext* context) { + if (auto jsonContext = azrtti_cast(context)) + { + jsonContext->Serializer()->HandlesType(); + } + AZ::SerializeContext* serialize = azrtti_cast(context); if (serialize) { serialize->Class() - ->Version(1) + ->Version(2) ->Field("ImageAsset", &ImageGradientConfig::m_imageAsset) ->Field("TilingX", &ImageGradientConfig::m_tilingX) ->Field("TilingY", &ImageGradientConfig::m_tilingY) @@ -265,7 +353,7 @@ namespace GradientSignal { AZStd::unique_lock imageLock(m_imageMutex); - m_configuration.m_imageAsset = AZ::Data::AssetManager::Instance().FindOrCreateAsset(assetId, azrtti_typeid(), m_configuration.m_imageAsset.GetAutoLoadBehavior()); + m_configuration.m_imageAsset = AZ::Data::AssetManager::Instance().FindOrCreateAsset(assetId, azrtti_typeid(), m_configuration.m_imageAsset.GetAutoLoadBehavior()); } SetupDependencies(); diff --git a/Gems/GradientSignal/Code/Source/ImageAsset.cpp b/Gems/GradientSignal/Code/Source/ImageAsset.cpp index 7e5667a5be..6ccd9e0a2a 100644 --- a/Gems/GradientSignal/Code/Source/ImageAsset.cpp +++ b/Gems/GradientSignal/Code/Source/ImageAsset.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include @@ -152,17 +153,15 @@ namespace GradientSignal return true; } - float GetValueFromImageAsset(const AZ::Data::Asset& imageAsset, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue) + float GetValueFromImageAsset(const AZ::Data::Asset& imageAsset, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue) { if (imageAsset.IsReady()) { - const auto& image = imageAsset.Get(); - AZStd::size_t imageSize = image->m_imageWidth * image->m_imageHeight * - static_cast(image->m_bytesPerPixel); - - if (image->m_imageWidth > 0 && - image->m_imageHeight > 0 && - image->m_imageData.size() == imageSize) + auto imageDescriptor = imageAsset->GetImageDescriptor(); + auto width = imageDescriptor.m_size.m_width; + auto height = imageDescriptor.m_size.m_height; + + if (width > 0 && height > 0) { // When "rasterizing" from uvs, a range of 0-1 has slightly different meanings depending on the sampler state. // For repeating states (Unbounded/None, Repeat), a uv value of 1 should wrap around back to our 0th pixel. @@ -185,8 +184,8 @@ namespace GradientSignal // A 16x16 pixel image and tilingX = tilingY = 1 maps the uv range of 0-1 to 0-16 pixels. // A 16x16 pixel image and tilingX = tilingY = 1.5 maps the uv range of 0-1 to 0-24 pixels. - const AZ::Vector3 tiledDimensions((image->m_imageWidth * tilingX), - (image->m_imageHeight * tilingY), + const AZ::Vector3 tiledDimensions((width * tilingX), + (height * tilingY), 0.0f); // Convert from uv space back to pixel space @@ -195,13 +194,13 @@ namespace GradientSignal // UVs outside the 0-1 range are treated as infinitely tiling, so that we behave the same as the // other gradient generators. As mentioned above, if clamping is desired, we expect it to be applied // outside of this function. - size_t x = static_cast(pixelLookup.GetX()) % image->m_imageWidth; - size_t y = static_cast(pixelLookup.GetY()) % image->m_imageHeight; + auto x = aznumeric_cast(pixelLookup.GetX()) % width; + auto y = aznumeric_cast(pixelLookup.GetY()) % height; // Flip the y because images are stored in reverse of our world axes - size_t index = ((image->m_imageHeight - 1) - y) * image->m_imageWidth + x; + y = (height - 1) - y; - return RetrieveValue(image->m_imageData.data(), index, image->m_imageFormat); + return AZ::RPI::GetSubImagePixelValue(imageAsset, x, y); } } From 4e15cef2fca68d34b77256da8fc68d474ac97b03 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 3 Feb 2022 13:49:54 -0600 Subject: [PATCH 008/133] Removed unused methods to fix compile error on linux Signed-off-by: Chris Galvan --- .../GradientSignal/Code/Source/ImageAsset.cpp | 75 ------------------- 1 file changed, 75 deletions(-) diff --git a/Gems/GradientSignal/Code/Source/ImageAsset.cpp b/Gems/GradientSignal/Code/Source/ImageAsset.cpp index 6ccd9e0a2a..0f91a3ea08 100644 --- a/Gems/GradientSignal/Code/Source/ImageAsset.cpp +++ b/Gems/GradientSignal/Code/Source/ImageAsset.cpp @@ -19,81 +19,6 @@ #include #include -namespace -{ - template - float RetrieveValue(const AZ::u8* mem, size_t index) - { - AZ_Assert(false, "Unimplemented!"); - return 0.0f; - } - - template <> - float RetrieveValue([[maybe_unused]] const AZ::u8* mem, [[maybe_unused]] size_t index) - { - return 0.0f; - } - - template <> - float RetrieveValue(const AZ::u8* mem, size_t index) - { - return mem[index] / static_cast(std::numeric_limits::max()); - } - - template <> - float RetrieveValue(const AZ::u8* mem, size_t index) - { - // 16 bits per channel - auto actualMem = reinterpret_cast(mem); - actualMem += index; - - return *actualMem / static_cast(std::numeric_limits::max()); - } - - template <> - float RetrieveValue(const AZ::u8* mem, size_t index) - { - // 32 bits per channel - auto actualMem = reinterpret_cast(mem); - actualMem += index; - - return *actualMem / static_cast(std::numeric_limits::max()); - } - - template <> - float RetrieveValue(const AZ::u8* mem, size_t index) - { - // 32 bits per channel - auto actualMem = reinterpret_cast(mem); - actualMem += index; - - return *actualMem; - } - - float RetrieveValue(const AZ::u8* mem, size_t index, ImageProcessingAtom::EPixelFormat format) - { - using namespace ImageProcessingAtom; - - switch (format) - { - case ePixelFormat_R8: - return RetrieveValue(mem, index); - - case ePixelFormat_R16: - return RetrieveValue(mem, index); - - case ePixelFormat_R32: - return RetrieveValue(mem, index); - - case ePixelFormat_R32F: - return RetrieveValue(mem, index); - - default: - return RetrieveValue(mem, index); - } - } -} - namespace GradientSignal { void ImageAsset::Reflect(AZ::ReflectContext* context) From 22f018c310b67c4a8c7fc54cde1feb5149454672 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 3 Feb 2022 15:05:01 -0600 Subject: [PATCH 009/133] Moved the ImageProcessingDefines to the Include folder and added it to the header only target Signed-off-by: Chris Galvan --- .../Atom/ImageProcessing}/ImageProcessingDefines.h | 14 ++++++++++++++ .../Source/BuilderSettings/BuilderSettingManager.h | 2 +- .../Code/Source/BuilderSettings/CubemapSettings.h | 2 +- .../Code/Source/BuilderSettings/MipmapSettings.h | 2 +- .../Code/Source/BuilderSettings/PlatformSettings.h | 2 +- .../Code/Source/BuilderSettings/PresetSettings.h | 2 +- .../Code/Source/BuilderSettings/TextureSettings.h | 2 +- .../Code/Source/Compressors/Compressor.h | 2 +- .../Code/Source/ImageBuilderComponent.cpp | 5 ++--- .../Code/Source/ImageProcessingSystemComponent.cpp | 5 ++--- .../Code/Source/Processing/ImageConvert.h | 2 +- .../Code/Source/Processing/ImageConvertJob.h | 2 +- .../Code/Tests/ImageProcessing_Test.cpp | 2 +- .../Code/imageprocessing_files.cmake | 2 +- .../Code/imageprocessingatom_headers_files.cmake | 1 + .../Code/Include/Atom/RPI.Reflect/Image/Image.h | 14 -------------- .../Source/Components/ImageGradientComponent.cpp | 6 +++--- 17 files changed, 33 insertions(+), 34 deletions(-) rename Gems/Atom/Asset/ImageProcessingAtom/Code/{Source/BuilderSettings => Include/Atom/ImageProcessing}/ImageProcessingDefines.h (92%) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Include/Atom/ImageProcessing/ImageProcessingDefines.h similarity index 92% rename from Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h rename to Gems/Atom/Asset/ImageProcessingAtom/Code/Include/Atom/ImageProcessing/ImageProcessingDefines.h index dcd95c7fb6..38f6e4a488 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/ImageProcessingDefines.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Include/Atom/ImageProcessing/ImageProcessingDefines.h @@ -49,6 +49,20 @@ namespace ImageProcessingAtom static const unsigned int s_MinReduceLevel = 0; static const unsigned int s_MaxReduceLevel = 5; + static const char* s_SupportedImageExtensions[] = { + "*.tif", + "*.tiff", + "*.png", + "*.bmp", + "*.jpg", + "*.jpeg", + "*.tga", + "*.gif", + "*.dds", + "*.exr" + }; + static constexpr int s_TotalSupportedImageExtensions = AZ_ARRAY_SIZE(s_SupportedImageExtensions); + enum class RGBWeight : AZ::u32 { uniform, // uniform weights (1.0, 1.0, 1.0) (default) diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.h index 443b91bc07..65fc0aa2a7 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/BuilderSettingManager.h @@ -8,12 +8,12 @@ #pragma once -#include #include #include #include #include #include +#include #include #include diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/CubemapSettings.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/CubemapSettings.h index 77f804b646..fbfc95ac46 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/CubemapSettings.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/CubemapSettings.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/MipmapSettings.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/MipmapSettings.h index c9abc82b09..c5fa48e10f 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/MipmapSettings.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/MipmapSettings.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/PlatformSettings.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/PlatformSettings.h index 10f76db1dd..014b2c7cfb 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/PlatformSettings.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/PlatformSettings.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/PresetSettings.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/PresetSettings.h index 348fff989d..c0228cef79 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/PresetSettings.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/PresetSettings.h @@ -11,9 +11,9 @@ #include #include -#include #include #include +#include #include namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/TextureSettings.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/TextureSettings.h index 24a2f07bfb..1767b5d9e8 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/TextureSettings.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/BuilderSettings/TextureSettings.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include #include diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.h index 6920ae0cc1..ae4217764d 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Compressors/Compressor.h @@ -8,7 +8,7 @@ #pragma once -#include +#include #include #include diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp index 8c2e61ff6d..55a6c1ea8f 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageBuilderComponent.cpp @@ -27,7 +27,6 @@ #include #include -#include #include namespace ImageProcessingAtom @@ -67,9 +66,9 @@ namespace ImageProcessingAtom AssetBuilderSDK::AssetBuilderDesc builderDescriptor; builderDescriptor.m_name = "Atom Image Builder"; - for (int i = 0; i < AZ::RPI::s_TotalSupportedImageExtensions; i++) + for (int i = 0; i < s_TotalSupportedImageExtensions; i++) { - builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern(AZ::RPI::s_SupportedImageExtensions[i], AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); + builderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern(s_SupportedImageExtensions[i], AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); } builderDescriptor.m_busId = azrtti_typeid(); diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessingSystemComponent.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessingSystemComponent.cpp index f0d881c416..665d08b3ae 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessingSystemComponent.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/ImageProcessingSystemComponent.cpp @@ -7,7 +7,6 @@ */ -#include #include #include @@ -224,9 +223,9 @@ namespace ImageProcessingAtom { AZStd::string targetExtension = entry->GetExtension(); - for (int i = 0; i < AZ::RPI::s_TotalSupportedImageExtensions; i++) + for (int i = 0; i < s_TotalSupportedImageExtensions; i++) { - if (AZStd::wildcard_match(AZ::RPI::s_SupportedImageExtensions[i], targetExtension.c_str())) + if (AZStd::wildcard_match(s_SupportedImageExtensions[i], targetExtension.c_str())) { return true; } diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h index ba3d21191f..a59c3471b3 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvert.h @@ -10,10 +10,10 @@ #include -#include #include #include #include +#include #include #include diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.h b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.h index ac15d47806..2a5aef9902 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.h +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Processing/ImageConvertJob.h @@ -8,10 +8,10 @@ #pragma once -#include #include #include #include +#include #include namespace ImageProcessingAtom diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp index 91b0952a06..f73446653f 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Tests/ImageProcessing_Test.cpp @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -45,7 +46,6 @@ #include #include -#include #include #include diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake b/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake index a6fe09bfa6..3f7cb0a79d 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessing_files.cmake @@ -13,6 +13,7 @@ set(FILES Include/Atom/ImageProcessing/ImageProcessingEditorBus.h Include/Atom/ImageProcessing/PixelFormats.h Include/Atom/ImageProcessing/ImageObject.h + Include/Atom/ImageProcessing/ImageProcessingDefines.h ../Assets/Editor/Resources.qrc ../Assets/Editor/Backward.png ../Assets/Editor/Forward.png @@ -28,7 +29,6 @@ set(FILES Source/BuilderSettings/BuilderSettings.h Source/BuilderSettings/CubemapSettings.cpp Source/BuilderSettings/CubemapSettings.h - Source/BuilderSettings/ImageProcessingDefines.h Source/BuilderSettings/MipmapSettings.cpp Source/BuilderSettings/MipmapSettings.h Source/BuilderSettings/PlatformSettings.h diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessingatom_headers_files.cmake b/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessingatom_headers_files.cmake index c2c5a11c4c..51864a8442 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessingatom_headers_files.cmake +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/imageprocessingatom_headers_files.cmake @@ -7,4 +7,5 @@ # set(FILES + Include/Atom/ImageProcessing/ImageProcessingDefines.h ) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Image/Image.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Image/Image.h index 66c91e92cf..185666626c 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Image/Image.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Image/Image.h @@ -22,20 +22,6 @@ namespace AZ { class ImageAsset; - static const int s_TotalSupportedImageExtensions = 10; - static const char* s_SupportedImageExtensions[s_TotalSupportedImageExtensions] = { - "*.tif", - "*.tiff", - "*.png", - "*.bmp", - "*.jpg", - "*.jpeg", - "*.tga", - "*.gif", - "*.dds", - "*.exr" - }; - //! A base class for images providing access to common image information. class Image : public Data::InstanceData diff --git a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp index e3f128ec95..c06792c1f1 100644 --- a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp @@ -7,7 +7,7 @@ */ #include -#include +#include #include #include #include @@ -52,9 +52,9 @@ namespace GradientSignal // We don't know what image format the original source was, so we need to loop through // all the supported image extensions to check if they have a valid corresponding // streaming image asset - for (int i = 0; i < AZ::RPI::s_TotalSupportedImageExtensions; i++) + for (int i = 0; i < ImageProcessingAtom::s_TotalSupportedImageExtensions; i++) { - AZStd::string imageExtension(AZ::RPI::s_SupportedImageExtensions[i]); + AZStd::string imageExtension(ImageProcessingAtom::s_SupportedImageExtensions[i]); // The image extensions are stored with a wildcard (e.g. *.png) so we need to strip that off first AZ::StringFunc::Replace(imageExtension, "*", ""); From 2c54b48a9e726906aa6b39780a1ea68af1dcc2ac Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Thu, 3 Feb 2022 16:20:55 -0600 Subject: [PATCH 010/133] Modified image gradient config json serializer to be able to detect version difference earlier Signed-off-by: Chris Galvan --- .../Components/ImageGradientComponent.cpp | 116 +++++++++--------- 1 file changed, 58 insertions(+), 58 deletions(-) diff --git a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp index c06792c1f1..468b96e5ad 100644 --- a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp @@ -23,6 +23,16 @@ namespace GradientSignal void* outputValue, [[maybe_unused]] const AZ::Uuid& outputValueTypeId, const rapidjson::Value& inputValue, AZ::JsonDeserializerContext& context) { + // We can distinguish between version 1 and 2 by the presence of the "ImageAsset" field, + // which is only in version 1. + // For version 2, we don't need to do any special processing, so just let the base class + // load the JSON if we don't find the "ImageAsset" field. + rapidjson::Value::ConstMemberIterator itr = inputValue.FindMember("ImageAsset"); + if (itr == inputValue.MemberEnd()) + { + return AZ::BaseJsonSerializer::Load(outputValue, outputValueTypeId, inputValue, context); + } + namespace JSR = AZ::JsonSerializationResult; auto configInstance = reinterpret_cast(outputValue); @@ -30,69 +40,59 @@ namespace GradientSignal JSR::ResultCode result(JSR::Tasks::ReadField); - rapidjson::Value::ConstMemberIterator itr = inputValue.FindMember("ImageAsset"); - if (itr != inputValue.MemberEnd()) - { - // Version 1 stored a custom GradientSignal::ImageAsset as the image asset. - // In Version 2, we changed the image asset to use the generic AZ::RPI::StreamingImageAsset, - // so they are both AZ::Data::Asset but reference different types. - // Using the assetHint, which will be something like "my_test_image.gradimage", - // we need to find the valid streaming image asset product from the same source, - // which will be something like "my_test_image.png.streamingimage" - AZStd::string assetHint; - AZ::Data::AssetId fixedAssetId; - auto it = itr->value.FindMember("assetHint"); - if (it != itr->value.MemberEnd()) - { - AZ::ScopedContextPath subPath(context, "assetHint"); - result.Combine(ContinueLoading(&assetHint, azrtti_typeid(), it->value, context)); - - if (assetHint.ends_with(".gradimage")) - { - // We don't know what image format the original source was, so we need to loop through - // all the supported image extensions to check if they have a valid corresponding - // streaming image asset - for (int i = 0; i < ImageProcessingAtom::s_TotalSupportedImageExtensions; i++) - { - AZStd::string imageExtension(ImageProcessingAtom::s_SupportedImageExtensions[i]); - - // The image extensions are stored with a wildcard (e.g. *.png) so we need to strip that off first - AZ::StringFunc::Replace(imageExtension, "*", ""); - - // Form potential streaming image path (e.g. my_test_image.png.streamingimage) - AZStd::string potentialStreamingImagePath(assetHint); - AZ::StringFunc::Replace(potentialStreamingImagePath, ".gradimage", ""); - potentialStreamingImagePath += imageExtension + ".streamingimage"; - - // Check if there is a valid streaming image asset for this path - AZ::Data::AssetCatalogRequestBus::BroadcastResult(fixedAssetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, potentialStreamingImagePath.c_str(), azrtti_typeid>(), false); - if (fixedAssetId.IsValid()) - { - break; - } - } - } - } - - // Replace the old gradimage with new AssetId for streaming image asset (if we needed to replace) - if (fixedAssetId.IsValid()) - { - configInstance->m_imageAsset = AZ::Data::AssetManager::Instance().GetAsset(fixedAssetId, AZ::Data::AssetLoadBehavior::QueueLoad); - } - // Otherwise, this was already a streaming image asset, so just load it like normal - else - { - result.Combine(ContinueLoadingFromJsonObjectField( - &configInstance->m_imageAsset, azrtti_typeidm_imageAsset)>(), inputValue, "ImageAsset", context)); - } - } - result.Combine(ContinueLoadingFromJsonObjectField( &configInstance->m_tilingX, azrtti_typeidm_tilingX)>(), inputValue, "TilingX", context)); result.Combine(ContinueLoadingFromJsonObjectField( &configInstance->m_tilingY, azrtti_typeidm_tilingY)>(), inputValue, "TilingY", context)); + // Version 1 stored a custom GradientSignal::ImageAsset as the image asset. + // In Version 2, we changed the image asset to use the generic AZ::RPI::StreamingImageAsset, + // so they are both AZ::Data::Asset but reference different types. + // Using the assetHint, which will be something like "my_test_image.gradimage", + // we need to find the valid streaming image asset product from the same source, + // which will be something like "my_test_image.png.streamingimage" + AZStd::string assetHint; + AZ::Data::AssetId fixedAssetId; + auto it = itr->value.FindMember("assetHint"); + if (it != itr->value.MemberEnd()) + { + AZ::ScopedContextPath subPath(context, "assetHint"); + result.Combine(ContinueLoading(&assetHint, azrtti_typeid(), it->value, context)); + + if (assetHint.ends_with(".gradimage")) + { + // We don't know what image format the original source was, so we need to loop through + // all the supported image extensions to check if they have a valid corresponding + // streaming image asset + for (auto& supportedImageExtension : ImageProcessingAtom::s_SupportedImageExtensions) + { + AZStd::string imageExtension(supportedImageExtension); + + // The image extensions are stored with a wildcard (e.g. *.png) so we need to strip that off first + AZ::StringFunc::Replace(imageExtension, "*", ""); + + // Form potential streaming image path (e.g. my_test_image.png.streamingimage) + AZStd::string potentialStreamingImagePath(assetHint); + AZ::StringFunc::Replace(potentialStreamingImagePath, ".gradimage", ""); + potentialStreamingImagePath += imageExtension + ".streamingimage"; + + // Check if there is a valid streaming image asset for this path + AZ::Data::AssetCatalogRequestBus::BroadcastResult(fixedAssetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, potentialStreamingImagePath.c_str(), azrtti_typeid>(), false); + if (fixedAssetId.IsValid()) + { + break; + } + } + } + } + + // Replace the old gradimage with new AssetId for streaming image asset + if (fixedAssetId.IsValid()) + { + configInstance->m_imageAsset = AZ::Data::AssetManager::Instance().GetAsset(fixedAssetId, AZ::Data::AssetLoadBehavior::QueueLoad); + } + return context.Report(result, result.GetProcessing() != JSR::Processing::Halted ? "Successfully loaded ImageGradientConfig information." : @@ -113,9 +113,9 @@ namespace GradientSignal { serialize->Class() ->Version(2) - ->Field("ImageAsset", &ImageGradientConfig::m_imageAsset) ->Field("TilingX", &ImageGradientConfig::m_tilingX) ->Field("TilingY", &ImageGradientConfig::m_tilingY) + ->Field("StreamingImageAsset", &ImageGradientConfig::m_imageAsset) ; AZ::EditContext* edit = serialize->GetEditContext(); From 9aece3e84bcc5cc48c5af5177942b4f274c5d558 Mon Sep 17 00:00:00 2001 From: Sergey Pereslavtsev Date: Fri, 4 Feb 2022 19:57:29 +0000 Subject: [PATCH 011/133] LYN-8403 Prevent the same Surface Tag from getting reused Signed-off-by: Sergey Pereslavtsev --- .../PropertyEditorAPI_Internals.h | 10 +++++ .../PropertyEditorAPI_Internals_Impl.h | 45 ++++++++++++++----- .../PropertyEnumComboBoxCtrl.hxx | 6 +++ .../Code/Include/SurfaceData/SurfaceTag.h | 7 +-- .../TerrainPhysicsColliderComponent.cpp | 29 ++++++++++++ .../TerrainPhysicsColliderComponent.h | 5 +++ .../TerrainSurfaceGradientListComponent.cpp | 27 +++++++++++ .../TerrainSurfaceGradientListComponent.h | 8 ++++ .../EditorTerrainPhysicsColliderComponent.cpp | 34 ++++++++++++++ .../EditorTerrainPhysicsColliderComponent.h | 12 +++++ ...torTerrainSurfaceGradientListComponent.cpp | 33 ++++++++++++++ ...ditorTerrainSurfaceGradientListComponent.h | 12 +++++ .../EditorSelectableTagListProvider.cpp | 31 +++++++++++++ .../Source/EditorSelectableTagListProvider.h | 26 +++++++++++ .../Code/terrain_editor_shared_files.cmake | 2 + 15 files changed, 274 insertions(+), 13 deletions(-) create mode 100644 Gems/Terrain/Code/Source/EditorSelectableTagListProvider.cpp create mode 100644 Gems/Terrain/Code/Source/EditorSelectableTagListProvider.h diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals.h index ecd27baed4..f1ddc2268d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals.h @@ -154,6 +154,16 @@ namespace AzToolsFramework (void)debugName; } + // provides an option to specify reading parent element attributes. + // This allows parent elements to override attributes of their children if needed. + virtual void ConsumeParentAttribute(WidgetType* widget, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName) + { + (void)widget; + (void)attrib; + (void)attrValue; + (void)debugName; + } + // override GetFirstInTabOrder, GetLastInTabOrder in your base class to define which widget gets focus first when pressing tab, // and also what widget is last. // for example, if your widget is a compound widget and contains, say, 5 buttons diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals_Impl.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals_Impl.h index 2ebacfa558..ec428de951 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals_Impl.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI_Internals_Impl.h @@ -40,7 +40,14 @@ namespace AzToolsFramework } void* classInstance = parent->FirstInstance(); // pointer to the owner class so we can read member variables and functions - auto consumeAttributes = [&](const auto& attributes, const char* name) + + void* parentClassInstance = nullptr; + if (InstanceDataNode* parentInstanceDataNode = parent->GetParent()) + { + parentClassInstance = parentInstanceDataNode->FirstInstance(); + } + + auto consumeAttributes = [this, classInstance, wid](const auto& attributes, const char* name) { for (size_t i = 0; i < attributes.size(); ++i) { @@ -50,25 +57,43 @@ namespace AzToolsFramework } }; + auto consumeParentAttributes = [this, parentClassInstance, wid](const auto& attributes, const char* name) + { + if (parentClassInstance) + { + for (size_t i = 0; i < attributes.size(); ++i) + { + const auto& attrPair = attributes[i]; + PropertyAttributeReader reader(parentClassInstance, &*attrPair.second); + ConsumeParentAttribute(wid, attrPair.first, &reader, name); + } + } + }; + const AZ::SerializeContext::ClassElement* element = dataNode->GetElementMetadata(); if (element) { consumeAttributes(element->m_attributes, element->m_name); - const AZ::Edit::ElementData* elementEdit = dataNode->GetElementEditMetadata(); - if (elementEdit) + + if (const AZ::Edit::ElementData* elementEdit = dataNode->GetElementEditMetadata(); + elementEdit != nullptr) { consumeAttributes(elementEdit->m_attributes, elementEdit->m_name); } - } - if (dataNode->GetClassMetadata()) - { - const AZ::Edit::ClassData* classEditData = dataNode->GetClassMetadata()->m_editData; - if (classEditData) + const AZ::SerializeContext::ClassElement* parentElement = parent != dataNode ? + dataNode->GetElementMetadata() : + nullptr; + + if (parentElement != nullptr) { - for (auto it = classEditData->m_elements.begin(); it != classEditData->m_elements.end(); ++it) + // Reuse the current instance element name for the debug name + consumeParentAttributes(parentElement->m_attributes, element->m_name); + + if (const AZ::Edit::ElementData* elementEdit = parent->GetElementEditMetadata(); + elementEdit != nullptr) { - consumeAttributes(it->m_attributes, it->m_name); + consumeParentAttributes(elementEdit->m_attributes, elementEdit->m_name); } } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEnumComboBoxCtrl.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEnumComboBoxCtrl.hxx index 206b972b37..fc1d24b7a5 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEnumComboBoxCtrl.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyEnumComboBoxCtrl.hxx @@ -66,6 +66,12 @@ namespace AzToolsFramework class GenericEnumPropertyComboBoxHandler : public GenericComboBoxHandler { + virtual void ConsumeParentAttribute(GenericComboBoxCtrlBase* GUI, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName) override + { + // Simply re-route to ConsumeAttribute since no special logic is needed. + ConsumeAttribute(GUI, attrib, attrValue, debugName); + } + virtual void ConsumeAttribute(GenericComboBoxCtrlBase* GUI, AZ::u32 attrib, PropertyAttributeReader* attrValue, const char* debugName) override { (void)debugName; diff --git a/Gems/SurfaceData/Code/Include/SurfaceData/SurfaceTag.h b/Gems/SurfaceData/Code/Include/SurfaceData/SurfaceTag.h index d16856995d..ab24ba09f0 100644 --- a/Gems/SurfaceData/Code/Include/SurfaceData/SurfaceTag.h +++ b/Gems/SurfaceData/Code/Include/SurfaceData/SurfaceTag.h @@ -19,7 +19,8 @@ namespace SurfaceData { public: AZ_CLASS_ALLOCATOR(SurfaceTag, AZ::SystemAllocator, 0); - AZ_RTTI(SurfaceTag, "{67C8C6ED-F32A-443E-A777-1CAE48B22CD7}"); + AZ_TYPE_INFO(SurfaceTag, "{67C8C6ED-F32A-443E-A777-1CAE48B22CD7}"); + static void Reflect(AZ::ReflectContext* context); SurfaceTag() @@ -47,6 +48,8 @@ namespace SurfaceData m_surfaceTagCrc = AZ::Crc32(value.data()); } + AZStd::string GetDisplayName() const; + static AZStd::vector> GetRegisteredTags(); private: @@ -54,8 +57,6 @@ namespace SurfaceData AZStd::vector> BuildSelectableTagList() const; - AZStd::string GetDisplayName() const; - AZ::u32 m_surfaceTagCrc; }; diff --git a/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.cpp index d70915a861..23134e663d 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.cpp @@ -17,11 +17,14 @@ #include #include #include +#include #include #include #include +#include + namespace Terrain { void TerrainPhysicsSurfaceMaterialMapping::Reflect(AZ::ReflectContext* context) @@ -45,6 +48,8 @@ namespace Terrain ->DataElement( AZ::Edit::UIHandlers::ComboBox, &TerrainPhysicsSurfaceMaterialMapping::m_surfaceTag, "Surface Tag", "Surface type to map to a physics material.") + ->Attribute(AZ::Edit::Attributes::EnumValues, &TerrainPhysicsSurfaceMaterialMapping::BuildSelectableTagList) + ->DataElement(AZ::Edit::UIHandlers::Default, &TerrainPhysicsSurfaceMaterialMapping::m_materialId, "Material ID", "") ->ElementAttribute(Physics::Attributes::MaterialLibraryAssetId, &TerrainPhysicsSurfaceMaterialMapping::GetMaterialLibraryId) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) @@ -53,6 +58,30 @@ namespace Terrain } } + AZStd::vector> TerrainPhysicsSurfaceMaterialMapping::BuildSelectableTagList() const + { + AZ_PROFILE_FUNCTION(Entity); + + if (m_tagListProvider) + { + AZStd::vector> selectableTags = AZStd::move(m_tagListProvider->BuildSelectableTagList()); + + // Insert the tag currently in use by this mapping + selectableTags.push_back({ m_surfaceTag, m_surfaceTag.GetDisplayName() }); + + // Sorting for consistency + AZStd::sort(selectableTags.begin(), selectableTags.end(), [](const auto& lhs, const auto& rhs) {return lhs.second < rhs.second; }); + return selectableTags; + } + + return SurfaceData::SurfaceTag::GetRegisteredTags(); + } + + void TerrainPhysicsSurfaceMaterialMapping::SetTagListProvider(const EditorSelectableTagListProvider* tagListProvider) + { + m_tagListProvider = tagListProvider; + } + AZ::Data::AssetId TerrainPhysicsSurfaceMaterialMapping::GetMaterialLibraryId() { if (const auto* physicsSystem = AZ::Interface::Get()) diff --git a/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.h b/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.h index 5f79fa9103..97b5e49fca 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.h +++ b/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.h @@ -25,6 +25,8 @@ namespace LmbrCentral namespace Terrain { + class EditorSelectableTagListProvider; + static const uint8_t InvalidSurfaceTagIndex = 0xFF; struct TerrainPhysicsSurfaceMaterialMapping final @@ -33,12 +35,15 @@ namespace Terrain AZ_CLASS_ALLOCATOR(TerrainPhysicsSurfaceMaterialMapping, AZ::SystemAllocator, 0); AZ_RTTI(TerrainPhysicsSurfaceMaterialMapping, "{A88B5289-DFCD-4564-8395-E2177DFE5B18}"); static void Reflect(AZ::ReflectContext* context); + AZStd::vector> BuildSelectableTagList() const; + void SetTagListProvider(const EditorSelectableTagListProvider* tagListProvider); SurfaceData::SurfaceTag m_surfaceTag; Physics::MaterialId m_materialId; private: static AZ::Data::AssetId GetMaterialLibraryId(); + const EditorSelectableTagListProvider* m_tagListProvider = nullptr; }; class TerrainPhysicsColliderConfig diff --git a/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.cpp index 7d41b829c1..64b5d36a8f 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.cpp @@ -11,9 +11,11 @@ #include #include #include +#include #include #include +#include namespace Terrain { @@ -44,6 +46,7 @@ namespace Terrain ->DataElement( AZ::Edit::UIHandlers::Default, &TerrainSurfaceGradientMapping::m_surfaceTag, "Surface Tag", "Surface type to map to this gradient.") + ->Attribute(AZ::Edit::Attributes::EnumValues, &TerrainSurfaceGradientMapping::BuildSelectableTagList) ; } } @@ -60,6 +63,30 @@ namespace Terrain } } + AZStd::vector> TerrainSurfaceGradientMapping::BuildSelectableTagList() const + { + AZ_PROFILE_FUNCTION(Entity); + + if (m_tagListProvider) + { + AZStd::vector> selectableTags = AZStd::move(m_tagListProvider->BuildSelectableTagList()); + + // Insert the tag currently in use by this mapping + selectableTags.push_back({ m_surfaceTag, m_surfaceTag.GetDisplayName() }); + + // Sorting for consistency + AZStd::sort(selectableTags.begin(), selectableTags.end(), [](const auto& lhs, const auto& rhs) {return lhs.second < rhs.second; }); + return selectableTags; + } + + return SurfaceData::SurfaceTag::GetRegisteredTags(); + } + + void TerrainSurfaceGradientMapping::SetTagListProvider(const EditorSelectableTagListProvider* tagListProvider) + { + m_tagListProvider = tagListProvider; + } + void TerrainSurfaceGradientListConfig::Reflect(AZ::ReflectContext* context) { TerrainSurfaceGradientMapping::Reflect(context); diff --git a/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.h b/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.h index 36c16bed8f..b2f41fae88 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.h +++ b/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.h @@ -25,6 +25,8 @@ namespace LmbrCentral namespace Terrain { + class EditorSelectableTagListProvider; + class TerrainSurfaceGradientMapping final { public: @@ -39,8 +41,14 @@ namespace Terrain { } + AZStd::vector> BuildSelectableTagList() const; + void SetTagListProvider(const EditorSelectableTagListProvider* tagListProvider); + AZ::EntityId m_gradientEntityId; SurfaceData::SurfaceTag m_surfaceTag; + + private: + const EditorSelectableTagListProvider* m_tagListProvider = nullptr; }; class TerrainSurfaceGradientListConfig : public AZ::ComponentConfig diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.cpp b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.cpp index 6df6c3b440..09f99fd7fe 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.cpp +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.cpp @@ -21,4 +21,38 @@ namespace Terrain typename BaseClassType::WrappedConfigType, 1> ); } + + void EditorTerrainPhysicsColliderComponent::Activate() + { + UpdateConfigurationTagProvider(); + BaseClassType::Activate(); + } + + AZStd::unordered_set EditorTerrainPhysicsColliderComponent::GetSurfaceTagsInUse() const + { + AZStd::unordered_set tagsInUse; + + for (const TerrainPhysicsSurfaceMaterialMapping& mapping : m_configuration.m_surfaceMaterialMappings) + { + AZ::u32 crc = mapping.m_surfaceTag; + tagsInUse.insert(crc); + } + + return AZStd::move(tagsInUse); + } + + AZ::u32 EditorTerrainPhysicsColliderComponent::ConfigurationChanged() + { + UpdateConfigurationTagProvider(); + return BaseClassType::ConfigurationChanged(); + } + + void EditorTerrainPhysicsColliderComponent::UpdateConfigurationTagProvider() + { + for (TerrainPhysicsSurfaceMaterialMapping& mapping : m_configuration.m_surfaceMaterialMappings) + { + mapping.SetTagListProvider(this); + } + } + } diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h index 924426c262..fb724507d6 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h @@ -11,22 +11,34 @@ #include #include #include +#include namespace Terrain { class EditorTerrainPhysicsColliderComponent : public LmbrCentral::EditorWrappedComponentBase + , public EditorSelectableTagListProvider { public: using BaseClassType = LmbrCentral::EditorWrappedComponentBase; AZ_EDITOR_COMPONENT(EditorTerrainPhysicsColliderComponent, "{C43FAB8F-3968-46A6-920E-E84AEDED3DF5}", BaseClassType); static void Reflect(AZ::ReflectContext* context); + // AZ::Component interface implementation + void Activate() override; + static constexpr auto s_categoryName = "Terrain"; static constexpr auto s_componentName = "Terrain Physics Heightfield Collider"; static constexpr auto s_componentDescription = "Provides terrain data to a physics collider in the form of a heightfield and surface->material mapping."; static constexpr auto s_icon = "Editor/Icons/Components/TerrainPhysicsCollider.svg"; static constexpr auto s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainPhysicsCollider.svg"; static constexpr auto s_helpUrl = ""; + + private: + // EditorSelectableTagListProvider interface implementation + AZStd::unordered_set GetSurfaceTagsInUse() const override; + + AZ::u32 ConfigurationChanged() override; + void UpdateConfigurationTagProvider(); }; } diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.cpp b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.cpp index bc823734b4..50d45d6cf0 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.cpp +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.cpp @@ -20,4 +20,37 @@ namespace Terrain typename BaseClassType::WrappedConfigType, 1> ); } + + void EditorTerrainSurfaceGradientListComponent::Activate() + { + UpdateConfigurationTagProvider(); + BaseClassType::Activate(); + } + + AZ::u32 EditorTerrainSurfaceGradientListComponent::ConfigurationChanged() + { + UpdateConfigurationTagProvider(); + return BaseClassType::ConfigurationChanged(); + } + + void EditorTerrainSurfaceGradientListComponent::UpdateConfigurationTagProvider() + { + for (TerrainSurfaceGradientMapping& mapping : m_configuration.m_gradientSurfaceMappings) + { + mapping.SetTagListProvider(this); + } + } + + AZStd::unordered_set EditorTerrainSurfaceGradientListComponent::GetSurfaceTagsInUse() const + { + AZStd::unordered_set tagsInUse; + + for (const TerrainSurfaceGradientMapping& mapping : m_configuration.m_gradientSurfaceMappings) + { + AZ::u32 crc = mapping.m_surfaceTag; + tagsInUse.insert(crc); + } + + return AZStd::move(tagsInUse); + } } diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h index 58cb776823..37fafdc0a9 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h @@ -11,22 +11,34 @@ #include #include #include +#include namespace Terrain { class EditorTerrainSurfaceGradientListComponent : public LmbrCentral::EditorWrappedComponentBase + , public EditorSelectableTagListProvider { public: using BaseClassType = LmbrCentral::EditorWrappedComponentBase; AZ_EDITOR_COMPONENT(EditorTerrainSurfaceGradientListComponent, "{49831E91-A11F-4EFF-A824-6D85C284B934}", BaseClassType); static void Reflect(AZ::ReflectContext* context); + // AZ::Component interface implementation + void Activate() override; + static constexpr const char* const s_categoryName = "Terrain"; static constexpr const char* const s_componentName = "Terrain Surface Gradient List"; static constexpr const char* const s_componentDescription = "Provides a mapping between gradients and surface tags for use by the terrain system."; static constexpr const char* const s_icon = "Editor/Icons/Components/TerrainSurfaceGradientList.svg"; static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/TerrainSurfaceGradientList.svg"; static constexpr const char* const s_helpUrl = "https://o3de.org/docs/user-guide/components/reference/terrain/surface-gradient-list/"; + + private: + // EditorSelectableTagListProvider interface implementation + AZStd::unordered_set GetSurfaceTagsInUse() const override; + + AZ::u32 ConfigurationChanged() override; + void UpdateConfigurationTagProvider(); }; } diff --git a/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.cpp b/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.cpp new file mode 100644 index 0000000000..82ea70158c --- /dev/null +++ b/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +namespace Terrain +{ + AZStd::vector> EditorSelectableTagListProvider::BuildSelectableTagList() const + { + AZStd::vector> availableTags = SurfaceData::SurfaceTag::GetRegisteredTags(); + + AZStd::unordered_set tagsInUse = AZStd::move(GetSurfaceTagsInUse()); + + // Filter out all tags in use from the list of registered tags + availableTags.erase(std::remove_if(availableTags.begin(), availableTags.end(), + [&tagsInUse](const auto& tag)-> bool + { + return tagsInUse.contains(tag.first); + }), availableTags.end()); + + return AZStd::move(availableTags); + } +} diff --git a/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.h b/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.h new file mode 100644 index 0000000000..d8640bd73f --- /dev/null +++ b/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once +#include +#include +#include + +namespace Terrain +{ + //! Interface for a class providing information about surface tags available for selecting in Editor components. + class EditorSelectableTagListProvider + { + public: + //! Returns a list of available tags to be selected in the component. + virtual AZStd::vector> BuildSelectableTagList() const; + + //! Returns a set of CRC of all surface tags currently in use and not available for selecting. + virtual AZStd::unordered_set GetSurfaceTagsInUse() const = 0; + }; +} diff --git a/Gems/Terrain/Code/terrain_editor_shared_files.cmake b/Gems/Terrain/Code/terrain_editor_shared_files.cmake index 09724751a9..deb70ba566 100644 --- a/Gems/Terrain/Code/terrain_editor_shared_files.cmake +++ b/Gems/Terrain/Code/terrain_editor_shared_files.cmake @@ -25,6 +25,8 @@ set(FILES Source/EditorComponents/EditorTerrainSystemComponent.h Source/EditorTerrainModule.cpp Source/EditorTerrainModule.h + Source/EditorSelectableTagListProvider.h + Source/EditorSelectableTagListProvider.cpp Source/TerrainModule.cpp Source/TerrainModule.h Source/TerrainRenderer/EditorComponents/EditorTerrainSurfaceMaterialsListComponent.cpp From 08eb115e26c646440672f4e44ad341960c7bdcee Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 4 Feb 2022 14:02:24 +0000 Subject: [PATCH 012/133] fix various issues with collider manipulators and non-uniform scale Signed-off-by: greerdv --- .../ComponentModes/BoxViewportEdit.cpp | 43 +++++++++++-------- .../Manipulators/BoxManipulatorRequestBus.h | 5 +++ .../EditorAxisAlignedBoxShapeComponent.cpp | 5 +++ .../EditorAxisAlignedBoxShapeComponent.h | 1 + .../Source/Shape/EditorBoxShapeComponent.cpp | 5 +++ .../Source/Shape/EditorBoxShapeComponent.h | 1 + Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp | 5 +++ .../Code/Editor/ColliderRotationMode.cpp | 13 +++++- .../Code/Source/EditorColliderComponent.cpp | 19 +++++--- .../Code/Source/EditorColliderComponent.h | 2 + 10 files changed, 74 insertions(+), 25 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp index 7e496390c8..19d19563f9 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp @@ -40,25 +40,26 @@ namespace AzToolsFramework BoxManipulatorRequestBus::EventResult( boxWorldFromLocal, m_entityComponentIdPair, &BoxManipulatorRequests::GetCurrentTransform); - AZ::Vector3 boxScale = AZ::Vector3::CreateOne(); + AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); BoxManipulatorRequestBus::EventResult( - boxScale, m_entityComponentIdPair, &BoxManipulatorRequests::GetBoxScale); + nonUniformScale, m_entityComponentIdPair, &BoxManipulatorRequests::GetCurrentNonUniformScale); AZ::Vector3 boxDimensions = AZ::Vector3::CreateZero(); BoxManipulatorRequestBus::EventResult( boxDimensions, m_entityComponentIdPair, &BoxManipulatorRequests::GetDimensions); - // ensure we apply the entity scale to the box dimensions so - // the manipulators appear in the correct location - boxDimensions *= boxScale; + AZ::Transform boxLocalTransform = AZ::Transform::CreateIdentity(); + BoxManipulatorRequestBus::EventResult( + boxLocalTransform, m_entityComponentIdPair, &BoxManipulatorRequests::GetCurrentLocalTransform); for (size_t manipulatorIndex = 0; manipulatorIndex < m_linearManipulators.size(); ++manipulatorIndex) { if (auto& linearManipulator = m_linearManipulators[manipulatorIndex]) { linearManipulator->SetSpace(boxWorldFromLocal); - linearManipulator->SetLocalTransform( - AZ::Transform::CreateTranslation(s_boxAxes[manipulatorIndex] * 0.5f * boxDimensions)); + linearManipulator->SetLocalTransform(boxLocalTransform * AZ::Transform::CreateTranslation( + s_boxAxes[manipulatorIndex] * 0.5f * boxDimensions)); + linearManipulator->SetNonUniformScale(nonUniformScale); linearManipulator->SetBoundsDirty(); } } @@ -92,29 +93,35 @@ namespace AzToolsFramework [this, entityComponentIdPair]( const LinearManipulator::Action& action) { + AZ::Transform boxLocalTransform = AZ::Transform::CreateIdentity(); + BoxManipulatorRequestBus::EventResult( + boxLocalTransform, entityComponentIdPair, &BoxManipulatorRequests::GetCurrentLocalTransform); + + AZ::Transform boxWorldTransform = AZ::Transform::CreateIdentity(); + BoxManipulatorRequestBus::EventResult( + boxWorldTransform, entityComponentIdPair, &BoxManipulatorRequests::GetCurrentTransform); + float boxScale = AZ::GetMax(AZ::MinTransformScale, boxWorldTransform.GetUniformScale()); + + // calculate the position of the manipulator in the reference frame of the box + // the local position offset of the manipulator does not take the transform scale into account, so need to apply it here + const AZ::Vector3 localPosition = boxLocalTransform.GetInverse().TransformPoint( + action.m_start.m_localPosition + action.m_current.m_localPositionOffset / boxScale); + // calculate the amount of displacement along an axis this manipulator has moved // clamp movement so it cannot go negative based on axis direction const AZ::Vector3 axisDisplacement = - action.LocalPosition().GetAbs() * 2.0f - * AZ::GetMax(0.0f, action.LocalPosition().GetNormalized().Dot(action.m_fixed.m_axis)); - - AZ::Vector3 boxScale = AZ::Vector3::CreateOne(); - BoxManipulatorRequestBus::EventResult( - boxScale, entityComponentIdPair, &BoxManipulatorRequests::GetBoxScale); + localPosition.GetAbs() * 2.0f + * AZ::GetMax(0.0f, localPosition.GetNormalized().Dot(action.m_fixed.m_axis)); AZ::Vector3 boxDimensions = AZ::Vector3::CreateZero(); BoxManipulatorRequestBus::EventResult( boxDimensions, entityComponentIdPair, &BoxManipulatorRequests::GetDimensions); - // ensure we take into account the entity scale using the axis displacement - const AZ::Vector3 scaledAxisDisplacement = - axisDisplacement / boxScale; - // update dimensions - preserve dimensions not effected by this // axis, and update current axis displacement BoxManipulatorRequestBus::Event( entityComponentIdPair, &BoxManipulatorRequests::SetDimensions, - (NotAxis(action.m_fixed.m_axis) * boxDimensions).GetMax(scaledAxisDisplacement)); + (NotAxis(action.m_fixed.m_axis) * boxDimensions).GetMax(axisDisplacement)); UpdateManipulators(); }); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h index b0bcdf47f2..f1440e3d55 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h @@ -31,12 +31,17 @@ namespace AzToolsFramework //! because a collider may have an additional translation/orientation offset from //! the Entity transform. virtual AZ::Transform GetCurrentTransform() = 0; + //! + //! + virtual AZ::Transform GetCurrentLocalTransform() = 0; //! Get the scale currently applied to the box. //! With the Box Shape, the largest x/y/z component is taken //! so scale is always uniform, with colliders the scale may //! be different per component. virtual AZ::Vector3 GetBoxScale() = 0; + virtual AZ::Vector3 GetCurrentNonUniformScale() { return AZ::Vector3::CreateOne(); } + protected: ~BoxManipulatorRequests() = default; }; diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp index f78f2f048d..953bc9d349 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp @@ -161,6 +161,11 @@ namespace LmbrCentral return AzToolsFramework::TransformNormalizedScale(m_aaboxShape.GetCurrentTransform()); } + AZ::Transform EditorAxisAlignedBoxShapeComponent::GetCurrentLocalTransform() + { + return AZ::Transform::CreateIdentity(); + } + AZ::Vector3 EditorAxisAlignedBoxShapeComponent::GetBoxScale() { return AZ::Vector3(m_aaboxShape.GetCurrentTransform().GetUniformScale() * m_aaboxShape.GetCurrentNonUniformScale()); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.h index 8bff4ea7e1..a906b10129 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.h @@ -58,6 +58,7 @@ namespace LmbrCentral AZ::Vector3 GetDimensions() override; void SetDimensions(const AZ::Vector3& dimensions) override; AZ::Transform GetCurrentTransform() override; + AZ::Transform GetCurrentLocalTransform() override; AZ::Vector3 GetBoxScale() override; void ConfigurationChanged(); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorBoxShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorBoxShapeComponent.cpp index 2983ca7753..777e2f728b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorBoxShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorBoxShapeComponent.cpp @@ -167,6 +167,11 @@ namespace LmbrCentral return AzToolsFramework::TransformNormalizedScale(m_boxShape.GetCurrentTransform()); } + AZ::Transform EditorBoxShapeComponent::GetCurrentLocalTransform() + { + return AZ::Transform::CreateIdentity(); + } + AZ::Vector3 EditorBoxShapeComponent::GetBoxScale() { return AZ::Vector3(m_boxShape.GetCurrentTransform().GetUniformScale() * m_boxShape.GetCurrentNonUniformScale()); diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorBoxShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorBoxShapeComponent.h index aa24bda5c4..499a20497c 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorBoxShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorBoxShapeComponent.h @@ -57,6 +57,7 @@ namespace LmbrCentral AZ::Vector3 GetDimensions() override; void SetDimensions(const AZ::Vector3& dimensions) override; AZ::Transform GetCurrentTransform() override; + AZ::Transform GetCurrentLocalTransform() override; AZ::Vector3 GetBoxScale() override; void ConfigurationChanged(); diff --git a/Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp b/Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp index 21f27e4622..026eb177ac 100644 --- a/Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp @@ -10,6 +10,7 @@ #include #include +#include #include #include @@ -28,10 +29,14 @@ namespace PhysX AZ::Transform worldTransform; AZ::TransformBus::EventResult(worldTransform, idPair.GetEntityId(), &AZ::TransformInterface::GetWorldTM); + AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + AZ::Vector3 colliderOffset; PhysX::EditorColliderComponentRequestBus::EventResult(colliderOffset, idPair, &PhysX::EditorColliderComponentRequests::GetColliderOffset); m_translationManipulators.SetSpace(worldTransform); + m_translationManipulators.SetNonUniformScale(nonUniformScale); m_translationManipulators.SetLocalPosition(colliderOffset); m_translationManipulators.AddEntityComponentIdPair(idPair); m_translationManipulators.Register(AzToolsFramework::g_mainManipulatorManagerId); diff --git a/Gems/PhysX/Code/Editor/ColliderRotationMode.cpp b/Gems/PhysX/Code/Editor/ColliderRotationMode.cpp index 5f3c98bcee..d39fd001e4 100644 --- a/Gems/PhysX/Code/Editor/ColliderRotationMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderRotationMode.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -29,6 +30,9 @@ namespace PhysX AZ::Transform worldTransform; AZ::TransformBus::EventResult(worldTransform, idPair.GetEntityId(), &AZ::TransformInterface::GetWorldTM); + AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + AZ::Quaternion colliderRotation; PhysX::EditorColliderComponentRequestBus::EventResult(colliderRotation, idPair, &PhysX::EditorColliderComponentRequests::GetColliderRotation); @@ -36,7 +40,8 @@ namespace PhysX PhysX::EditorColliderComponentRequestBus::EventResult(colliderOffset, idPair, &PhysX::EditorColliderComponentRequests::GetColliderOffset); m_rotationManipulators.SetSpace(worldTransform); - m_rotationManipulators.SetLocalPosition(colliderOffset); + m_rotationManipulators.SetNonUniformScale(nonUniformScale); + m_rotationManipulators.SetLocalPosition(nonUniformScale * colliderOffset); m_rotationManipulators.SetLocalOrientation(colliderRotation); m_rotationManipulators.AddEntityComponentIdPair(idPair); m_rotationManipulators.Register(AzToolsFramework::g_mainManipulatorManagerId); @@ -70,7 +75,11 @@ namespace PhysX AZ::Vector3 colliderOffset = AZ::Vector3::CreateZero(); PhysX::EditorColliderComponentRequestBus::EventResult(colliderOffset, idPair, &PhysX::EditorColliderComponentRequests::GetColliderOffset); - m_rotationManipulators.SetLocalPosition(colliderOffset); + + AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + + m_rotationManipulators.SetLocalPosition(nonUniformScale * colliderOffset); } void ColliderRotationMode::Teardown(const AZ::EntityComponentIdPair& idPair) diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 7e1d1c341f..1adc4b941f 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -581,9 +581,8 @@ namespace PhysX AZ::Transform EditorColliderComponent::GetColliderLocalTransform() const { - const AZ::Vector3 nonUniformScale = Utils::GetTransformScale(GetEntityId()); return AZ::Transform::CreateFromQuaternionAndTranslation( - m_configuration.m_rotation, m_configuration.m_position * nonUniformScale); + m_configuration.m_rotation, m_configuration.m_position); } void EditorColliderComponent::UpdateMeshAsset() @@ -1053,12 +1052,22 @@ namespace PhysX AZ::Transform EditorColliderComponent::GetCurrentTransform() { - return GetColliderWorldTransform(); + return GetWorldTM(); + } + + AZ::Transform EditorColliderComponent::GetCurrentLocalTransform() + { + return GetColliderLocalTransform(); } AZ::Vector3 EditorColliderComponent::GetBoxScale() { - return AZ::Vector3(GetWorldTM().GetUniformScale()); + return AZ::Vector3::CreateOne(); + } + + AZ::Vector3 EditorColliderComponent::GetCurrentNonUniformScale() + { + return m_cachedNonUniformScale; } void EditorColliderComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) @@ -1202,7 +1211,7 @@ namespace PhysX AZ::Transform EditorColliderComponent::GetColliderWorldTransform() { - return AzToolsFramework::TransformNormalizedScale(GetWorldTM()) * GetColliderLocalTransform(); + return GetWorldTM() * GetColliderLocalTransform(); } bool EditorColliderComponent::ShouldUpdateCollisionMeshFromRender() const diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.h b/Gems/PhysX/Code/Source/EditorColliderComponent.h index 773dd0a9b8..52d788ecef 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.h +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.h @@ -171,7 +171,9 @@ namespace PhysX AZ::Vector3 GetDimensions() override; void SetDimensions(const AZ::Vector3& dimensions) override; AZ::Transform GetCurrentTransform() override; + AZ::Transform GetCurrentLocalTransform() override; AZ::Vector3 GetBoxScale() override; + AZ::Vector3 GetCurrentNonUniformScale() override; // AZ::Render::MeshComponentNotificationBus void OnModelReady(const AZ::Data::Asset& modelAsset, From d37315c2af58c03dad450121721dd17a75a29eb0 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 4 Feb 2022 15:54:47 +0000 Subject: [PATCH 013/133] tidy up bus usage Signed-off-by: greerdv --- .../ComponentModes/BoxViewportEdit.cpp | 18 ++++++++++-------- .../Manipulators/BoxManipulatorRequestBus.h | 11 +++++++---- .../Code/Source/EditorColliderComponent.cpp | 5 ----- .../Code/Source/EditorColliderComponent.h | 1 - 4 files changed, 17 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp index 19d19563f9..8c47bfc797 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp @@ -14,6 +14,8 @@ #include #include #include +#include +#include namespace AzToolsFramework { @@ -37,12 +39,12 @@ namespace AzToolsFramework void BoxViewportEdit::UpdateManipulators() { AZ::Transform boxWorldFromLocal = AZ::Transform::CreateIdentity(); - BoxManipulatorRequestBus::EventResult( - boxWorldFromLocal, m_entityComponentIdPair, &BoxManipulatorRequests::GetCurrentTransform); + AZ::TransformBus::EventResult( + boxWorldFromLocal, m_entityComponentIdPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); - BoxManipulatorRequestBus::EventResult( - nonUniformScale, m_entityComponentIdPair, &BoxManipulatorRequests::GetCurrentNonUniformScale); + AZ::NonUniformScaleRequestBus::EventResult( + nonUniformScale, m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); AZ::Vector3 boxDimensions = AZ::Vector3::CreateZero(); BoxManipulatorRequestBus::EventResult( @@ -70,8 +72,8 @@ namespace AzToolsFramework m_entityComponentIdPair = entityComponentIdPair; AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - BoxManipulatorRequestBus::EventResult( - worldFromLocal, entityComponentIdPair, &BoxManipulatorRequests::GetCurrentTransform); + AZ::TransformBus::EventResult( + worldFromLocal, entityComponentIdPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); for (size_t manipulatorIndex = 0; manipulatorIndex < m_linearManipulators.size(); ++manipulatorIndex) { @@ -98,8 +100,8 @@ namespace AzToolsFramework boxLocalTransform, entityComponentIdPair, &BoxManipulatorRequests::GetCurrentLocalTransform); AZ::Transform boxWorldTransform = AZ::Transform::CreateIdentity(); - BoxManipulatorRequestBus::EventResult( - boxWorldTransform, entityComponentIdPair, &BoxManipulatorRequests::GetCurrentTransform); + AZ::TransformBus::EventResult( + boxWorldTransform, m_entityComponentIdPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); float boxScale = AZ::GetMax(AZ::MinTransformScale, boxWorldTransform.GetUniformScale()); // calculate the position of the manipulator in the reference frame of the box diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h index f1440e3d55..359b92502e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h @@ -26,22 +26,25 @@ namespace AzToolsFramework virtual AZ::Vector3 GetDimensions() = 0; //! Set the X/Y/Z dimensions of the box shape/collider. virtual void SetDimensions(const AZ::Vector3& dimensions) = 0; + //! @deprecated Because non-uniform scale effects can be complex, it is recommended to separately use + //! AZ::TransformBus::Events::GetWorldTM, AZ::NonUniformScaleRequests::GetScale and GetCurrentLocalTransform + //! and combine their effects. //! Get the transform of the box shape/collider. //! This is used by \ref BoxComponentMode instead of the \ref \AZ::TransformBus //! because a collider may have an additional translation/orientation offset from //! the Entity transform. virtual AZ::Transform GetCurrentTransform() = 0; - //! - //! + //! Get the transform of the box relative to the entity. virtual AZ::Transform GetCurrentLocalTransform() = 0; + //! @deprecated Because non-uniform scale effects can be complex, it is recommended to separately use + //! AZ::TransformBus::Events::GetWorldTM, AZ::NonUniformScaleRequests::GetScale and GetCurrentLocalTransform + //! and combine their effects. //! Get the scale currently applied to the box. //! With the Box Shape, the largest x/y/z component is taken //! so scale is always uniform, with colliders the scale may //! be different per component. virtual AZ::Vector3 GetBoxScale() = 0; - virtual AZ::Vector3 GetCurrentNonUniformScale() { return AZ::Vector3::CreateOne(); } - protected: ~BoxManipulatorRequests() = default; }; diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 1adc4b941f..03e4bdb63e 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -1065,11 +1065,6 @@ namespace PhysX return AZ::Vector3::CreateOne(); } - AZ::Vector3 EditorColliderComponent::GetCurrentNonUniformScale() - { - return m_cachedNonUniformScale; - } - void EditorColliderComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) { if (world.IsClose(m_cachedWorldTransform)) diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.h b/Gems/PhysX/Code/Source/EditorColliderComponent.h index 52d788ecef..bc3d4da6d9 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.h +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.h @@ -173,7 +173,6 @@ namespace PhysX AZ::Transform GetCurrentTransform() override; AZ::Transform GetCurrentLocalTransform() override; AZ::Vector3 GetBoxScale() override; - AZ::Vector3 GetCurrentNonUniformScale() override; // AZ::Render::MeshComponentNotificationBus void OnModelReady(const AZ::Data::Asset& modelAsset, From bb4c89631160651db89f3b9b1fd686ab079208c3 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 4 Feb 2022 16:35:49 +0000 Subject: [PATCH 014/133] fix scaling issue with collider offset manipulators Signed-off-by: greerdv --- Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp | 16 ++++++++++------ Gems/PhysX/Code/Editor/ColliderOffsetMode.h | 3 ++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp b/Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp index 026eb177ac..2c9b90d5b3 100644 --- a/Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderOffsetMode.cpp @@ -45,19 +45,19 @@ namespace PhysX m_translationManipulators.InstallLinearManipulatorMouseMoveCallback([this, idPair]( const AzToolsFramework::LinearManipulator::Action& action) { - OnManipulatorMoved(action.LocalPosition(), idPair); + OnManipulatorMoved(action.m_start.m_localPosition, action.m_current.m_localPositionOffset, idPair); }); m_translationManipulators.InstallPlanarManipulatorMouseMoveCallback([this, idPair]( const AzToolsFramework::PlanarManipulator::Action& action) { - OnManipulatorMoved(action.LocalPosition(), idPair); + OnManipulatorMoved(action.m_start.m_localPosition, action.m_current.m_localOffset, idPair); }); m_translationManipulators.InstallSurfaceManipulatorMouseMoveCallback([this, idPair]( const AzToolsFramework::SurfaceManipulator::Action& action) { - OnManipulatorMoved(action.LocalPosition(), idPair); + OnManipulatorMoved(action.m_start.m_localPosition, action.m_current.m_localOffset, idPair); }); } @@ -74,10 +74,14 @@ namespace PhysX m_translationManipulators.Unregister(); } - void ColliderOffsetMode::OnManipulatorMoved(const AZ::Vector3& position, const AZ::EntityComponentIdPair& idPair) + void ColliderOffsetMode::OnManipulatorMoved(const AZ::Vector3& startPosition, const AZ::Vector3& offset, const AZ::EntityComponentIdPair& idPair) { - m_translationManipulators.SetLocalPosition(position); - PhysX::EditorColliderComponentRequestBus::Event(idPair, &PhysX::EditorColliderComponentRequests::SetColliderOffset, position); + AZ::Transform worldTransform = AZ::Transform::CreateIdentity(); + AZ::TransformBus::EventResult(worldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); + const float scale = AZ::GetMax(AZ::MinTransformScale, worldTransform.GetUniformScale()); + const AZ::Vector3 newPosition = startPosition + offset / scale; + m_translationManipulators.SetLocalPosition(newPosition); + PhysX::EditorColliderComponentRequestBus::Event(idPair, &PhysX::EditorColliderComponentRequests::SetColliderOffset, newPosition); } void ColliderOffsetMode::ResetValues(const AZ::EntityComponentIdPair& idPair) diff --git a/Gems/PhysX/Code/Editor/ColliderOffsetMode.h b/Gems/PhysX/Code/Editor/ColliderOffsetMode.h index 6a2e6a8a12..525000a1b1 100644 --- a/Gems/PhysX/Code/Editor/ColliderOffsetMode.h +++ b/Gems/PhysX/Code/Editor/ColliderOffsetMode.h @@ -28,7 +28,8 @@ namespace PhysX void ResetValues(const AZ::EntityComponentIdPair& idPair) override; private: - void OnManipulatorMoved(const AZ::Vector3& position, const AZ::EntityComponentIdPair& idPair); + void OnManipulatorMoved( + const AZ::Vector3& startPosition, const AZ::Vector3& offset, const AZ::EntityComponentIdPair& idPair); AzToolsFramework::TranslationManipulators m_translationManipulators; }; From a4d5587183d66dd5bf606472fccdd6fa065b0e5a Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 4 Feb 2022 18:30:09 +0000 Subject: [PATCH 015/133] fix scaling manipulator for sphere collider with non-uniform scale Signed-off-by: greerdv --- Gems/PhysX/Code/Editor/ColliderSphereMode.cpp | 59 ++++++++++++++++--- 1 file changed, 50 insertions(+), 9 deletions(-) diff --git a/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp b/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp index ba0fd76ea9..335d1339a8 100644 --- a/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -24,10 +25,27 @@ namespace PhysX static const float MinSphereRadius = 0.01f; static const AZ::Vector3 ManipulatorAxis = AZ::Vector3::CreateAxisX(); + AZ::Transform GetColliderLocalTransform(const AZ::EntityComponentIdPair& idPair) + { + AZ::Quaternion colliderRotation = AZ::Quaternion::CreateIdentity(); + PhysX::EditorColliderComponentRequestBus::EventResult(colliderRotation, idPair, &PhysX::EditorColliderComponentRequests::GetColliderRotation); + + AZ::Vector3 colliderOffset = AZ::Vector3::CreateZero(); + PhysX::EditorColliderComponentRequestBus::EventResult(colliderOffset, idPair, &PhysX::EditorColliderComponentRequests::GetColliderOffset); + + return AZ::Transform::CreateFromQuaternionAndTranslation(colliderRotation, colliderOffset); + } + void ColliderSphereMode::Setup(const AZ::EntityComponentIdPair& idPair) { AZ::Transform colliderWorldTransform = AZ::Transform::Identity(); - PhysX::EditorColliderComponentRequestBus::EventResult(colliderWorldTransform, idPair, &PhysX::EditorColliderComponentRequests::GetColliderWorldTransform); + AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); + //PhysX::EditorColliderComponentRequestBus::EventResult(colliderWorldTransform, idPair, &PhysX::EditorColliderComponentRequests::GetColliderWorldTransform); + + AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + + const AZ::Transform colliderLocalTransform = GetColliderLocalTransform(idPair); float sphereRadius = 0.0f; PhysX::EditorColliderComponentRequestBus::EventResult(sphereRadius, idPair, &PhysX::EditorColliderComponentRequests::GetSphereRadius); @@ -36,7 +54,10 @@ namespace PhysX m_radiusManipulator->AddEntityComponentIdPair(idPair); m_radiusManipulator->SetAxis(ManipulatorAxis); m_radiusManipulator->Register(AzToolsFramework::g_mainManipulatorManagerId); - m_radiusManipulator->SetLocalPosition(ManipulatorAxis * sphereRadius); + //m_radiusManipulator->SetLocalPosition(ManipulatorAxis * sphereRadius); + m_radiusManipulator->SetLocalTransform(colliderLocalTransform * AZ::Transform::CreateTranslation(ManipulatorAxis * sphereRadius)); + m_radiusManipulator->SetNonUniformScale(nonUniformScale); + m_radiusManipulator->SetBoundsDirty(); AzToolsFramework::ManipulatorViews views; views.emplace_back(AzToolsFramework::CreateManipulatorViewQuadBillboard(AzFramework::ViewportColors::DefaultManipulatorHandleColor, AzFramework::ViewportConstants::DefaultManipulatorHandleSize)); @@ -53,12 +74,19 @@ namespace PhysX void ColliderSphereMode::Refresh(const AZ::EntityComponentIdPair& idPair) { AZ::Transform colliderWorldTransform = AZ::Transform::Identity(); - PhysX::EditorColliderComponentRequestBus::EventResult(colliderWorldTransform, idPair, &PhysX::EditorColliderComponentRequests::GetColliderWorldTransform); + AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); + //PhysX::EditorColliderComponentRequestBus::EventResult(colliderWorldTransform, idPair, &PhysX::EditorColliderComponentRequests::GetColliderWorldTransform); m_radiusManipulator->SetSpace(colliderWorldTransform); + AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + + const AZ::Transform colliderLocalTransform = GetColliderLocalTransform(idPair); + float sphereRadius = 0.0f; PhysX::EditorColliderComponentRequestBus::EventResult(sphereRadius, idPair, &PhysX::EditorColliderComponentRequests::GetSphereRadius); - m_radiusManipulator->SetLocalPosition(ManipulatorAxis * sphereRadius); + m_radiusManipulator->SetLocalTransform(colliderLocalTransform * AZ::Transform::CreateTranslation(ManipulatorAxis * sphereRadius)); + m_radiusManipulator->SetBoundsDirty(); } void ColliderSphereMode::Teardown(const AZ::EntityComponentIdPair& idPair) @@ -80,22 +108,35 @@ namespace PhysX AZ_UNUSED(debugDisplay); const AzFramework::CameraState cameraState = AzToolsFramework::GetCameraState(viewportInfo.m_viewportId); - float radius = m_radiusManipulator->GetLocalPosition().GetLength(); - m_radiusManipulator->SetAxis(cameraState.m_side); - m_radiusManipulator->SetLocalPosition(cameraState.m_side * radius); + if (!m_radiusManipulator->EntityComponentIdPairs().empty()) + { + const AZ::EntityComponentIdPair idPair = *m_radiusManipulator->EntityComponentIdPairs().begin(); + float radius = 0.0f; + PhysX::EditorColliderComponentRequestBus::EventResult(radius, idPair, &PhysX::EditorColliderComponentRequests::GetSphereRadius); + const AZ::Transform colliderLocalTransform = GetColliderLocalTransform(idPair); + m_radiusManipulator->SetAxis(cameraState.m_side); + m_radiusManipulator->SetLocalTransform(GetColliderLocalTransform(idPair) * AZ::Transform::CreateTranslation(cameraState.m_side * radius)); + } } void ColliderSphereMode::OnManipulatorMoved(const AzToolsFramework::LinearManipulator::Action& action, const AZ::EntityComponentIdPair& idPair) { + // manipulator offsets do not take transform scale into account, need to handle it here + AZ::Transform colliderWorldTransform = AZ::Transform::CreateIdentity(); + AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); + const float transformScale = AZ::GetMax(AZ::MinTransformScale, colliderWorldTransform.GetUniformScale()); + const AZ::Vector3 localPosition = action.m_start.m_localPosition + action.m_current.m_localPositionOffset / transformScale; + // Get the distance the manipulator has moved along the axis. - float extent = action.LocalPosition().Dot(action.m_fixed.m_axis); + float extent = localPosition.Dot(action.m_fixed.m_axis); // Clamp the distance to a small value to prevent it going negative. extent = AZ::GetMax(extent, MinSphereRadius); // Update the manipulator and sphere radius - m_radiusManipulator->SetLocalPosition(extent * action.m_fixed.m_axis); + m_radiusManipulator->SetLocalTransform( + GetColliderLocalTransform(idPair) * AZ::Transform::CreateTranslation(extent * action.m_fixed.m_axis)); PhysX::EditorColliderComponentRequestBus::Event(idPair, &PhysX::EditorColliderComponentRequests::SetSphereRadius, extent); } } From 8ca4dbf2daa125e013355573e9b21b82885e5386 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 4 Feb 2022 18:56:59 +0000 Subject: [PATCH 016/133] refactor and tidy up Signed-off-by: greerdv --- Gems/PhysX/Code/Editor/ColliderSphereMode.cpp | 25 +++++-------------- Gems/PhysX/Code/Source/Utils.cpp | 12 +++++++++ Gems/PhysX/Code/Source/Utils.h | 3 +++ 3 files changed, 21 insertions(+), 19 deletions(-) diff --git a/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp b/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp index 335d1339a8..8425f203c1 100644 --- a/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp @@ -8,6 +8,7 @@ #include "ColliderSphereMode.h" #include +#include #include #include @@ -25,27 +26,15 @@ namespace PhysX static const float MinSphereRadius = 0.01f; static const AZ::Vector3 ManipulatorAxis = AZ::Vector3::CreateAxisX(); - AZ::Transform GetColliderLocalTransform(const AZ::EntityComponentIdPair& idPair) - { - AZ::Quaternion colliderRotation = AZ::Quaternion::CreateIdentity(); - PhysX::EditorColliderComponentRequestBus::EventResult(colliderRotation, idPair, &PhysX::EditorColliderComponentRequests::GetColliderRotation); - - AZ::Vector3 colliderOffset = AZ::Vector3::CreateZero(); - PhysX::EditorColliderComponentRequestBus::EventResult(colliderOffset, idPair, &PhysX::EditorColliderComponentRequests::GetColliderOffset); - - return AZ::Transform::CreateFromQuaternionAndTranslation(colliderRotation, colliderOffset); - } - void ColliderSphereMode::Setup(const AZ::EntityComponentIdPair& idPair) { AZ::Transform colliderWorldTransform = AZ::Transform::Identity(); AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); - //PhysX::EditorColliderComponentRequestBus::EventResult(colliderWorldTransform, idPair, &PhysX::EditorColliderComponentRequests::GetColliderWorldTransform); AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); - const AZ::Transform colliderLocalTransform = GetColliderLocalTransform(idPair); + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); float sphereRadius = 0.0f; PhysX::EditorColliderComponentRequestBus::EventResult(sphereRadius, idPair, &PhysX::EditorColliderComponentRequests::GetSphereRadius); @@ -54,7 +43,6 @@ namespace PhysX m_radiusManipulator->AddEntityComponentIdPair(idPair); m_radiusManipulator->SetAxis(ManipulatorAxis); m_radiusManipulator->Register(AzToolsFramework::g_mainManipulatorManagerId); - //m_radiusManipulator->SetLocalPosition(ManipulatorAxis * sphereRadius); m_radiusManipulator->SetLocalTransform(colliderLocalTransform * AZ::Transform::CreateTranslation(ManipulatorAxis * sphereRadius)); m_radiusManipulator->SetNonUniformScale(nonUniformScale); m_radiusManipulator->SetBoundsDirty(); @@ -75,13 +63,12 @@ namespace PhysX { AZ::Transform colliderWorldTransform = AZ::Transform::Identity(); AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); - //PhysX::EditorColliderComponentRequestBus::EventResult(colliderWorldTransform, idPair, &PhysX::EditorColliderComponentRequests::GetColliderWorldTransform); m_radiusManipulator->SetSpace(colliderWorldTransform); AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); - const AZ::Transform colliderLocalTransform = GetColliderLocalTransform(idPair); + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); float sphereRadius = 0.0f; PhysX::EditorColliderComponentRequestBus::EventResult(sphereRadius, idPair, &PhysX::EditorColliderComponentRequests::GetSphereRadius); @@ -114,9 +101,9 @@ namespace PhysX const AZ::EntityComponentIdPair idPair = *m_radiusManipulator->EntityComponentIdPairs().begin(); float radius = 0.0f; PhysX::EditorColliderComponentRequestBus::EventResult(radius, idPair, &PhysX::EditorColliderComponentRequests::GetSphereRadius); - const AZ::Transform colliderLocalTransform = GetColliderLocalTransform(idPair); + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); m_radiusManipulator->SetAxis(cameraState.m_side); - m_radiusManipulator->SetLocalTransform(GetColliderLocalTransform(idPair) * AZ::Transform::CreateTranslation(cameraState.m_side * radius)); + m_radiusManipulator->SetLocalTransform(colliderLocalTransform * AZ::Transform::CreateTranslation(cameraState.m_side * radius)); } } @@ -136,7 +123,7 @@ namespace PhysX // Update the manipulator and sphere radius m_radiusManipulator->SetLocalTransform( - GetColliderLocalTransform(idPair) * AZ::Transform::CreateTranslation(extent * action.m_fixed.m_axis)); + Utils::GetColliderLocalTransform(idPair) * AZ::Transform::CreateTranslation(extent * action.m_fixed.m_axis)); PhysX::EditorColliderComponentRequestBus::Event(idPair, &PhysX::EditorColliderComponentRequests::SetSphereRadius, extent); } } diff --git a/Gems/PhysX/Code/Source/Utils.cpp b/Gems/PhysX/Code/Source/Utils.cpp index cc4ef2a12c..9848ab0415 100644 --- a/Gems/PhysX/Code/Source/Utils.cpp +++ b/Gems/PhysX/Code/Source/Utils.cpp @@ -29,6 +29,7 @@ #include #include +#include #include #include #include @@ -832,6 +833,17 @@ namespace PhysX return AZ::Transform::CreateFromQuaternionAndTranslation(colliderRelativeRotation, colliderRelativePosition); } + AZ::Transform GetColliderLocalTransform(const AZ::EntityComponentIdPair& idPair) + { + AZ::Quaternion colliderRotation = AZ::Quaternion::CreateIdentity(); + PhysX::EditorColliderComponentRequestBus::EventResult(colliderRotation, idPair, &PhysX::EditorColliderComponentRequests::GetColliderRotation); + + AZ::Vector3 colliderOffset = AZ::Vector3::CreateZero(); + PhysX::EditorColliderComponentRequestBus::EventResult(colliderOffset, idPair, &PhysX::EditorColliderComponentRequests::GetColliderOffset); + + return AZ::Transform::CreateFromQuaternionAndTranslation(colliderRotation, colliderOffset); + } + AZ::Transform GetColliderWorldTransform(const AZ::Transform& worldTransform, const AZ::Vector3& colliderRelativePosition, const AZ::Quaternion& colliderRelativeRotation) diff --git a/Gems/PhysX/Code/Source/Utils.h b/Gems/PhysX/Code/Source/Utils.h index 5244926aa2..f9e25a59f2 100644 --- a/Gems/PhysX/Code/Source/Utils.h +++ b/Gems/PhysX/Code/Source/Utils.h @@ -142,6 +142,9 @@ namespace PhysX AZ::Transform GetColliderLocalTransform(const AZ::Vector3& colliderRelativePosition , const AZ::Quaternion& colliderRelativeRotation); + //! Gets the local transform for a collider (the position and rotation relative to its entity). + AZ::Transform GetColliderLocalTransform(const AZ::EntityComponentIdPair& idPair); + //! Combines collider position and orientation offsets and world transform to a transform. AZ::Transform GetColliderWorldTransform(const AZ::Transform& worldTransform , const AZ::Vector3& colliderRelativePosition From 773336d38879b07326040759496e05c449aa99d1 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 4 Feb 2022 18:56:59 +0000 Subject: [PATCH 017/133] refactor and tidy up Signed-off-by: greerdv --- .../PhysX/Code/Editor/ColliderCapsuleMode.cpp | 92 +++++++++++++++---- Gems/PhysX/Code/Editor/ColliderCapsuleMode.h | 12 ++- Gems/PhysX/Code/Editor/ColliderSphereMode.cpp | 4 +- 3 files changed, 85 insertions(+), 23 deletions(-) diff --git a/Gems/PhysX/Code/Editor/ColliderCapsuleMode.cpp b/Gems/PhysX/Code/Editor/ColliderCapsuleMode.cpp index 0bc941b082..eddd65a7f0 100644 --- a/Gems/PhysX/Code/Editor/ColliderCapsuleMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderCapsuleMode.cpp @@ -8,11 +8,13 @@ #include "ColliderCapsuleMode.h" #include +#include #include #include #include #include +#include #include #include @@ -34,10 +36,15 @@ namespace PhysX void ColliderCapsuleMode::Setup(const AZ::EntityComponentIdPair& idPair) { AZ::Transform colliderWorldTransform = AZ::Transform::Identity(); - PhysX::EditorColliderComponentRequestBus::EventResult(colliderWorldTransform, idPair, &PhysX::EditorColliderComponentRequests::GetColliderWorldTransform); + AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); - SetupRadiusManipulator(idPair, colliderWorldTransform); - SetupHeightManipulator(idPair, colliderWorldTransform); + AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); + + SetupRadiusManipulator(idPair, colliderWorldTransform, colliderLocalTransform, nonUniformScale); + SetupHeightManipulator(idPair, colliderWorldTransform, colliderLocalTransform, nonUniformScale); AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(idPair.GetEntityId()); } @@ -45,7 +52,12 @@ namespace PhysX void ColliderCapsuleMode::Refresh(const AZ::EntityComponentIdPair& idPair) { AZ::Transform colliderWorldTransform = AZ::Transform::Identity(); - PhysX::EditorColliderComponentRequestBus::EventResult(colliderWorldTransform, idPair, &PhysX::EditorColliderComponentRequests::GetColliderWorldTransform); + AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); + + AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(nonUniformScale, idPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + + AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); // Read the state of the capsule into manipulators to support undo/redo float capsuleHeight = 0.0f; @@ -55,9 +67,13 @@ namespace PhysX PhysX::EditorColliderComponentRequestBus::EventResult(capsuleRadius, idPair, &PhysX::EditorColliderComponentRequests::GetCapsuleRadius); m_radiusManipulator->SetSpace(colliderWorldTransform); - m_radiusManipulator->SetLocalPosition(m_radiusManipulator->GetAxis() * capsuleRadius); + m_radiusManipulator->SetLocalTransform( + colliderLocalTransform * AZ::Transform::CreateTranslation(m_radiusManipulator->GetAxis() * capsuleRadius)); + m_radiusManipulator->SetNonUniformScale(nonUniformScale); m_heightManipulator->SetSpace(colliderWorldTransform); - m_heightManipulator->SetLocalPosition(m_heightManipulator->GetAxis() * capsuleHeight * HalfHeight); + m_heightManipulator->SetLocalTransform( + colliderLocalTransform * AZ::Transform::CreateTranslation(m_heightManipulator->GetAxis() * capsuleHeight * HalfHeight)); + m_heightManipulator->SetNonUniformScale(nonUniformScale); } void ColliderCapsuleMode::Teardown(const AZ::EntityComponentIdPair& idPair) @@ -83,13 +99,23 @@ namespace PhysX AZ_UNUSED(debugDisplay); const AzFramework::CameraState cameraState = AzToolsFramework::GetCameraState(viewportInfo.m_viewportId); - float radius = m_radiusManipulator->GetLocalPosition().GetLength(); - m_radiusManipulator->SetAxis(cameraState.m_side); - m_radiusManipulator->SetLocalPosition(cameraState.m_side * radius); + if (!m_radiusManipulator->EntityComponentIdPairs().empty()) + { + const AZ::EntityComponentIdPair idPair = *m_radiusManipulator->EntityComponentIdPairs().begin(); + float radius = 0.0f; + PhysX::EditorColliderComponentRequestBus::EventResult(radius, idPair, &PhysX::EditorColliderComponentRequests::GetCapsuleRadius); + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); + m_radiusManipulator->SetAxis(cameraState.m_side); + m_radiusManipulator->SetLocalTransform(colliderLocalTransform * AZ::Transform::CreateTranslation(cameraState.m_side * radius)); + } } - void ColliderCapsuleMode::SetupRadiusManipulator(const AZ::EntityComponentIdPair& idPair, const AZ::Transform& worldTransform) + void ColliderCapsuleMode::SetupRadiusManipulator( + const AZ::EntityComponentIdPair& idPair, + const AZ::Transform& worldTransform, + const AZ::Transform& localTransform, + const AZ::Vector3& nonUniformScale) { // Radius manipulator float capsuleRadius = 0.0f; @@ -99,7 +125,8 @@ namespace PhysX m_radiusManipulator->AddEntityComponentIdPair(idPair); m_radiusManipulator->SetAxis(RadiusManipulatorAxis); m_radiusManipulator->Register(AzToolsFramework::g_mainManipulatorManagerId); - m_radiusManipulator->SetLocalPosition(RadiusManipulatorAxis * capsuleRadius); + m_radiusManipulator->SetLocalTransform(localTransform * AZ::Transform::CreateTranslation(RadiusManipulatorAxis * capsuleRadius)); + m_radiusManipulator->SetNonUniformScale(nonUniformScale); { AzToolsFramework::ManipulatorViews views; @@ -114,7 +141,11 @@ namespace PhysX }); } - void ColliderCapsuleMode::SetupHeightManipulator(const AZ::EntityComponentIdPair& idPair, const AZ::Transform& worldTransform) + void ColliderCapsuleMode::SetupHeightManipulator( + const AZ::EntityComponentIdPair& idPair, + const AZ::Transform& worldTransform, + const AZ::Transform& localTransform, + const AZ::Vector3& nonUniformScale) { // Height manipulator float capsuleHeight = 0.0f; @@ -124,7 +155,9 @@ namespace PhysX m_heightManipulator->AddEntityComponentIdPair(idPair); m_heightManipulator->SetAxis(HeightManipulatorAxis); m_heightManipulator->Register(AzToolsFramework::g_mainManipulatorManagerId); - m_heightManipulator->SetLocalPosition(HeightManipulatorAxis * capsuleHeight * HalfHeight); // Manipulator positioned at half the capsules height. + m_heightManipulator->SetLocalTransform( + localTransform * AZ::Transform::CreateTranslation(HeightManipulatorAxis * capsuleHeight * HalfHeight)); + m_heightManipulator->SetNonUniformScale(nonUniformScale); { AzToolsFramework::ManipulatorViews views; @@ -137,19 +170,26 @@ namespace PhysX { OnHeightManipulatorMoved(action, idPair); }); - } void ColliderCapsuleMode::OnRadiusManipulatorMoved(const AzToolsFramework::LinearManipulator::Action& action, const AZ::EntityComponentIdPair& idPair) { + // manipulator action offsets do not take entity transform scale into account, so need to apply it here + float transformScale = 1.0f; + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); + AZ::TransformBus::EventResult(transformScale, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldUniformScale); + transformScale = AZ::GetMax(AZ::MinTransformScale, transformScale); + const AZ::Vector3 localPosition = colliderLocalTransform.GetInverse().TransformPoint( + action.m_start.m_localPosition + action.m_current.m_localPositionOffset / transformScale); + // Get the distance the manipulator has moved along the axis. - float extent = action.LocalPosition().Dot(action.m_fixed.m_axis); + float extent = localPosition.Dot(action.m_fixed.m_axis); // Clamp radius to a small value. extent = AZ::GetMax(extent, MinCapsuleRadius); // Update the manipulator and capsule radius. - m_radiusManipulator->SetLocalPosition(extent * action.m_fixed.m_axis); + m_radiusManipulator->SetLocalTransform(colliderLocalTransform * AZ::Transform::CreateTranslation(extent * action.m_fixed.m_axis)); // Adjust the height manipulator so it is always clamped to twice the radius. AdjustHeightManipulator(idPair, static_cast(extent)); @@ -160,14 +200,22 @@ namespace PhysX void ColliderCapsuleMode::OnHeightManipulatorMoved(const AzToolsFramework::LinearManipulator::Action& action, const AZ::EntityComponentIdPair& idPair) { + // manipulator action offsets do not take entity transform scale into account, so need to apply it here + float transformScale = 1.0f; + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); + AZ::TransformBus::EventResult(transformScale, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldUniformScale); + transformScale = AZ::GetMax(AZ::MinTransformScale, transformScale); + const AZ::Vector3 localPosition = colliderLocalTransform.GetInverse().TransformPoint( + action.m_start.m_localPosition + action.m_current.m_localPositionOffset / transformScale); + // Get the distance the manipulator has moved along the axis. - float extent = action.LocalPosition().Dot(action.m_fixed.m_axis); + float extent = localPosition.Dot(action.m_fixed.m_axis); // Ensure capsule's half height is always greater than the radius. extent = AZ::GetMax(extent, MinCapsuleHeight); // Update the manipulator and capsule height. - m_heightManipulator->SetLocalPosition(extent * action.m_fixed.m_axis); + m_heightManipulator->SetLocalTransform(colliderLocalTransform * AZ::Transform::CreateTranslation(extent * action.m_fixed.m_axis)); // The final height of the capsule is twice the manipulator's extent. float capsuleHeight = extent / HalfHeight; @@ -188,7 +236,9 @@ namespace PhysX capsuleRadius = AZ::GetMin(capsuleRadius, capsuleHeight * HalfHeight); // Update manipulator and the capsule radius. - m_radiusManipulator->SetLocalPosition(capsuleRadius * m_radiusManipulator->GetAxis()); + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); + m_radiusManipulator->SetLocalTransform( + colliderLocalTransform * AZ::Transform::CreateTranslation(capsuleRadius * m_radiusManipulator->GetAxis())); PhysX::EditorColliderComponentRequestBus::Event(idPair, &PhysX::EditorColliderComponentRequests::SetCapsuleRadius, capsuleRadius); } @@ -201,7 +251,9 @@ namespace PhysX capsuleHeight = AZ::GetMax(capsuleHeight, capsuleRadius / HalfHeight); // Update the manipulator and capsule height. - m_heightManipulator->SetLocalPosition(capsuleHeight * HalfHeight * m_heightManipulator->GetAxis()); + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); + m_heightManipulator->SetLocalTransform( + colliderLocalTransform * AZ::Transform::CreateTranslation(capsuleHeight * HalfHeight * m_heightManipulator->GetAxis())); PhysX::EditorColliderComponentRequestBus::Event(idPair, &PhysX::EditorColliderComponentRequests::SetCapsuleHeight, capsuleHeight); } } diff --git a/Gems/PhysX/Code/Editor/ColliderCapsuleMode.h b/Gems/PhysX/Code/Editor/ColliderCapsuleMode.h index ceedd84a35..5284b3d1ed 100644 --- a/Gems/PhysX/Code/Editor/ColliderCapsuleMode.h +++ b/Gems/PhysX/Code/Editor/ColliderCapsuleMode.h @@ -34,8 +34,16 @@ namespace PhysX const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; - void SetupRadiusManipulator(const AZ::EntityComponentIdPair& idPair, const AZ::Transform& worldTransform); - void SetupHeightManipulator(const AZ::EntityComponentIdPair& idPair, const AZ::Transform& worldTransform); + void SetupRadiusManipulator( + const AZ::EntityComponentIdPair& idPair, + const AZ::Transform& worldTransform, + const AZ::Transform& localTransform, + const AZ::Vector3& nonUniformScale); + void SetupHeightManipulator( + const AZ::EntityComponentIdPair& idPair, + const AZ::Transform& worldTransform, + const AZ::Transform& localTransform, + const AZ::Vector3& nonUniformScale); void OnRadiusManipulatorMoved(const AzToolsFramework::LinearManipulator::Action& action, const AZ::EntityComponentIdPair& idPair); void OnHeightManipulatorMoved(const AzToolsFramework::LinearManipulator::Action& action, const AZ::EntityComponentIdPair& idPair); void AdjustRadiusManipulator(const AZ::EntityComponentIdPair& idPair, const float capsuleHeight); diff --git a/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp b/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp index 8425f203c1..d292f2dd2a 100644 --- a/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp @@ -112,8 +112,10 @@ namespace PhysX // manipulator offsets do not take transform scale into account, need to handle it here AZ::Transform colliderWorldTransform = AZ::Transform::CreateIdentity(); AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); + const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); const float transformScale = AZ::GetMax(AZ::MinTransformScale, colliderWorldTransform.GetUniformScale()); - const AZ::Vector3 localPosition = action.m_start.m_localPosition + action.m_current.m_localPositionOffset / transformScale; + const AZ::Vector3 localPosition = colliderLocalTransform.GetInverse().TransformPoint( + action.m_start.m_localPosition + action.m_current.m_localPositionOffset / transformScale); // Get the distance the manipulator has moved along the axis. float extent = localPosition.Dot(action.m_fixed.m_axis); From 23788e9297b967fff63107ba9d3ba5017270435d Mon Sep 17 00:00:00 2001 From: greerdv Date: Sat, 5 Feb 2022 12:51:28 +0000 Subject: [PATCH 018/133] fix bug with placement of debug draw for mesh geometry in asset colliders with non-uniform scale Signed-off-by: greerdv --- Gems/PhysX/Code/Source/EditorColliderComponent.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 03e4bdb63e..8da6744dfb 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -968,8 +968,10 @@ namespace PhysX static_cast(shapeConfiguration); const AZ::Vector3 overallScale = Utils::GetTransformScale(GetEntityId()) * m_cachedNonUniformScale * assetScale; + Physics::ColliderConfiguration nonUniformScaledColliderConfiguration = *colliderConfiguration; + nonUniformScaledColliderConfiguration.m_position *= m_cachedNonUniformScale; - m_colliderDebugDraw.DrawMesh(debugDisplay, *colliderConfiguration, *cookedMeshShapeConfiguration, + m_colliderDebugDraw.DrawMesh(debugDisplay, nonUniformScaledColliderConfiguration, *cookedMeshShapeConfiguration, overallScale, static_cast(shapeIndex)); break; } From e66d55189e175864c40c2d1d776c615ffd11c0ed Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Mon, 7 Feb 2022 12:06:11 -0600 Subject: [PATCH 019/133] Updated the gradient signal unit tests for the image gradient now using a StreamingImageAsset Signed-off-by: Chris Galvan --- .../Code/Tests/GradientSignalImageTests.cpp | 5 +- .../Code/Tests/GradientSignalTestFixtures.cpp | 15 +- .../Code/Tests/GradientSignalTestFixtures.h | 3 +- .../Code/Tests/GradientSignalTestHelpers.cpp | 178 ++++++++++++++++++ .../Code/Tests/GradientSignalTestHelpers.h | 64 +++++++ .../Code/Tests/GradientSignalTestMocks.cpp | 74 -------- .../Code/Tests/GradientSignalTestMocks.h | 47 ----- .../gradientsignal_shared_tests_files.cmake | 1 - 8 files changed, 257 insertions(+), 130 deletions(-) delete mode 100644 Gems/GradientSignal/Code/Tests/GradientSignalTestMocks.cpp diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp b/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp index 8ec190000d..c6656d589e 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp +++ b/Gems/GradientSignal/Code/Tests/GradientSignalImageTests.cpp @@ -8,6 +8,7 @@ #include +#include #include #include @@ -88,7 +89,7 @@ namespace UnitTest // Create the Image Gradient Component. GradientSignal::ImageGradientConfig config; - config.m_imageAsset = ImageAssetMockAssetHandler::CreateSpecificPixelImageAsset( + config.m_imageAsset = UnitTest::CreateSpecificPixelImageAsset( test.m_imageSize, test.m_imageSize, static_cast(test.m_pixel.GetX()), static_cast(test.m_pixel.GetY())); config.m_tilingX = test.m_tiling; config.m_tilingY = test.m_tiling; @@ -379,7 +380,7 @@ namespace UnitTest // Create an ImageGradient with a 3x3 asset with the center pixel set. GradientSignal::ImageGradientConfig gradientConfig; - gradientConfig.m_imageAsset = ImageAssetMockAssetHandler::CreateSpecificPixelImageAsset(3, 3, 1, 1); + gradientConfig.m_imageAsset = UnitTest::CreateSpecificPixelImageAsset(3, 3, 1, 1); entity->CreateComponent(gradientConfig); // Create the test GradientTransform diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.cpp b/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.cpp index 402438ee88..d07d2aae50 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.cpp +++ b/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.cpp @@ -8,7 +8,10 @@ #include +#include +#include +#include #include #include #include @@ -70,14 +73,16 @@ namespace UnitTest void GradientSignalBaseFixture::SetupCoreSystems() { - m_mockHandler = new UnitTest::ImageAssetMockAssetHandler(); - AZ::Data::AssetManager::Instance().RegisterHandler(m_mockHandler, azrtti_typeid()); + // Using the AZ::RPI::MakeAssetHandler will both create the asset handlers, + // and register them with the AssetManager + m_assetHandlers.emplace_back(AZ::RPI::MakeAssetHandler()); + m_assetHandlers.emplace_back(AZ::RPI::MakeAssetHandler()); } void GradientSignalBaseFixture::TearDownCoreSystems() { - AZ::Data::AssetManager::Instance().UnregisterHandler(m_mockHandler); - delete m_mockHandler; // delete after removing from the asset manager + // This will delete the asset handlers, which will unregister themselves on deletion + m_assetHandlers.clear(); AzFramework::LegacyAssetEventBus::ClearQueuedEvents(); } @@ -147,7 +152,7 @@ namespace UnitTest GradientSignal::ImageGradientConfig config; const uint32_t imageSize = 4096; const int32_t imageSeed = 12345; - config.m_imageAsset = ImageAssetMockAssetHandler::CreateImageAsset(imageSize, imageSize, imageSeed); + config.m_imageAsset = UnitTest::CreateImageAsset(imageSize, imageSize, imageSeed); config.m_tilingX = 1.0f; config.m_tilingY = 1.0f; entity->CreateComponent(config); diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h b/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h index 5fda88ea27..1c703964e7 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h +++ b/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h @@ -9,6 +9,7 @@ #include #include +#include #include namespace UnitTest @@ -89,7 +90,7 @@ namespace UnitTest AZStd::unique_ptr BuildTestSurfaceMaskGradient(float shapeHalfBounds); AZStd::unique_ptr BuildTestSurfaceSlopeGradient(float shapeHalfBounds); - UnitTest::ImageAssetMockAssetHandler* m_mockHandler = nullptr; + AZ::RPI::AssetHandlerPtrList m_assetHandlers; }; struct GradientSignalTest diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.cpp b/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.cpp index 46cc3475e8..560aa09f48 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.cpp +++ b/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.cpp @@ -8,11 +8,189 @@ #include +#include +#include #include #include namespace UnitTest { + AZ::RHI::ImageSubresourceLayout BuildSubImageLayout(AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize) + { + AZ::RHI::ImageSubresourceLayout layout; + layout.m_size = AZ::RHI::Size{ width, height, 1 }; + layout.m_rowCount = width; + layout.m_bytesPerRow = width * pixelSize; + layout.m_bytesPerImage = width * height * pixelSize; + return layout; + } + + AZStd::vector BuildBasicImageData(AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize, AZ::s32 seed) + { + const size_t imageSize = width * height * pixelSize; + + AZStd::vector image; + image.reserve(imageSize); + + size_t value = 0; + AZStd::hash_combine(value, seed); + + for (AZ::u32 x = 0; x < width; ++x) + { + for (AZ::u32 y = 0; y < height; ++y) + { + AZStd::hash_combine(value, x); + AZStd::hash_combine(value, y); + image.push_back(static_cast(value)); + } + } + + EXPECT_EQ(image.size(), imageSize); + return image; + } + + AZ::Data::Asset BuildBasicMipChainAsset(AZ::u16 mipLevels, AZ::u16 arraySize, AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize, AZ::s32 seed) + { + using namespace AZ; + + RPI::ImageMipChainAssetCreator assetCreator; + + assetCreator.Begin(Data::AssetId(AZ::Uuid::CreateRandom()), mipLevels, arraySize); + + RHI::ImageSubresourceLayout layout = BuildSubImageLayout(width, height, pixelSize); + + assetCreator.BeginMip(layout); + + for (AZ::u32 arrayIndex = 0; arrayIndex < arraySize; ++arrayIndex) + { + AZStd::vector data = BuildBasicImageData(width, height, pixelSize, seed); + assetCreator.AddSubImage(data.data(), data.size()); + } + + assetCreator.EndMip(); + + Data::Asset asset; + EXPECT_TRUE(assetCreator.End(asset)); + EXPECT_TRUE(asset.IsReady()); + EXPECT_NE(asset.Get(), nullptr); + + return asset; + } + + AZStd::vector BuildSpecificPixelImageData(AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize, AZ::u32 pixelX, AZ::u32 pixelY) + { + const size_t imageSize = width * height * pixelSize; + + AZStd::vector image; + image.reserve(imageSize); + + const AZ::u8 pixelValue = 255; + + // Image data should be stored inverted on the y axis relative to our engine, so loop backwards through y. + for (int y = static_cast(height) - 1; y >= 0; --y) + { + for (AZ::u32 x = 0; x < width; ++x) + { + if ((x == static_cast(pixelX)) && (y == static_cast(pixelY))) + { + image.push_back(pixelValue); + } + else + { + image.push_back(0); + } + } + } + + EXPECT_EQ(image.size(), imageSize); + return image; + } + + AZ::Data::Asset BuildSpecificPixelMipChainAsset(AZ::u16 mipLevels, AZ::u16 arraySize, AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize, AZ::u32 pixelX, AZ::u32 pixelY) + { + using namespace AZ; + + RPI::ImageMipChainAssetCreator assetCreator; + + assetCreator.Begin(Data::AssetId(AZ::Uuid::CreateRandom()), mipLevels, arraySize); + + RHI::ImageSubresourceLayout layout = BuildSubImageLayout(width, height, pixelSize); + + assetCreator.BeginMip(layout); + + for (AZ::u32 arrayIndex = 0; arrayIndex < arraySize; ++arrayIndex) + { + AZStd::vector data = BuildSpecificPixelImageData(width, height, pixelSize, pixelX, pixelY); + assetCreator.AddSubImage(data.data(), data.size()); + } + + assetCreator.EndMip(); + + Data::Asset asset; + EXPECT_TRUE(assetCreator.End(asset)); + EXPECT_TRUE(asset.IsReady()); + EXPECT_NE(asset.Get(), nullptr); + + return asset; + } + + AZ::Data::Asset CreateImageAsset(AZ::u32 width, AZ::u32 height, AZ::s32 seed) + { + auto randomAssetId = AZ::Data::AssetId(AZ::Uuid::CreateRandom()); + auto imageAsset = AZ::Data::AssetManager::Instance().CreateAsset( + randomAssetId, AZ::Data::AssetLoadBehavior::Default); + + const AZ::u32 arraySize = 1; + const AZ::u32 mipCountTotal = 1; + const auto format = AZ::RHI::Format::R8_UNORM; + const AZ::u32 pixelSize = AZ::RHI::GetFormatComponentCount(format); + + AZ::Data::Asset mipChain = BuildBasicMipChainAsset(mipCountTotal, arraySize, width, height, pixelSize, seed); + + AZ::RPI::StreamingImageAssetCreator assetCreator; + assetCreator.Begin(randomAssetId); + + AZ::RHI::ImageDescriptor imageDesc = AZ::RHI::ImageDescriptor::Create2DArray(AZ::RHI::ImageBindFlags::ShaderRead, width, height, arraySize, format); + imageDesc.m_mipLevels = static_cast(mipCountTotal); + + assetCreator.SetImageDescriptor(imageDesc); + assetCreator.AddMipChainAsset(*mipChain.Get()); + + EXPECT_TRUE(assetCreator.End(imageAsset)); + EXPECT_TRUE(imageAsset.IsReady()); + EXPECT_NE(imageAsset.Get(), nullptr); + + return imageAsset; + } + + AZ::Data::Asset CreateSpecificPixelImageAsset(AZ::u32 width, AZ::u32 height, AZ::u32 pixelX, AZ::u32 pixelY) + { + auto randomAssetId = AZ::Data::AssetId(AZ::Uuid::CreateRandom()); + auto imageAsset = AZ::Data::AssetManager::Instance().CreateAsset( + randomAssetId, AZ::Data::AssetLoadBehavior::Default); + + const AZ::u32 arraySize = 1; + const AZ::u32 mipCountTotal = 1; + const auto format = AZ::RHI::Format::R8_UNORM; + const AZ::u32 pixelSize = AZ::RHI::GetFormatComponentCount(format); + + AZ::Data::Asset mipChain = BuildSpecificPixelMipChainAsset(mipCountTotal, arraySize, width, height, pixelSize, pixelX, pixelY); + + AZ::RPI::StreamingImageAssetCreator assetCreator; + assetCreator.Begin(randomAssetId); + + AZ::RHI::ImageDescriptor imageDesc = AZ::RHI::ImageDescriptor::Create2DArray(AZ::RHI::ImageBindFlags::ShaderRead, width, height, arraySize, format); + imageDesc.m_mipLevels = static_cast(mipCountTotal); + + assetCreator.SetImageDescriptor(imageDesc); + assetCreator.AddMipChainAsset(*mipChain.Get()); + + EXPECT_TRUE(assetCreator.End(imageAsset)); + EXPECT_TRUE(imageAsset.IsReady()); + EXPECT_NE(imageAsset.Get(), nullptr); + return imageAsset; + } + void GradientSignalTestHelpers::CompareGetValueAndGetValues(AZ::EntityId gradientEntityId, float shapeHalfBounds) { // Create a gradient sampler and run through a series of points to see if they match expectations. diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.h b/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.h index 8a175939ee..5a13167975 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.h +++ b/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.h @@ -12,8 +12,72 @@ #include #include +#include +#include +#include + namespace UnitTest { + //! Helper method to build a AZ::RHI::ImageSubresourceLayout + //! @param width The width of the image + //! @param height The height of the image + //! @param pixelSize Number of bytes per pixel + //! @return The AZ::RHI::ImageSubresourceLayout that has been filled out appropriately + AZ::RHI::ImageSubresourceLayout BuildSubImageLayout(AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize); + + //! Build a deterministic random set of image pixel data + //! @param width Width of the image + //! @param height Height of the image + //! @param pixelSize Number of bytes per pixel + //! @param seed The random seed for generating the data + //! @return A vector of bytes for the image data + AZStd::vector BuildBasicImageData(AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize, AZ::s32 seed); + + //! Build a mip chain asset that contains the basic image data from BuildBasicImageData + //! @param mipLevels Number of mip levels in the chain + //! @param arraySize Number of sub images within a mip level + //! @param width The width of the image + //! @param height The height of the image + //! @param pixelSize The number of bytes per pixel + //! @param seed The random seed for generating the data + //! @return A mip chain asset with the specified basic image data + AZ::Data::Asset BuildBasicMipChainAsset(AZ::u16 mipLevels, AZ::u16 arraySize, AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize, AZ::s32 seed); + + //! Construct an array of image data where all the pixels are 0 except for one at the given coordinate + //! @param width Width of the image + //! @param height Height of the image + //! @param pixelSize Number of bytes per pixel + //! @param pixelX The X coordinate of the pixel to set to 1 + //! @param pixelY The Y coordinate of the pixel to set to 1 + //! @return A vector of bytes for the image data + AZStd::vector BuildSpecificPixelImageData(AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize, AZ::u32 pixelX, AZ::u32 pixelY); + + //! Build a mip chain asset that contains the specific image data from BuildSpecificPixelImageData + //! @param mipLevels Number of mip levels in the chain + //! @param arraySize Number of sub images within a mip level + //! @param width The width of the image + //! @param height The height of the image + //! @param pixelSize The number of bytes per pixel + //! @param pixelX The X coordinate of the pixel to set to 1 + //! @param pixelY The Y coordinate of the pixel to set to 1 + //! @return A mip chain asset with the specific pixel image data + AZ::Data::Asset BuildSpecificPixelMipChainAsset(AZ::u16 mipLevels, AZ::u16 arraySize, AZ::u32 width, AZ::u32 height, AZ::u32 pixelSize, AZ::u32 pixelX, AZ::u32 pixelY); + + //! Creates a deterministically random set of pixel data as an AZ::RPI::StreamingImageAsset. + //! \param width The width of the AZ::RPI::StreamingImageAsset + //! \param height The height of the AZ::RPI::StreamingImageAsset + //! \param seed The random seed to use for generating the random data + //! \return The AZ::RPI::StreamingImageAsset in a loaded ready state + AZ::Data::Asset CreateImageAsset(AZ::u32 width, AZ::u32 height, AZ::s32 seed); + + //! Creates an AZ::RPI::StreamingImageAsset where all the pixels are 0 except for the one pixel at the given coordinates, which is set to 1. + //! \param width The width of the AZ::RPI::StreamingImageAsset + //! \param height The height of the AZ::RPI::StreamingImageAsset + //! \param pixelX The X coordinate of the pixel to set to 1 + //! \param pixelY The Y coordinate of the pixel to set to 1 + //! \return The AZ::RPI::StreamingImageAsset in a loaded ready state + AZ::Data::Asset CreateSpecificPixelImageAsset(AZ::u32 width, AZ::u32 height, AZ::u32 pixelX, AZ::u32 pixelY); + class GradientSignalTestHelpers { public: diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalTestMocks.cpp b/Gems/GradientSignal/Code/Tests/GradientSignalTestMocks.cpp deleted file mode 100644 index 7ac6ef1ecc..0000000000 --- a/Gems/GradientSignal/Code/Tests/GradientSignalTestMocks.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include - -namespace UnitTest -{ - AZ::Data::Asset ImageAssetMockAssetHandler::CreateImageAsset(AZ::u32 width, AZ::u32 height, AZ::s32 seed) - { - auto imageAsset = AZ::Data::AssetManager::Instance().CreateAsset( - AZ::Data::AssetId(AZ::Uuid::CreateRandom()), AZ::Data::AssetLoadBehavior::Default); - - imageAsset->m_imageWidth = width; - imageAsset->m_imageHeight = height; - imageAsset->m_bytesPerPixel = 1; - imageAsset->m_imageFormat = ImageProcessingAtom::EPixelFormat::ePixelFormat_R8; - imageAsset->m_imageData.reserve(width * height); - - size_t value = 0; - AZStd::hash_combine(value, seed); - - for (AZ::u32 x = 0; x < width; ++x) - { - for (AZ::u32 y = 0; y < height; ++y) - { - AZStd::hash_combine(value, x); - AZStd::hash_combine(value, y); - imageAsset->m_imageData.push_back(static_cast(value)); - } - } - - return imageAsset; - } - - AZ::Data::Asset ImageAssetMockAssetHandler::CreateSpecificPixelImageAsset( - AZ::u32 width, AZ::u32 height, AZ::u32 pixelX, AZ::u32 pixelY) - { - auto imageAsset = AZ::Data::AssetManager::Instance().CreateAsset( - AZ::Data::AssetId(AZ::Uuid::CreateRandom()), AZ::Data::AssetLoadBehavior::Default); - - imageAsset->m_imageWidth = width; - imageAsset->m_imageHeight = height; - imageAsset->m_bytesPerPixel = 1; - imageAsset->m_imageFormat = ImageProcessingAtom::EPixelFormat::ePixelFormat_R8; - imageAsset->m_imageData.reserve(width * height); - - const AZ::u8 pixelValue = 255; - - // Image data should be stored inverted on the y axis relative to our engine, so loop backwards through y. - for (int y = static_cast(height) - 1; y >= 0; --y) - { - for (AZ::u32 x = 0; x < width; ++x) - { - if ((x == static_cast(pixelX)) && (y == static_cast(pixelY))) - { - imageAsset->m_imageData.push_back(pixelValue); - } - else - { - imageAsset->m_imageData.push_back(0); - } - } - } - - return imageAsset; - } -} - diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalTestMocks.h b/Gems/GradientSignal/Code/Tests/GradientSignalTestMocks.h index 30f262d9b4..997e88ce17 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalTestMocks.h +++ b/Gems/GradientSignal/Code/Tests/GradientSignalTestMocks.h @@ -27,53 +27,6 @@ namespace UnitTest { - // Mock asset handler for GradientSignal::ImageAsset that we can use in unit tests to pretend to load an image asset with. - // Also includes utility functions for creating image assets with specific testable patterns. - struct ImageAssetMockAssetHandler : public AZ::Data::AssetHandler - { - //! Creates a deterministically random set of pixel data as an ImageAsset. - //! \param width The width of the ImageAsset - //! \param height The height of the ImageAsset - //! \param seed The random seed to use for generating the random data - //! \return The ImageAsset in a loaded ready state - static AZ::Data::Asset CreateImageAsset(AZ::u32 width, AZ::u32 height, AZ::s32 seed); - - //! Creates an ImageAsset where all the pixels are 0 except for the one pixel at the given coordinates, which is set to 1. - //! \param width The width of the ImageAsset - //! \param height The height of the ImageAsset - //! \param pixelX The X coordinate of the pixel to set to 1 - //! \param pixelY The Y coordinate of the pixel to set to 1 - //! \return The ImageAsset in a loaded ready state - static AZ::Data::Asset CreateSpecificPixelImageAsset( - AZ::u32 width, AZ::u32 height, AZ::u32 pixelX, AZ::u32 pixelY); - - AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, [[maybe_unused]] const AZ::Data::AssetType& type) override - { - // For our mock handler, always mark our assets as immediately ready. - return aznew GradientSignal::ImageAsset(id, AZ::Data::AssetData::AssetStatus::Ready); - } - - void DestroyAsset(AZ::Data::AssetPtr ptr) override - { - if (ptr) - { - delete ptr; - } - } - - void GetHandledAssetTypes([[maybe_unused]] AZStd::vector& assetTypes) override - { - } - - AZ::Data::AssetHandler::LoadResult LoadAssetData( - [[maybe_unused]] const AZ::Data::Asset& asset, - [[maybe_unused]] AZStd::shared_ptr stream, - [[maybe_unused]] const AZ::Data::AssetFilterCB& assetLoadFilterCB) override - { - return AZ::Data::AssetHandler::LoadResult::LoadComplete; - } - }; - struct MockGradientRequestsBus : public GradientSignal::GradientRequestBus::Handler { diff --git a/Gems/GradientSignal/Code/gradientsignal_shared_tests_files.cmake b/Gems/GradientSignal/Code/gradientsignal_shared_tests_files.cmake index 98ab57b7b0..5e11406bae 100644 --- a/Gems/GradientSignal/Code/gradientsignal_shared_tests_files.cmake +++ b/Gems/GradientSignal/Code/gradientsignal_shared_tests_files.cmake @@ -11,6 +11,5 @@ set(FILES Tests/GradientSignalTestHelpers.h Tests/GradientSignalTestFixtures.cpp Tests/GradientSignalTestFixtures.h - Tests/GradientSignalTestMocks.cpp Tests/GradientSignalTestMocks.h ) From fc01207d147fcc9dfc3645b5483fde43556df8f3 Mon Sep 17 00:00:00 2001 From: greerdv Date: Mon, 7 Feb 2022 18:47:10 +0000 Subject: [PATCH 020/133] add test for box component scale manipulators Signed-off-by: greerdv --- .../Tests/EditorBoxShapeComponentTests.cpp | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) diff --git a/Gems/LmbrCentral/Code/Tests/EditorBoxShapeComponentTests.cpp b/Gems/LmbrCentral/Code/Tests/EditorBoxShapeComponentTests.cpp index 4b72a4fb58..713799640b 100644 --- a/Gems/LmbrCentral/Code/Tests/EditorBoxShapeComponentTests.cpp +++ b/Gems/LmbrCentral/Code/Tests/EditorBoxShapeComponentTests.cpp @@ -7,6 +7,17 @@ */ #include "LmbrCentralReflectionTest.h" #include "Shape/EditorBoxShapeComponent.h" +#include "Shape/EditorSphereShapeComponent.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include namespace LmbrCentral { @@ -56,5 +67,111 @@ namespace LmbrCentral EXPECT_EQ(dimensions, AZ::Vector3(0.37f, 0.57f, 0.66f)); } + + class EditorBoxShapeComponentFixture : public UnitTest::ToolsApplicationFixture + { + public: + void SetUpEditorFixtureImpl() override; + void TearDownEditorFixtureImpl() override; + + AZStd::unique_ptr m_editorBoxShapeComponentDescriptor; + AZStd::unique_ptr m_editorSphereShapeComponentDescriptor; + + AZ::Entity* m_entity = nullptr; + }; + + void EditorBoxShapeComponentFixture::SetUpEditorFixtureImpl() + { + AZ::SerializeContext* serializeContext = nullptr; + AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); + + // need to reflect EditorSphereShapeComponent in order for EditorBaseShapeComponent to be reflected + m_editorSphereShapeComponentDescriptor = AZStd::unique_ptr(EditorSphereShapeComponent::CreateDescriptor()); + + m_editorBoxShapeComponentDescriptor = + AZStd::unique_ptr(EditorBoxShapeComponent::CreateDescriptor()); + + ShapeComponentConfig::Reflect(serializeContext); + BoxShape::Reflect(serializeContext); + m_editorSphereShapeComponentDescriptor->Reflect(serializeContext); + m_editorBoxShapeComponentDescriptor->Reflect(serializeContext); + + UnitTest::CreateDefaultEditorEntity("BoxShapeComponentEntity", &m_entity); + m_entity->Deactivate(); + m_entity->CreateComponent(AzToolsFramework::Components::EditorNonUniformScaleComponent::RTTI_Type()); + m_entity->CreateComponent(EditorBoxShapeComponentTypeId); + m_entity->Activate(); + } + + void EditorBoxShapeComponentFixture::TearDownEditorFixtureImpl() + { + AzToolsFramework::EditorEntityContextRequestBus::Broadcast( + &AzToolsFramework::EditorEntityContextRequestBus::Events::DestroyEditorEntity, m_entity->GetId()); + m_entity = nullptr; + + m_editorBoxShapeComponentDescriptor.reset(); + m_editorSphereShapeComponentDescriptor.reset(); + } + + using EditorBoxShapeComponentManipulatorFixture = + UnitTest::IndirectCallManipulatorViewportInteractionFixtureMixin; + + TEST_F(EditorBoxShapeComponentManipulatorFixture, BoxShapeNonUniformScaleManipulatorsScaleCorrectly) + { + // a rotation which should map (1, 0, 0) to (0.8, 0.6, 0) + const AZ::Quaternion boxRotation(0.0f, 0.0f, 0.316228f, 0.948683f); + AZ::Transform boxTransform = AZ::Transform::CreateFromQuaternionAndTranslation(boxRotation, AZ::Vector3(2.0f, 3.0f, 4.0f)); + boxTransform.SetUniformScale(1.5f); + AZ::TransformBus::Event(m_entity->GetId(), &AZ::TransformBus::Events::SetWorldTM, boxTransform); + + const AZ::Vector3 nonUniformScale(4.0f, 1.5f, 2.0f); + AZ::NonUniformScaleRequestBus::Event(m_entity->GetId(), &AZ::NonUniformScaleRequests::SetScale, nonUniformScale); + + const AZ::Vector3 boxDimensions(1.0f, 2.0f, 2.5f); + BoxShapeComponentRequestsBus::Event(m_entity->GetId(), &BoxShapeComponentRequests::SetBoxDimensions, boxDimensions); + + // enter the box shape component's component mode + AzToolsFramework::SelectEntity(m_entity->GetId()); + + AzToolsFramework::ComponentModeFramework::ComponentModeSystemRequestBus::Broadcast( + &AzToolsFramework::ComponentModeFramework::ComponentModeSystemRequestBus::Events::AddSelectedComponentModesOfType, + EditorBoxShapeComponentTypeId); + + // position the camera so it is looking down at the box + AzFramework::SetCameraTransform( + m_cameraState, + AZ::Transform::CreateFromQuaternionAndTranslation( + AZ::Quaternion::CreateRotationX(-AZ::Constants::HalfPi), AZ::Vector3(2.0f, 3.0f, 20.0f))); + + // position in world space which should allow grabbing the box's x scale manipulator + // the unscaled position of the x scale manipulator in the box's local frame should be (0.5f, 0.0f, 0.0f) + // after non-uniform scale, the manipulator position should be (2.0f, 0.0f, 0.0f) + // after the scale of the entity transform, the manipulator position should be (3.0f, 0.0f, 0.0f) + // after the rotation of the entity transform, the manipulator position should be (2.4f, 1.8f, 0.0f) + // after the translation of the entity transform, the manipulator position should be (4.4f, 4.8f, 4.0f) + const AZ::Vector3 worldStart(4.4f, 4.8f, 4.0f); + + // position in world space to move to + const AZ::Vector3 worldEnd(6.8f, 6.6f, 4.0f); + + const auto screenStart = AzFramework::WorldToScreen(worldStart, m_cameraState); + const auto screenEnd = AzFramework::WorldToScreen(worldEnd, m_cameraState); + + m_actionDispatcher + ->CameraState(m_cameraState) + // move the mouse to the position of the x scale manipulator + ->MousePosition(screenStart) + // drag to move the manipulator + ->MouseLButtonDown() + ->MousePosition(screenEnd) + ->MouseLButtonUp(); + + AZ::Vector3 newBoxDimensions = AZ::Vector3::CreateZero(); + BoxShapeComponentRequestsBus::EventResult(newBoxDimensions, m_entity->GetId(), &BoxShapeComponentRequests::GetBoxDimensions); + + const AZ::Vector3 expectedBoxDimensions(2.0f, 2.0f, 2.5f); + // allow a reasonably high tolerance because we can't get better accuracy than the resolution of the viewport + EXPECT_THAT(newBoxDimensions, UnitTest::IsCloseTolerance(expectedBoxDimensions, 1e-2f)); + } } From 701b7a55e6e308b15c4ec258efc21d774e666d4b Mon Sep 17 00:00:00 2001 From: Sergey Pereslavtsev Date: Tue, 8 Feb 2022 12:43:40 +0000 Subject: [PATCH 021/133] PR feedback addressing Signed-off-by: Sergey Pereslavtsev --- .../TerrainPhysicsColliderComponent.cpp | 61 ------------------ .../TerrainPhysicsColliderComponent.h | 10 +-- .../TerrainSurfaceGradientListComponent.cpp | 62 ------------------- .../TerrainSurfaceGradientListComponent.h | 6 +- .../EditorTerrainPhysicsColliderComponent.cpp | 54 ++++++++++++++-- .../EditorTerrainPhysicsColliderComponent.h | 8 +-- ...torTerrainSurfaceGradientListComponent.cpp | 53 ++++++++++++++-- ...ditorTerrainSurfaceGradientListComponent.h | 8 +-- .../EditorSelectableTagListProvider.cpp | 31 ---------- .../Source/EditorSelectableTagListProvider.h | 26 -------- .../Source/EditorSurfaceTagListProvider.cpp | 43 +++++++++++++ .../Source/EditorSurfaceTagListProvider.h | 29 +++++++++ .../Code/terrain_editor_shared_files.cmake | 4 +- 13 files changed, 190 insertions(+), 205 deletions(-) delete mode 100644 Gems/Terrain/Code/Source/EditorSelectableTagListProvider.cpp delete mode 100644 Gems/Terrain/Code/Source/EditorSelectableTagListProvider.h create mode 100644 Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp create mode 100644 Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.h diff --git a/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.cpp index ecc91d06ff..a0689ec23a 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.cpp @@ -17,13 +17,11 @@ #include #include #include -#include #include #include #include -#include namespace Terrain { @@ -35,52 +33,9 @@ namespace Terrain ->Version(1) ->Field("Surface", &TerrainPhysicsSurfaceMaterialMapping::m_surfaceTag) ->Field("Material", &TerrainPhysicsSurfaceMaterialMapping::m_materialId); - - if (auto edit = serialize->GetEditContext()) - { - edit->Class( - "Terrain Surface Material Mapping", "Mapping between a surface and a physics material.") - - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) - - ->DataElement( - AZ::Edit::UIHandlers::ComboBox, &TerrainPhysicsSurfaceMaterialMapping::m_surfaceTag, "Surface Tag", - "Surface type to map to a physics material.") - ->Attribute(AZ::Edit::Attributes::EnumValues, &TerrainPhysicsSurfaceMaterialMapping::BuildSelectableTagList) - - ->DataElement(AZ::Edit::UIHandlers::Default, &TerrainPhysicsSurfaceMaterialMapping::m_materialId, "Material ID", "") - ->ElementAttribute(Physics::Attributes::MaterialLibraryAssetId, &TerrainPhysicsSurfaceMaterialMapping::GetMaterialLibraryId) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::ShowProductAssetFileName, true); - } } } - AZStd::vector> TerrainPhysicsSurfaceMaterialMapping::BuildSelectableTagList() const - { - AZ_PROFILE_FUNCTION(Entity); - - if (m_tagListProvider) - { - AZStd::vector> selectableTags = AZStd::move(m_tagListProvider->BuildSelectableTagList()); - - // Insert the tag currently in use by this mapping - selectableTags.push_back({ m_surfaceTag, m_surfaceTag.GetDisplayName() }); - - // Sorting for consistency - AZStd::sort(selectableTags.begin(), selectableTags.end(), [](const auto& lhs, const auto& rhs) {return lhs.second < rhs.second; }); - return selectableTags; - } - - return SurfaceData::SurfaceTag::GetRegisteredTags(); - } - - void TerrainPhysicsSurfaceMaterialMapping::SetTagListProvider(const EditorSelectableTagListProvider* tagListProvider) - { - m_tagListProvider = tagListProvider; - } AZ::Data::AssetId TerrainPhysicsSurfaceMaterialMapping::GetMaterialLibraryId() { @@ -105,22 +60,6 @@ namespace Terrain ->Field("DefaultMaterial", &TerrainPhysicsColliderConfig::m_defaultMaterialSelection) ->Field("Mappings", &TerrainPhysicsColliderConfig::m_surfaceMaterialMappings) ; - - if (auto edit = serialize->GetEditContext()) - { - edit->Class( - "Terrain Physics Collider Component", - "Provides terrain data to a physics collider with configurable surface mappings.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &TerrainPhysicsColliderConfig::m_defaultMaterialSelection, - "Default Surface Physics Material", "Select a material to be used by unmapped surfaces by default") - ->DataElement( - AZ::Edit::UIHandlers::Default, &TerrainPhysicsColliderConfig::m_surfaceMaterialMappings, - "Surface to Material Mappings", "Maps surfaces to physics materials") - ; - } } } diff --git a/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.h b/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.h index 97b5e49fca..2bd0e95769 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.h +++ b/Gems/Terrain/Code/Source/Components/TerrainPhysicsColliderComponent.h @@ -25,7 +25,7 @@ namespace LmbrCentral namespace Terrain { - class EditorSelectableTagListProvider; + class EditorSurfaceTagListProvider; static const uint8_t InvalidSurfaceTagIndex = 0xFF; @@ -35,15 +35,16 @@ namespace Terrain AZ_CLASS_ALLOCATOR(TerrainPhysicsSurfaceMaterialMapping, AZ::SystemAllocator, 0); AZ_RTTI(TerrainPhysicsSurfaceMaterialMapping, "{A88B5289-DFCD-4564-8395-E2177DFE5B18}"); static void Reflect(AZ::ReflectContext* context); + static AZ::Data::AssetId GetMaterialLibraryId(); + AZStd::vector> BuildSelectableTagList() const; - void SetTagListProvider(const EditorSelectableTagListProvider* tagListProvider); + void SetTagListProvider(const EditorSurfaceTagListProvider* tagListProvider); SurfaceData::SurfaceTag m_surfaceTag; Physics::MaterialId m_materialId; private: - static AZ::Data::AssetId GetMaterialLibraryId(); - const EditorSelectableTagListProvider* m_tagListProvider = nullptr; + const EditorSurfaceTagListProvider* m_tagListProvider = nullptr; }; class TerrainPhysicsColliderConfig @@ -53,6 +54,7 @@ namespace Terrain AZ_CLASS_ALLOCATOR(TerrainPhysicsColliderConfig, AZ::SystemAllocator, 0); AZ_RTTI(TerrainPhysicsColliderConfig, "{E9EADB8F-C3A5-4B9C-A62D-2DBC86B4CE59}", AZ::ComponentConfig); static void Reflect(AZ::ReflectContext* context); + Physics::MaterialSelection m_defaultMaterialSelection; AZStd::vector m_surfaceMaterialMappings; }; diff --git a/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.cpp index 64b5d36a8f..a93bda1872 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.cpp @@ -11,11 +11,9 @@ #include #include #include -#include #include #include -#include namespace Terrain { @@ -28,27 +26,6 @@ namespace Terrain ->Field("Gradient Entity", &TerrainSurfaceGradientMapping::m_gradientEntityId) ->Field("Surface Tag", &TerrainSurfaceGradientMapping::m_surfaceTag) ; - - if (auto edit = serialize->GetEditContext()) - { - edit->Class("Terrain Surface Gradient Mapping", "Mapping between a gradient and a surface.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - - ->DataElement( - AZ::Edit::UIHandlers::Default, &TerrainSurfaceGradientMapping::m_gradientEntityId, - "Gradient Entity", "ID of Entity providing a gradient.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) - ->UIElement("GradientPreviewer", "Previewer") - ->Attribute(AZ::Edit::Attributes::NameLabelOverride, "") - ->Attribute(AZ_CRC_CE("GradientEntity"), &TerrainSurfaceGradientMapping::m_gradientEntityId) - ->DataElement( - AZ::Edit::UIHandlers::Default, &TerrainSurfaceGradientMapping::m_surfaceTag, "Surface Tag", - "Surface type to map to this gradient.") - ->Attribute(AZ::Edit::Attributes::EnumValues, &TerrainSurfaceGradientMapping::BuildSelectableTagList) - ; - } } if (auto behaviorContext = azrtti_cast(context)) @@ -63,30 +40,6 @@ namespace Terrain } } - AZStd::vector> TerrainSurfaceGradientMapping::BuildSelectableTagList() const - { - AZ_PROFILE_FUNCTION(Entity); - - if (m_tagListProvider) - { - AZStd::vector> selectableTags = AZStd::move(m_tagListProvider->BuildSelectableTagList()); - - // Insert the tag currently in use by this mapping - selectableTags.push_back({ m_surfaceTag, m_surfaceTag.GetDisplayName() }); - - // Sorting for consistency - AZStd::sort(selectableTags.begin(), selectableTags.end(), [](const auto& lhs, const auto& rhs) {return lhs.second < rhs.second; }); - return selectableTags; - } - - return SurfaceData::SurfaceTag::GetRegisteredTags(); - } - - void TerrainSurfaceGradientMapping::SetTagListProvider(const EditorSelectableTagListProvider* tagListProvider) - { - m_tagListProvider = tagListProvider; - } - void TerrainSurfaceGradientListConfig::Reflect(AZ::ReflectContext* context) { TerrainSurfaceGradientMapping::Reflect(context); @@ -98,21 +51,6 @@ namespace Terrain ->Version(1) ->Field("Mappings", &TerrainSurfaceGradientListConfig::m_gradientSurfaceMappings) ; - - AZ::EditContext* edit = serialize->GetEditContext(); - if (edit) - { - edit->Class( - "Terrain Surface Gradient List Component", "Provide mapping between gradients and surfaces.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - - ->DataElement( - AZ::Edit::UIHandlers::Default, &TerrainSurfaceGradientListConfig::m_gradientSurfaceMappings, - "Gradient to Surface Mappings", "Maps Gradient Entities to Surfaces.") - ; - } } } diff --git a/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.h b/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.h index b2f41fae88..fd6c16d30d 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.h +++ b/Gems/Terrain/Code/Source/Components/TerrainSurfaceGradientListComponent.h @@ -25,7 +25,7 @@ namespace LmbrCentral namespace Terrain { - class EditorSelectableTagListProvider; + class EditorSurfaceTagListProvider; class TerrainSurfaceGradientMapping final { @@ -42,13 +42,13 @@ namespace Terrain } AZStd::vector> BuildSelectableTagList() const; - void SetTagListProvider(const EditorSelectableTagListProvider* tagListProvider); + void SetTagListProvider(const EditorSurfaceTagListProvider* tagListProvider); AZ::EntityId m_gradientEntityId; SurfaceData::SurfaceTag m_surfaceTag; private: - const EditorSelectableTagListProvider* m_tagListProvider = nullptr; + const EditorSurfaceTagListProvider* m_tagListProvider = nullptr; }; class TerrainSurfaceGradientListConfig : public AZ::ComponentConfig diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.cpp b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.cpp index 09f99fd7fe..5f76b7de6a 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.cpp +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.cpp @@ -20,6 +20,43 @@ namespace Terrain &LmbrCentral::EditorWrappedComponentBaseVersionConverter ); + + if (auto serialize = azrtti_cast(context)) + { + if (auto edit = serialize->GetEditContext()) + { + edit->Class( + "Terrain Surface Material Mapping", "Mapping between a surface and a physics material.") + + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) + + ->DataElement( + AZ::Edit::UIHandlers::ComboBox, &TerrainPhysicsSurfaceMaterialMapping::m_surfaceTag, "Surface Tag", + "Surface type to map to a physics material.") + ->Attribute(AZ::Edit::Attributes::EnumValues, &TerrainPhysicsSurfaceMaterialMapping::BuildSelectableTagList) + + ->DataElement(AZ::Edit::UIHandlers::Default, &TerrainPhysicsSurfaceMaterialMapping::m_materialId, "Material ID", "") + ->ElementAttribute(Physics::Attributes::MaterialLibraryAssetId, &TerrainPhysicsSurfaceMaterialMapping::GetMaterialLibraryId) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::ShowProductAssetFileName, true) + ; + + edit->Class( + "Terrain Physics Collider Component", + "Provides terrain data to a physics collider with configurable surface mappings.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &TerrainPhysicsColliderConfig::m_defaultMaterialSelection, + "Default Surface Physics Material", "Select a material to be used by unmapped surfaces by default") + ->DataElement( + AZ::Edit::UIHandlers::Default, &TerrainPhysicsColliderConfig::m_surfaceMaterialMappings, + "Surface to Material Mappings", "Maps surfaces to physics materials") + ; + } + } } void EditorTerrainPhysicsColliderComponent::Activate() @@ -28,14 +65,13 @@ namespace Terrain BaseClassType::Activate(); } - AZStd::unordered_set EditorTerrainPhysicsColliderComponent::GetSurfaceTagsInUse() const + AZStd::unordered_set EditorTerrainPhysicsColliderComponent::GetSurfaceTagsInUse() const { - AZStd::unordered_set tagsInUse; + AZStd::unordered_set tagsInUse; for (const TerrainPhysicsSurfaceMaterialMapping& mapping : m_configuration.m_surfaceMaterialMappings) { - AZ::u32 crc = mapping.m_surfaceTag; - tagsInUse.insert(crc); + tagsInUse.insert(mapping.m_surfaceTag); } return AZStd::move(tagsInUse); @@ -55,4 +91,14 @@ namespace Terrain } } + AZStd::vector> TerrainPhysicsSurfaceMaterialMapping::BuildSelectableTagList() const + { + AZ_PROFILE_FUNCTION(Entity); + return AZStd::move(Terrain::BuildSelectableTagList(m_tagListProvider, m_surfaceTag)); + } + + void TerrainPhysicsSurfaceMaterialMapping::SetTagListProvider(const EditorSurfaceTagListProvider* tagListProvider) + { + m_tagListProvider = tagListProvider; + } } diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h index fb724507d6..fca8e52246 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainPhysicsColliderComponent.h @@ -11,13 +11,13 @@ #include #include #include -#include +#include namespace Terrain { class EditorTerrainPhysicsColliderComponent : public LmbrCentral::EditorWrappedComponentBase - , public EditorSelectableTagListProvider + , public EditorSurfaceTagListProvider { public: using BaseClassType = LmbrCentral::EditorWrappedComponentBase; @@ -35,8 +35,8 @@ namespace Terrain static constexpr auto s_helpUrl = ""; private: - // EditorSelectableTagListProvider interface implementation - AZStd::unordered_set GetSurfaceTagsInUse() const override; + // EditorSurfaceTagListProvider interface implementation + AZStd::unordered_set GetSurfaceTagsInUse() const override; AZ::u32 ConfigurationChanged() override; void UpdateConfigurationTagProvider(); diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.cpp b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.cpp index 50d45d6cf0..0ea51f282b 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.cpp +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.cpp @@ -19,6 +19,41 @@ namespace Terrain &LmbrCentral::EditorWrappedComponentBaseVersionConverter ); + + if (auto serialize = azrtti_cast(context)) + { + if (auto edit = serialize->GetEditContext()) + { + edit->Class("Terrain Surface Gradient Mapping", "Mapping between a gradient and a surface.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + + ->DataElement( + AZ::Edit::UIHandlers::Default, &TerrainSurfaceGradientMapping::m_gradientEntityId, + "Gradient Entity", "ID of Entity providing a gradient.") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, AZ::Edit::PropertyRefreshLevels::AttributesAndValues) + ->UIElement("GradientPreviewer", "Previewer") + ->Attribute(AZ::Edit::Attributes::NameLabelOverride, "") + ->Attribute(AZ_CRC_CE("GradientEntity"), &TerrainSurfaceGradientMapping::m_gradientEntityId) + ->DataElement( + AZ::Edit::UIHandlers::Default, &TerrainSurfaceGradientMapping::m_surfaceTag, "Surface Tag", + "Surface type to map to this gradient.") + ->Attribute(AZ::Edit::Attributes::EnumValues, &TerrainSurfaceGradientMapping::BuildSelectableTagList) + ; + + edit->Class( + "Terrain Surface Gradient List Component", "Provide mapping between gradients and surfaces.") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + + ->DataElement( + AZ::Edit::UIHandlers::Default, &TerrainSurfaceGradientListConfig::m_gradientSurfaceMappings, + "Gradient to Surface Mappings", "Maps Gradient Entities to Surfaces.") + ; + } + } } void EditorTerrainSurfaceGradientListComponent::Activate() @@ -41,16 +76,26 @@ namespace Terrain } } - AZStd::unordered_set EditorTerrainSurfaceGradientListComponent::GetSurfaceTagsInUse() const + AZStd::unordered_set EditorTerrainSurfaceGradientListComponent::GetSurfaceTagsInUse() const { - AZStd::unordered_set tagsInUse; + AZStd::unordered_set tagsInUse; for (const TerrainSurfaceGradientMapping& mapping : m_configuration.m_gradientSurfaceMappings) { - AZ::u32 crc = mapping.m_surfaceTag; - tagsInUse.insert(crc); + tagsInUse.insert(mapping.m_surfaceTag); } return AZStd::move(tagsInUse); } + + AZStd::vector> TerrainSurfaceGradientMapping::BuildSelectableTagList() const + { + AZ_PROFILE_FUNCTION(Entity); + return AZStd::move(Terrain::BuildSelectableTagList(m_tagListProvider, m_surfaceTag)); + } + + void TerrainSurfaceGradientMapping::SetTagListProvider(const EditorSurfaceTagListProvider* tagListProvider) + { + m_tagListProvider = tagListProvider; + } } diff --git a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h index 37fafdc0a9..bcd5d84c38 100644 --- a/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h +++ b/Gems/Terrain/Code/Source/EditorComponents/EditorTerrainSurfaceGradientListComponent.h @@ -11,13 +11,13 @@ #include #include #include -#include +#include namespace Terrain { class EditorTerrainSurfaceGradientListComponent : public LmbrCentral::EditorWrappedComponentBase - , public EditorSelectableTagListProvider + , public EditorSurfaceTagListProvider { public: using BaseClassType = LmbrCentral::EditorWrappedComponentBase; @@ -35,8 +35,8 @@ namespace Terrain static constexpr const char* const s_helpUrl = "https://o3de.org/docs/user-guide/components/reference/terrain/surface-gradient-list/"; private: - // EditorSelectableTagListProvider interface implementation - AZStd::unordered_set GetSurfaceTagsInUse() const override; + // EditorSurfaceTagListProvider interface implementation + AZStd::unordered_set GetSurfaceTagsInUse() const override; AZ::u32 ConfigurationChanged() override; void UpdateConfigurationTagProvider(); diff --git a/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.cpp b/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.cpp deleted file mode 100644 index 82ea70158c..0000000000 --- a/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include - -namespace Terrain -{ - AZStd::vector> EditorSelectableTagListProvider::BuildSelectableTagList() const - { - AZStd::vector> availableTags = SurfaceData::SurfaceTag::GetRegisteredTags(); - - AZStd::unordered_set tagsInUse = AZStd::move(GetSurfaceTagsInUse()); - - // Filter out all tags in use from the list of registered tags - availableTags.erase(std::remove_if(availableTags.begin(), availableTags.end(), - [&tagsInUse](const auto& tag)-> bool - { - return tagsInUse.contains(tag.first); - }), availableTags.end()); - - return AZStd::move(availableTags); - } -} diff --git a/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.h b/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.h deleted file mode 100644 index d8640bd73f..0000000000 --- a/Gems/Terrain/Code/Source/EditorSelectableTagListProvider.h +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once -#include -#include -#include - -namespace Terrain -{ - //! Interface for a class providing information about surface tags available for selecting in Editor components. - class EditorSelectableTagListProvider - { - public: - //! Returns a list of available tags to be selected in the component. - virtual AZStd::vector> BuildSelectableTagList() const; - - //! Returns a set of CRC of all surface tags currently in use and not available for selecting. - virtual AZStd::unordered_set GetSurfaceTagsInUse() const = 0; - }; -} diff --git a/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp b/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp new file mode 100644 index 0000000000..aa4a666d1b --- /dev/null +++ b/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + + +namespace Terrain +{ + AZStd::vector> BuildSelectableTagList(const EditorSurfaceTagListProvider* tagListProvider, + const SurfaceData::SurfaceTag& currentTag) + { + AZStd::vector> availableTags = SurfaceData::SurfaceTag::GetRegisteredTags(); + + AZStd::unordered_set tagsInUse; + + if (tagListProvider) + { + tagsInUse = AZStd::move(tagListProvider->GetSurfaceTagsInUse()); + + // Filter out all tags in use from the list of registered tags + AZStd::erase_if(availableTags, [&tagsInUse](const auto& tag)-> bool + { + return tagsInUse.contains(SurfaceData::SurfaceTag(tag.first)); + }); + } + + // Insert the current tag back if it was removed via tagsInUse + availableTags.emplace_back({ AZ::u32(currentTag), currentTag.GetDisplayName() }); + + // Sorting for consistency + AZStd::sort(availableTags.begin(), availableTags.end(), [](const auto& lhs, const auto& rhs) {return lhs.second < rhs.second; }); + + return AZStd::move(availableTags); + } +} diff --git a/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.h b/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.h new file mode 100644 index 0000000000..ed5a5c1c0a --- /dev/null +++ b/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once +#include +#include +#include +#include + +namespace Terrain +{ + //! Interface for a class providing information about surface tags available for selecting in Editor components. + class EditorSurfaceTagListProvider + { + public: + //! Returns a set of all surface tags currently in use that won't be available for selecting. + virtual AZStd::unordered_set GetSurfaceTagsInUse() const = 0; + }; + + //! Returns a list of available tags to be selected in the component. + AZStd::vector> BuildSelectableTagList( + const EditorSurfaceTagListProvider* tagListProvider, + const SurfaceData::SurfaceTag& currentTag); +} diff --git a/Gems/Terrain/Code/terrain_editor_shared_files.cmake b/Gems/Terrain/Code/terrain_editor_shared_files.cmake index deb70ba566..ed64b7c4fc 100644 --- a/Gems/Terrain/Code/terrain_editor_shared_files.cmake +++ b/Gems/Terrain/Code/terrain_editor_shared_files.cmake @@ -25,8 +25,8 @@ set(FILES Source/EditorComponents/EditorTerrainSystemComponent.h Source/EditorTerrainModule.cpp Source/EditorTerrainModule.h - Source/EditorSelectableTagListProvider.h - Source/EditorSelectableTagListProvider.cpp + Source/EditorSurfaceTagListProvider.h + Source/EditorSurfaceTagListProvider.cpp Source/TerrainModule.cpp Source/TerrainModule.h Source/TerrainRenderer/EditorComponents/EditorTerrainSurfaceMaterialsListComponent.cpp From 5dfbddd0cf21e982072a83f84d28cd326e8c4af8 Mon Sep 17 00:00:00 2001 From: Sergey Pereslavtsev Date: Tue, 8 Feb 2022 14:48:52 +0000 Subject: [PATCH 022/133] Build fix Signed-off-by: Sergey Pereslavtsev --- Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp b/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp index aa4a666d1b..12a371fc49 100644 --- a/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp +++ b/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp @@ -33,7 +33,7 @@ namespace Terrain } // Insert the current tag back if it was removed via tagsInUse - availableTags.emplace_back({ AZ::u32(currentTag), currentTag.GetDisplayName() }); + availableTags.emplace_back(AZ::u32(currentTag), currentTag.GetDisplayName()); // Sorting for consistency AZStd::sort(availableTags.begin(), availableTags.end(), [](const auto& lhs, const auto& rhs) {return lhs.second < rhs.second; }); From 74f6d1ec742baf7cad54c64a3100564efc7c9124 Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Tue, 8 Feb 2022 12:12:40 -0800 Subject: [PATCH 023/133] Cleanup up and resolving conflicts after the latest merge. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../Material/MaterialNameContext.h | 3 ++ .../Material/MaterialNameContext.cpp | 33 +++++++++++++++++++ .../Code/Source/Document/MaterialDocument.cpp | 26 +++++++++------ .../Code/Source/Document/MaterialDocument.h | 3 +- 4 files changed, 54 insertions(+), 11 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h index 3ecdfeb449..124d73ad7a 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h @@ -40,6 +40,9 @@ namespace AZ bool ContextualizeProperty(Name& propertyName) const; bool ContextualizeSrgInput(Name& srgInputName) const; bool ContextualizeShaderOption(Name& shaderOptionName) const; + bool ContextualizeProperty(AZStd::string& propertyName) const; + bool ContextualizeSrgInput(AZStd::string& srgInputName) const; + bool ContextualizeShaderOption(AZStd::string& shaderOptionName) const; //! Returns true if there is some non-default name context. bool HasContextForProperties() const { return !m_propertyIdContext.empty(); } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp index bf457a0a93..5846c60e05 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp @@ -84,6 +84,39 @@ namespace AZ shaderOptionName = m_shaderOptionNameContext + shaderOptionName.GetCStr(); return true; } + + bool MaterialNameContext::ContextualizeProperty(AZStd::string& propertyName) const + { + if (m_propertyIdContext.empty()) + { + return false; + } + + propertyName = m_propertyIdContext + propertyName; + return true; + } + + bool MaterialNameContext::ContextualizeSrgInput(AZStd::string& srgInputName) const + { + if (m_srgInputNameContext.empty()) + { + return false; + } + + srgInputName = m_srgInputNameContext + srgInputName; + return true; + } + + bool MaterialNameContext::ContextualizeShaderOption(AZStd::string& shaderOptionName) const + { + if (m_shaderOptionNameContext.empty()) + { + return false; + } + + shaderOptionName = m_shaderOptionNameContext + shaderOptionName; + return true; + } } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index a66aa1dd21..648b0dd4c8 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -336,9 +336,9 @@ namespace MaterialEditor bool addPropertiesResult = true; // populate sourceData with properties that meet the filter - m_materialTypeSourceData.EnumerateProperties([&](const auto& propertyDefinition, const MaterialNameContext& nameContext) { + m_materialTypeSourceData.EnumerateProperties([&](const auto& propertyDefinition, const AZ::RPI::MaterialNameContext& nameContext) { - Name propertyId{propertyDefinition->GetName()}; + AZ::Name propertyId{propertyDefinition->GetName()}; nameContext.ContextualizeProperty(propertyId); const auto property = FindProperty(propertyId); @@ -551,16 +551,19 @@ namespace MaterialEditor // in the hierarchy are applied bool enumerateResult = m_materialTypeSourceData.EnumeratePropertyGroups( [this, &parentPropertyValues]( - const AZStd::string& propertyIdContext, const AZ::RPI::MaterialTypeSourceData::PropertyGroup* propertyGroup) + const AZ::RPI::MaterialTypeSourceData::PropertyGroup* propertyGroup, + const AZ::RPI::MaterialNameContext& groupNameContext, + const AZ::RPI::MaterialNameContext& parentNameContext) { // Add any material functors that are located inside each property group. - if (!AddEditorMaterialFunctors(propertyGroup->GetFunctors())) + if (!AddEditorMaterialFunctors(propertyGroup->GetFunctors(), groupNameContext)) { return false; } - + m_groups.emplace_back(aznew AtomToolsFramework::DynamicPropertyGroup); - m_groups.back()->m_name = propertyIdContext + propertyGroup->GetName(); + m_groups.back()->m_name = propertyGroup->GetName(); + parentNameContext.ContextualizeProperty(m_groups.back()->m_name); m_groups.back()->m_displayName = propertyGroup->GetDisplayName(); m_groups.back()->m_description = propertyGroup->GetDescription(); @@ -568,7 +571,8 @@ namespace MaterialEditor { // Assign id before conversion so it can be used in dynamic description AtomToolsFramework::DynamicPropertyConfig propertyConfig; - propertyConfig.m_id = m_groups.back()->m_name + "." + propertyDefinition->GetName(); + propertyConfig.m_id = propertyDefinition->GetName(); + groupNameContext.ContextualizeProperty(m_groups.back()->m_name); const auto& propertyIndex = m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); const bool propertyIndexInBounds = @@ -610,7 +614,8 @@ namespace MaterialEditor } // Add material functors that are in the top-level functors list. - if (!AddEditorMaterialFunctors(m_materialTypeSourceData.m_materialFunctorSourceData)) + AZ::RPI::MaterialNameContext materialNameContext; // There is no name context for top-level functors, only functors inside PropertyGroups + if (!AddEditorMaterialFunctors(m_materialTypeSourceData.m_materialFunctorSourceData, materialNameContext)) { return OpenFailed(); } @@ -736,10 +741,11 @@ namespace MaterialEditor } bool MaterialDocument::AddEditorMaterialFunctors( - const AZStd::vector>& functorSourceDataHolders) + const AZStd::vector>& functorSourceDataHolders, + const AZ::RPI::MaterialNameContext& nameContext) { const AZ::RPI::MaterialFunctorSourceData::EditorContext editorContext = AZ::RPI::MaterialFunctorSourceData::EditorContext( - m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout()); + m_materialSourceData.m_materialType, m_materialAsset->GetMaterialPropertiesLayout(), &nameContext); for (AZ::RPI::Ptr functorData : functorSourceDataHolders) { diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h index 37b3e1922f..42385cfb25 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h @@ -82,7 +82,8 @@ namespace MaterialEditor void RestorePropertyValues(const PropertyValueMap& propertyValues); bool AddEditorMaterialFunctors( - const AZStd::vector>& functorSourceDataHolders); + const AZStd::vector>& functorSourceDataHolders, + const AZ::RPI::MaterialNameContext& nameContext); // Run editor material functor to update editor metadata. // @param dirtyFlags indicates which properties have changed, and thus which MaterialFunctors need to be run. From 1af5b28ea367e50b2a6592979684e7777d20fc5e Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Tue, 8 Feb 2022 12:41:03 -0800 Subject: [PATCH 024/133] Fixed a copy-paste mistake, wrong name for a property. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../MaterialEditor/Code/Source/Document/MaterialDocument.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index 648b0dd4c8..04021f2def 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -572,7 +572,7 @@ namespace MaterialEditor // Assign id before conversion so it can be used in dynamic description AtomToolsFramework::DynamicPropertyConfig propertyConfig; propertyConfig.m_id = propertyDefinition->GetName(); - groupNameContext.ContextualizeProperty(m_groups.back()->m_name); + groupNameContext.ContextualizeProperty(propertyConfig.m_id); const auto& propertyIndex = m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); const bool propertyIndexInBounds = From 2a3c5b38e54f93dc68f70415e80120c0296e237a Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Tue, 8 Feb 2022 14:06:53 -0800 Subject: [PATCH 025/133] Added a unit test demonstrating that MaterialSourceData can support properties and subgroups together in the same property group. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../Material/MaterialTypeSourceDataTests.cpp | 35 ++++++++++++++----- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp index 46cbb1ac46..c187660377 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp @@ -2093,6 +2093,8 @@ namespace UnitTest materialSrgLayout->AddShaderInput(RHI::ShaderInputImageDescriptor{ Name{ "m_unused1" }, RHI::ShaderInputImageAccess::Read, RHI::ShaderInputImageType::Image2D, 1, 1 }); materialSrgLayout->AddShaderInput(RHI::ShaderInputImageDescriptor{ Name{ "m_unused2" }, RHI::ShaderInputImageAccess::Read, RHI::ShaderInputImageType::Image2D, 1, 1 }); materialSrgLayout->AddShaderInput(RHI::ShaderInputImageDescriptor{ Name{ "m_groupA_m_groupB_m_texture" }, RHI::ShaderInputImageAccess::Read, RHI::ShaderInputImageType::Image2D, 1, 1 }); + materialSrgLayout->AddShaderInput(RHI::ShaderInputConstantDescriptor{ Name{ "m_unused3" }, 0, 4, 0 }); + materialSrgLayout->AddShaderInput(RHI::ShaderInputConstantDescriptor{ Name{ "m_groupA_m_groupB_m_number" }, 4, 4, 0 }); EXPECT_TRUE(materialSrgLayout->Finalize()); Ptr shaderOptions = ShaderOptionGroupLayout::Create(); @@ -2120,6 +2122,16 @@ namespace UnitTest "name": "groupB", "shaderInputsPrefix": "m_groupB_", "shaderOptionsPrefix": "o_groupB_", + "properties": [ + { + "name": "number", + "type": "Float", + "connection": { + "type": "ShaderInput", + "name": "m_number" + } + } + ], "propertyGroups": [ { "name": "groupC", @@ -2177,25 +2189,32 @@ namespace UnitTest Data::Asset materialTypeAsset = materialTypeAssetOutcome.TakeValue(); const MaterialPropertiesLayout* propertiesLayout = materialTypeAsset->GetMaterialPropertiesLayout(); - EXPECT_EQ(2, propertiesLayout->GetPropertyCount()); - - EXPECT_EQ(0, propertiesLayout->FindPropertyIndex(Name("groupA.groupB.groupC.textureMap")).GetIndex()); - EXPECT_EQ(1, propertiesLayout->FindPropertyIndex(Name("groupA.groupB.groupC.useTextureMap")).GetIndex()); + EXPECT_EQ(3, propertiesLayout->GetPropertyCount()); + + EXPECT_EQ(0, propertiesLayout->FindPropertyIndex(Name("groupA.groupB.number")).GetIndex()); + EXPECT_EQ(1, propertiesLayout->FindPropertyIndex(Name("groupA.groupB.groupC.textureMap")).GetIndex()); + EXPECT_EQ(2, propertiesLayout->FindPropertyIndex(Name("groupA.groupB.groupC.useTextureMap")).GetIndex()); + + // groupA.groupB.number has a connection to m_groupA_m_groupB_m_number + MaterialPropertyIndex numberPropertyIndex{0}; + EXPECT_EQ(1, propertiesLayout->GetPropertyDescriptor(numberPropertyIndex)->GetOutputConnections().size()); + EXPECT_EQ(materialSrgLayout->FindShaderInputConstantIndex(Name("m_groupA_m_groupB_m_number")).GetIndex(), + propertiesLayout->GetPropertyDescriptor(numberPropertyIndex)->GetOutputConnections()[0].m_itemIndex.GetIndex()); // groupA.gropuB.groupC.textureMap has a connection to m_groupA_m_groupB_m_texture - MaterialPropertyIndex texturePropertyIndex{0}; + MaterialPropertyIndex texturePropertyIndex{1}; EXPECT_EQ(1, propertiesLayout->GetPropertyDescriptor(texturePropertyIndex)->GetOutputConnections().size()); EXPECT_EQ(materialSrgLayout->FindShaderInputImageIndex(Name("m_groupA_m_groupB_m_texture")).GetIndex(), propertiesLayout->GetPropertyDescriptor(texturePropertyIndex)->GetOutputConnections()[0].m_itemIndex.GetIndex()); - + // groupA.gropuB.groupC.useTextureMap has a connection to o_groupA_o_groupB_o_useTexture and o_groupA_o_groupB_o_useTextureAlt - MaterialPropertyIndex useTexturePropertyIndex{1}; + MaterialPropertyIndex useTexturePropertyIndex{2}; EXPECT_EQ(2, propertiesLayout->GetPropertyDescriptor(useTexturePropertyIndex)->GetOutputConnections().size()); EXPECT_EQ(shaderOptions->FindShaderOptionIndex(Name("o_groupA_o_groupB_o_useTexture")).GetIndex(), propertiesLayout->GetPropertyDescriptor(useTexturePropertyIndex)->GetOutputConnections()[0].m_itemIndex.GetIndex()); EXPECT_EQ(shaderOptions->FindShaderOptionIndex(Name("o_groupA_o_groupB_o_useTextureAlt")).GetIndex(), propertiesLayout->GetPropertyDescriptor(useTexturePropertyIndex)->GetOutputConnections()[1].m_itemIndex.GetIndex()); - + // There should be one functor, which processes useTextureMap, and it should have the appropriate name context for constructing the correct full names. EXPECT_EQ(1, materialTypeAsset->GetMaterialFunctors().size()); From 8c545138673c7b8fdc249cff6a4c2d780279f35f Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 8 Feb 2022 16:59:25 -0800 Subject: [PATCH 026/133] Add box selection tests for Editor Focus Mode Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../ContainerEntitySelectionTests.cpp | 10 +-- .../FocusMode/EditorFocusModeFixture.cpp | 11 ++- .../Tests/FocusMode/EditorFocusModeFixture.h | 10 +-- .../EditorFocusModeSelectionFixture.h | 15 ++++ .../EditorFocusModeSelectionTests.cpp | 71 +++++++++++++++++-- 5 files changed, 99 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzToolsFramework/Tests/FocusMode/ContainerEntitySelectionTests.cpp b/Code/Framework/AzToolsFramework/Tests/FocusMode/ContainerEntitySelectionTests.cpp index 0ad61b924b..483db4076e 100644 --- a/Code/Framework/AzToolsFramework/Tests/FocusMode/ContainerEntitySelectionTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/FocusMode/ContainerEntitySelectionTests.cpp @@ -15,7 +15,7 @@ namespace UnitTest // When no containers are in the way, the function will just return the entityId of the entity that was clicked. // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify the correct entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); @@ -29,7 +29,7 @@ namespace UnitTest m_containerEntityInterface->RegisterEntityAsContainer(m_entityMap[StreetEntityName]); // Containers are closed by default // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify the correct entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); @@ -47,7 +47,7 @@ namespace UnitTest m_containerEntityInterface->SetContainerOpen(m_entityMap[StreetEntityName], true); // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify the correct entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); @@ -65,7 +65,7 @@ namespace UnitTest m_containerEntityInterface->RegisterEntityAsContainer(m_entityMap[CityEntityName]); // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify the correct entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); @@ -85,7 +85,7 @@ namespace UnitTest m_containerEntityInterface->SetContainerOpen(m_entityMap[CityEntityName], true); // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify the correct entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); diff --git a/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeFixture.cpp b/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeFixture.cpp index 90becfa46f..374b85c01d 100644 --- a/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeFixture.cpp +++ b/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeFixture.cpp @@ -8,6 +8,7 @@ #include +#include #include #include @@ -93,10 +94,13 @@ namespace UnitTest entity->CreateComponent(); entity->Activate(); - // Move the CarEntity so it's out of the way. - AZ::TransformBus::Event(m_entityMap[CarEntityName], &AZ::TransformBus::Events::SetWorldTranslation, WorldCarEntityPosition); + // Move the City so that it is in view + AZ::TransformBus::Event(m_entityMap[CityEntityName], &AZ::TransformBus::Events::SetWorldTranslation, s_worldCityEntityPosition); - // Setup the camera so the Car entity is in view. + // Move the CarEntity so that it's not overlapping with the rest + AZ::TransformBus::Event(m_entityMap[CarEntityName], &AZ::TransformBus::Events::SetWorldTranslation, s_worldCarEntityPosition); + + // Setup the camera so the entities is in view. AzFramework::SetCameraTransform( m_cameraState, AZ::Transform::CreateFromQuaternionAndTranslation( @@ -113,4 +117,5 @@ namespace UnitTest return entity->GetId(); } + } // namespace UnitTest diff --git a/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeFixture.h b/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeFixture.h index 0cf1be6ffd..88cc5ac921 100644 --- a/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeFixture.h +++ b/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeFixture.h @@ -8,7 +8,6 @@ #pragma once -#include #include #include @@ -38,9 +37,6 @@ namespace UnitTest AzToolsFramework::EntityIdList GetSelectedEntities(); AzFramework::EntityContextId m_editorEntityContextId = AzFramework::EntityContextId::CreateNull(); - AzFramework::CameraState m_cameraState; - - inline static const AZ::Vector3 CameraPosition = AZ::Vector3(10.0f, 15.0f, 10.0f); inline static const char* CityEntityName = "City"; inline static const char* StreetEntityName = "Street"; @@ -49,7 +45,11 @@ namespace UnitTest inline static const char* Passenger1EntityName = "Passenger1"; inline static const char* Passenger2EntityName = "Passenger2"; - inline static AZ::Vector3 WorldCarEntityPosition = AZ::Vector3(5.0f, 15.0f, 0.0f); + AzFramework::CameraState m_cameraState; + + inline static const AZ::Vector3 CameraPosition = AZ::Vector3(10.0f, 15.0f, 10.0f); + inline static AZ::Vector3 s_worldCityEntityPosition = AZ::Vector3(5.0f, 10.0f, 0.0f); + inline static AZ::Vector3 s_worldCarEntityPosition = AZ::Vector3(5.0f, 15.0f, 0.0f); }; } // namespace UnitTest diff --git a/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeSelectionFixture.h b/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeSelectionFixture.h index fe1de9b122..5dc323dd8c 100644 --- a/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeSelectionFixture.h +++ b/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeSelectionFixture.h @@ -45,5 +45,20 @@ namespace UnitTest // Click the entity in the viewport m_actionDispatcher->CameraState(m_cameraState)->MousePosition(carScreenPosition)->MouseLButtonDown()->MouseLButtonUp(); } + + void BoxSelectOnViewport() + { + // Calculate the position in screen space of where to begin and end the box select action + const auto beginningPositionWorldBoxSelect = AzFramework::WorldToScreen(AZ::Vector3(-10.0f, 15.0f, 5.0f), m_cameraState); + const auto endingPositionWorldBoxSelect = AzFramework::WorldToScreen(AZ::Vector3(10.0f, 15.0f, -5.0f), m_cameraState); + + // Perform a box select in the viewport + m_actionDispatcher->SetStickySelect(true) + ->CameraState(m_cameraState) + ->MousePosition(beginningPositionWorldBoxSelect) + ->MouseLButtonDown() + ->MousePosition(endingPositionWorldBoxSelect) + ->MouseLButtonUp(); + } }; } // namespace UnitTest diff --git a/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeSelectionTests.cpp b/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeSelectionTests.cpp index 1efcb15b30..ee338539a8 100644 --- a/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeSelectionTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/FocusMode/EditorFocusModeSelectionTests.cpp @@ -13,7 +13,7 @@ namespace UnitTest TEST_F(EditorFocusModeSelectionFixture, EditorFocusModeSelectionSelectEntityWithFocusOnLevel) { // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); @@ -27,7 +27,7 @@ namespace UnitTest m_focusModeInterface->SetFocusRoot(m_entityMap[StreetEntityName]); // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); @@ -41,7 +41,7 @@ namespace UnitTest m_focusModeInterface->SetFocusRoot(m_entityMap[CarEntityName]); // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); @@ -55,7 +55,7 @@ namespace UnitTest m_focusModeInterface->SetFocusRoot(m_entityMap[SportsCarEntityName]); // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); @@ -68,10 +68,71 @@ namespace UnitTest m_focusModeInterface->SetFocusRoot(m_entityMap[Passenger1EntityName]); // Click on Car Entity - ClickAtWorldPositionOnViewport(WorldCarEntityPosition); + ClickAtWorldPositionOnViewport(s_worldCarEntityPosition); // Verify entity is selected auto selectedEntitiesAfter = GetSelectedEntities(); EXPECT_EQ(selectedEntitiesAfter.size(), 0); } + + TEST_F(EditorFocusModeSelectionFixture, EditorFocusModeSelectionBoxSelectWithFocusOnLevel) + { + // Do a box select that includes all entities in the fixture + BoxSelectOnViewport(); + + // Entities are selected + using ::testing::UnorderedElementsAre; + auto selectedEntitiesAfter = GetSelectedEntities(); + EXPECT_THAT(selectedEntitiesAfter, + UnorderedElementsAre( + m_entityMap[CityEntityName], + m_entityMap[StreetEntityName], + m_entityMap[CarEntityName], + m_entityMap[Passenger1EntityName], + m_entityMap[SportsCarEntityName], + m_entityMap[Passenger2EntityName] + ) + ); + } + + TEST_F(EditorFocusModeSelectionFixture, EditorFocusModeSelectionBoxSelectWithFocusOnChild) + { + // Set the focus on the Passenger1 Entity (child of the entity) + m_focusModeInterface->SetFocusRoot(m_entityMap[StreetEntityName]); + + // Do a box select that includes all entities in the fixture + BoxSelectOnViewport(); + + // Entities are selected + using ::testing::UnorderedElementsAre; + auto selectedEntitiesAfter = GetSelectedEntities(); + EXPECT_THAT(selectedEntitiesAfter, + UnorderedElementsAre( + m_entityMap[StreetEntityName], + m_entityMap[CarEntityName], + m_entityMap[Passenger1EntityName], + m_entityMap[SportsCarEntityName], + m_entityMap[Passenger2EntityName] + ) + ); + } + + TEST_F(EditorFocusModeSelectionFixture, EditorFocusModeSelectionBoxSelectWithFocusOnLeaf) + { + // Set the focus on the Passenger1 Entity (child of the entity) + m_focusModeInterface->SetFocusRoot(m_entityMap[Passenger1EntityName]); + + // Do a box select that includes all entities in the fixture + BoxSelectOnViewport(); + + // Entities are selected + using ::testing::UnorderedElementsAre; + auto selectedEntitiesAfter = GetSelectedEntities(); + EXPECT_THAT(selectedEntitiesAfter, + UnorderedElementsAre( + m_entityMap[Passenger1EntityName] + ) + ); + } + } // namespace UnitTest From b2206be14d48622811f8c324ca66f75f0e44fb65 Mon Sep 17 00:00:00 2001 From: moraaar Date: Wed, 9 Feb 2022 13:37:34 +0000 Subject: [PATCH 027/133] Fixed range-loop-analysis warninig reported as error on mac/ios (#7511) Signed-off-by: moraaar --- Gems/Prefab/PrefabBuilder/PrefabGroup/PrefabGroupBehavior.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Prefab/PrefabBuilder/PrefabGroup/PrefabGroupBehavior.cpp b/Gems/Prefab/PrefabBuilder/PrefabGroup/PrefabGroupBehavior.cpp index 751c04952c..aac758b96e 100644 --- a/Gems/Prefab/PrefabBuilder/PrefabGroup/PrefabGroupBehavior.cpp +++ b/Gems/Prefab/PrefabBuilder/PrefabGroup/PrefabGroupBehavior.cpp @@ -153,7 +153,7 @@ namespace AZ::SceneAPI::Behaviors // all mesh data nodes left in the meshIndexContainer do not have a matching TransformData node // since the nodes have an identity transform, so map the MeshData index with an Invalid mesh index to // indicate the transform should not be set to a default value - for( const auto meshIndex : meshIndexContainer) + for( const auto& meshIndex : meshIndexContainer) { MeshTransformPair pair{ meshIndex, Containers::SceneGraph::NodeIndex{} }; meshTransformMap.emplace(MeshTransformEntry{ graph.GetNodeParent(meshIndex), AZStd::move(pair) }); From fee95f3f5eb6c7d62ea97158a74f071f9e80a7de Mon Sep 17 00:00:00 2001 From: jromnoa <80134229+jromnoa@users.noreply.github.com> Date: Wed, 9 Feb 2022 08:10:33 -0800 Subject: [PATCH 028/133] sandboxing the sponza level from the level test because it causes a hardlock 4%-12% of the time (#7513) Signed-off-by: jromnoa <80134229+jromnoa@users.noreply.github.com> --- .../Gem/PythonTests/Atom/TestSuite_Sandbox.py | 7 +- .../Atom/atom_utils/atom_constants.py | 4 +- .../tests/hydra_Atom_LevelLoadTest_Sandbox.py | 71 +++++++++++++++++++ 3 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_Atom_LevelLoadTest_Sandbox.py diff --git a/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Sandbox.py b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Sandbox.py index 5299e55a2b..54e3d8cb41 100644 --- a/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Sandbox.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/TestSuite_Sandbox.py @@ -20,9 +20,14 @@ TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "tests") @pytest.mark.parametrize("launcher_platform", ['windows_editor']) class TestAutomation(EditorTestSuite): - enable_prefab_system = False + enable_prefab_system = True # this test is intermittently timing out without ever having executed. sandboxing while we investigate cause. @pytest.mark.test_case_id("C36525660") class AtomEditorComponents_DisplayMapperAdded(EditorSharedTest): from Atom.tests import hydra_AtomEditorComponents_DisplayMapperAdded as test_module + + # The "Sponza" level is failing with a hard lock 4-12% of the time, needs root causing and fixing. + @pytest.mark.test_case_id("C36529679") + class AtomLevelLoadTest_Editor_Sandbox(EditorSharedTest): + from Atom.tests import hydra_Atom_LevelLoadTest_Sandbox as test_module diff --git a/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/atom_constants.py b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/atom_constants.py index 6525536f96..778f9bd3fb 100644 --- a/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/atom_constants.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/atom_constants.py @@ -33,7 +33,9 @@ GLOBAL_ILLUMINATION_QUALITY = { } # Level list used in Editor Level Load Test -LEVEL_LIST = ["hermanubis", "hermanubis_high", "macbeth_shaderballs", "PbrMaterialChart", "ShadowTest", "Sponza"] +# WARNING: "Sponza" level is sandboxed due to an intermittent failure. +LEVEL_LIST = ["hermanubis", "hermanubis_high", "macbeth_shaderballs", "PbrMaterialChart", "ShadowTest"] + class AtomComponentProperties: """ diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_Atom_LevelLoadTest_Sandbox.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_Atom_LevelLoadTest_Sandbox.py new file mode 100644 index 0000000000..6cee7b2840 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_Atom_LevelLoadTest_Sandbox.py @@ -0,0 +1,71 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + + +def Atom_LevelLoadTest(): + """ + Summary: + Loads all graphics levels within the AutomatedTesting project in editor. For each level this script will verify that + the level loads, and can enter/exit gameplay without crashing the editor. + + Test setup: + - Store all available levels in a list. + - Set up a for loop to run all checks for each level. + + Expected Behavior: + Test verifies that each level loads, enters/exits game mode, and reports success for all test actions. + + Test Steps for each level: + 1) Create tuple with level load success and failure messages + 2) Open the level using the python test tools command + 3) Verify level is loaded using a separate command, and report success/failure + 4) Enter gameplay and report result using a tuple + 5) Exit Gameplay and report result using a tuple + 6) Look for errors or asserts. + + :return: None + """ + SANDBOX_LEVEL_LIST = ["Sponza"] + + import azlmbr.legacy.general as general + + from editor_python_test_tools.utils import Report, Tracer, TestHelper + + with Tracer() as error_tracer: + + for level in SANDBOX_LEVEL_LIST: + + # 1. Create tuple with level load success and failure messages + level_check_tuple = (f"loaded {level}", f"failed to load {level}") + + # 2. Open the level using the python test tools command + TestHelper.init_idle() + TestHelper.open_level("Graphics", level) + + # 3. Verify level is loaded using a separate command, and report success/failure + Report.result(level_check_tuple, level == general.get_current_level_name()) + + # 4. Enter gameplay and report result using a tuple + enter_game_mode_tuple = (f"{level} entered gameplay successfully ", f"{level} failed to enter gameplay") + TestHelper.enter_game_mode(enter_game_mode_tuple) + general.idle_wait_frames(1) + + # 5. Exit gameplay and report result using a tuple + exit_game_mode_tuple = (f"{level} exited gameplay successfully ", f"{level} failed to exit gameplay") + TestHelper.exit_game_mode(exit_game_mode_tuple) + + # 6. Look for errors or asserts. + TestHelper.wait_for_condition(lambda: error_tracer.has_errors or error_tracer.has_asserts, 1.0) + for error_info in error_tracer.errors: + Report.info(f"Error: {error_info.filename} {error_info.function} | {error_info.message}") + for assert_info in error_tracer.asserts: + Report.info(f"Assert: {assert_info.filename} {assert_info.function} | {assert_info.message}") + + +if __name__ == "__main__": + from editor_python_test_tools.utils import Report + Report.start_test(Atom_LevelLoadTest) From 08a9f908a2a2e3bcf72ac5fa3aa770638e2971f4 Mon Sep 17 00:00:00 2001 From: lsemp3d <58790905+lsemp3d@users.noreply.github.com> Date: Wed, 9 Feb 2022 09:16:21 -0800 Subject: [PATCH 029/133] Disabled tests that are reported failing on nightly builds Signed-off-by: lsemp3d <58790905+lsemp3d@users.noreply.github.com> --- .../Gem/PythonTests/scripting/TestSuite_Periodic.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py index 27af63ddbc..85714b84a9 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Periodic.py @@ -61,6 +61,7 @@ class TestAutomation(TestAutomationBase): from . import Graph_HappyPath_ZoomInZoomOut as test_module self._run_test(request, workspace, editor, test_module, enable_prefab_system=False) + @pytest.mark.xfail(reason="Test fails on nightly build builds, it needs to be fixed.") def test_NodePalette_HappyPath_CanSelectNode(self, request, workspace, editor, launcher_platform): from . import NodePalette_HappyPath_CanSelectNode as test_module self._run_test(request, workspace, editor, test_module, enable_prefab_system=False) @@ -113,6 +114,7 @@ class TestAutomation(TestAutomationBase): from . import Debugger_HappyPath_TargetMultipleGraphs as test_module self._run_test(request, workspace, editor, test_module, enable_prefab_system=False) + @pytest.mark.xfail(reason="Test fails on nightly build builds, it needs to be fixed.") @pytest.mark.parametrize("level", ["tmp_level"]) def test_Debugger_HappyPath_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): def teardown(): @@ -174,6 +176,7 @@ class TestAutomation(TestAutomationBase): from . import ScriptEvents_ReturnSetType_Successfully as test_module self._run_test(request, workspace, editor, test_module, enable_prefab_system=False) + @pytest.mark.xfail(reason="Test fails on nightly build builds, it needs to be fixed.") def test_NodeCategory_ExpandOnClick(self, request, workspace, editor, launcher_platform): from . import NodeCategory_ExpandOnClick as test_module self._run_test(request, workspace, editor, test_module, enable_prefab_system=False) @@ -187,6 +190,7 @@ class TestAutomation(TestAutomationBase): from . import VariableManager_UnpinVariableType_Works as test_module self._run_test(request, workspace, editor, test_module, enable_prefab_system=False) + @pytest.mark.xfail(reason="Test fails on nightly build builds, it needs to be fixed.") def test_Node_HappyPath_DuplicateNode(self, request, workspace, editor, launcher_platform): from . import Node_HappyPath_DuplicateNode as test_module self._run_test(request, workspace, editor, test_module, enable_prefab_system=False) @@ -266,6 +270,7 @@ class TestScriptCanvasTests(object): enable_prefab_system=False, ) + @pytest.mark.xfail(reason="Test fails on nightly build builds, it needs to be fixed.") def test_VariableManager_Default_CreateDeleteVars(self, request, editor, launcher_platform): var_types = ["Boolean", "Color", "EntityID", "Number", "String", "Transform", "Vector2", "Vector3", "Vector4"] expected_lines = [f"Success: {var_type} variable is created" for var_type in var_types] From 8cd8638316682dcb2738cc8d3c928f7d1a3c8bc0 Mon Sep 17 00:00:00 2001 From: carlitosan <82187351+carlitosan@users.noreply.github.com> Date: Wed, 9 Feb 2022 10:19:39 -0800 Subject: [PATCH 030/133] initial locale safety for translating to Lua on multiple platforms (#7490) * initial locale safety for translating to Lua on multiple platforms Signed-off-by: carlitosan <82187351+carlitosan@users.noreply.github.com> * fix android build error Signed-off-by: carlitosan <82187351+carlitosan@users.noreply.github.com> --- .../Translation/GraphToLuaUtility.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/GraphToLuaUtility.cpp b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/GraphToLuaUtility.cpp index f0eae04383..08bd3883ca 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/GraphToLuaUtility.cpp +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Translation/GraphToLuaUtility.cpp @@ -8,6 +8,8 @@ #include "GraphToLuaUtility.h" +#include + #include #include #include @@ -23,6 +25,23 @@ namespace GraphToLuaUtilityCpp { + class ScopedLocale + { + public: + ScopedLocale() + { + m_previousLocale = std::setlocale(LC_NUMERIC, "en_US.UTF-8"); + } + + ~ScopedLocale() + { + std::setlocale(LC_NUMERIC, m_previousLocale); + } + + private: + char* m_previousLocale = nullptr; + }; + AZStd::string EqualSigns(size_t numEqualSignsRequired) { AZStd::string equalSigns = ""; @@ -183,6 +202,8 @@ namespace ScriptCanvas AZStd::string ToValueString(const Datum& datum, const Configuration& config) { + GraphToLuaUtilityCpp::ScopedLocale scopedLocal; + switch (datum.GetType().GetType()) { case Data::eType::AABB: From 2f3c4d37dfc77485041b79358c9683a3860574cd Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Wed, 9 Feb 2022 12:22:38 -0600 Subject: [PATCH 031/133] Improved image gradient GetValue(s) performance by using cached image data Signed-off-by: Chris Galvan --- .../Code/Include/Atom/RPI.Public/RPIUtils.h | 5 ++ .../RPI/Code/Source/RPI.Public/RPIUtils.cpp | 74 +++++++++++++------ .../Components/ImageGradientComponent.h | 3 + .../Code/Include/GradientSignal/ImageAsset.h | 2 +- .../Components/ImageGradientComponent.cpp | 49 +++++++++++- .../GradientSignal/Code/Source/ImageAsset.cpp | 7 +- 6 files changed, 109 insertions(+), 31 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPIUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPIUtils.h index 546089ab1e..6516407265 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPIUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPIUtils.h @@ -60,6 +60,11 @@ namespace AZ //! Same as above. Provided as a convenience when all arguments of the 'numthreads' attributes should be assigned to RHI::DispatchDirect::m_threadsPerGroup* variables. AZ::Outcome GetComputeShaderNumThreads(const Data::Asset& shaderAsset, RHI::DispatchDirect& dispatchDirect); + //! Get single image pixel value from raw image data + //! This assumes the imageData is not empty + template + T GetImageDataPixelValue(AZStd::span imageData, const AZ::RHI::ImageDescriptor& imageDescriptor, uint32_t x, uint32_t y, uint32_t componentIndex = 0); + //! Get single image pixel value for specified mip and slice template T GetSubImagePixelValue(const AZ::Data::Asset& imageAsset, uint32_t x, uint32_t y, uint32_t componentIndex = 0, uint32_t mip = 0, uint32_t slice = 0); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp index 9ff26f0d3a..8a6cc80cfe 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RPIUtils.cpp @@ -232,16 +232,12 @@ namespace AZ } } - template - T GetSubImagePixelValueInternal(const AZ::Data::Asset& imageAsset, uint32_t x, uint32_t y, uint32_t componentIndex, uint32_t mip, uint32_t slice) + size_t GetImageDataIndex(const AZ::RHI::ImageDescriptor& imageDescriptor, uint32_t x, uint32_t y, uint32_t componentIndex) { - AZStd::array values{ aznumeric_cast(0) }; + auto width = imageDescriptor.m_size.m_width; + const uint32_t numComponents = AZ::RHI::GetFormatComponentCount(imageDescriptor.m_format); - auto topLeft = AZStd::make_pair(x, y); - auto bottomRight = AZStd::make_pair(x + 1, y + 1); - GetSubImagePixelValues(imageAsset, topLeft, bottomRight, AZStd::span(values), componentIndex, mip, slice); - - return values[0]; + return (y * width + x) * numComponents + componentIndex; } } @@ -447,22 +443,60 @@ namespace AZ return GetComputeShaderNumThreads(shaderAsset, &dispatchDirect.m_threadsPerGroupX, &dispatchDirect.m_threadsPerGroupY, &dispatchDirect.m_threadsPerGroupZ); } + template<> + float GetImageDataPixelValue(AZStd::span imageData, const AZ::RHI::ImageDescriptor& imageDescriptor, uint32_t x, uint32_t y, uint32_t componentIndex) + { + size_t imageDataIndex = Internal::GetImageDataIndex(imageDescriptor, x, y, componentIndex); + return Internal::RetrieveFloatValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); + } + + template<> + AZ::u32 GetImageDataPixelValue(AZStd::span imageData, const AZ::RHI::ImageDescriptor& imageDescriptor, uint32_t x, uint32_t y, uint32_t componentIndex) + { + size_t imageDataIndex = Internal::GetImageDataIndex(imageDescriptor, x, y, componentIndex); + return Internal::RetrieveUintValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); + } + + template<> + AZ::s32 GetImageDataPixelValue(AZStd::span imageData, const AZ::RHI::ImageDescriptor& imageDescriptor, uint32_t x, uint32_t y, uint32_t componentIndex) + { + size_t imageDataIndex = Internal::GetImageDataIndex(imageDescriptor, x, y, componentIndex); + return Internal::RetrieveIntValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); + } + + template + T GetSubImagePixelValueInternal(const AZ::Data::Asset& imageAsset, uint32_t x, uint32_t y, uint32_t componentIndex, uint32_t mip, uint32_t slice) + { + if (!imageAsset.IsReady()) + { + return aznumeric_cast(0); + } + + auto imageData = imageAsset->GetSubImageData(mip, slice); + if (imageData.empty()) + { + return aznumeric_cast(0); + } + + return GetImageDataPixelValue(imageData, imageAsset->GetImageDescriptor(), x, y, componentIndex); + } + template<> float GetSubImagePixelValue(const AZ::Data::Asset& imageAsset, uint32_t x, uint32_t y, uint32_t componentIndex, uint32_t mip, uint32_t slice) { - return Internal::GetSubImagePixelValueInternal(imageAsset, x, y, componentIndex, mip, slice); + return GetSubImagePixelValueInternal(imageAsset, x, y, componentIndex, mip, slice); } template<> AZ::u32 GetSubImagePixelValue(const AZ::Data::Asset& imageAsset, uint32_t x, uint32_t y, uint32_t componentIndex, uint32_t mip, uint32_t slice) { - return Internal::GetSubImagePixelValueInternal(imageAsset, x, y, componentIndex, mip, slice); + return GetSubImagePixelValueInternal(imageAsset, x, y, componentIndex, mip, slice); } template<> AZ::s32 GetSubImagePixelValue(const AZ::Data::Asset& imageAsset, uint32_t x, uint32_t y, uint32_t componentIndex, uint32_t mip, uint32_t slice) { - return Internal::GetSubImagePixelValueInternal(imageAsset, x, y, componentIndex, mip, slice); + return GetSubImagePixelValueInternal(imageAsset, x, y, componentIndex, mip, slice); } bool GetSubImagePixelValues(const AZ::Data::Asset& imageAsset, AZStd::pair topLeft, AZStd::pair bottomRight, AZStd::span outValues, uint32_t componentIndex, uint32_t mip, uint32_t slice) @@ -478,16 +512,14 @@ namespace AZ return false; } - const AZ::RHI::ImageDescriptor imageDescriptor = imageAsset->GetImageDescriptor(); - auto width = imageDescriptor.m_size.m_width; - const uint32_t numComponents = AZ::RHI::GetFormatComponentCount(imageDescriptor.m_format); + const AZ::RHI::ImageDescriptor& imageDescriptor = imageAsset->GetImageDescriptor(); size_t outValuesIndex = 0; for (uint32_t y = topLeft.second; y < bottomRight.second; ++y) { for (uint32_t x = topLeft.first; x < bottomRight.first; ++x) { - size_t imageDataIndex = (y * width + x) * numComponents + componentIndex; + size_t imageDataIndex = Internal::GetImageDataIndex(imageDescriptor, x, y, componentIndex); auto& outValue = outValues[outValuesIndex++]; outValue = Internal::RetrieveFloatValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); @@ -510,16 +542,14 @@ namespace AZ return false; } - const AZ::RHI::ImageDescriptor imageDescriptor = imageAsset->GetImageDescriptor(); - auto width = imageDescriptor.m_size.m_width; - const uint32_t numComponents = AZ::RHI::GetFormatComponentCount(imageDescriptor.m_format); + const AZ::RHI::ImageDescriptor& imageDescriptor = imageAsset->GetImageDescriptor(); size_t outValuesIndex = 0; for (uint32_t y = topLeft.second; y < bottomRight.second; ++y) { for (uint32_t x = topLeft.first; x < bottomRight.first; ++x) { - size_t imageDataIndex = (y * width + x) * numComponents + componentIndex; + size_t imageDataIndex = Internal::GetImageDataIndex(imageDescriptor, x, y, componentIndex); auto& outValue = outValues[outValuesIndex++]; outValue = Internal::RetrieveUintValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); @@ -542,16 +572,14 @@ namespace AZ return false; } - const AZ::RHI::ImageDescriptor imageDescriptor = imageAsset->GetImageDescriptor(); - auto width = imageDescriptor.m_size.m_width; - const uint32_t numComponents = AZ::RHI::GetFormatComponentCount(imageDescriptor.m_format); + const AZ::RHI::ImageDescriptor& imageDescriptor = imageAsset->GetImageDescriptor(); size_t outValuesIndex = 0; for (uint32_t y = topLeft.second; y < bottomRight.second; ++y) { for (uint32_t x = topLeft.first; x < bottomRight.first; ++x) { - size_t imageDataIndex = (y * width + x) * numComponents + componentIndex; + size_t imageDataIndex = Internal::GetImageDataIndex(imageDescriptor, x, y, componentIndex); auto& outValue = outValues[outValuesIndex++]; outValue = Internal::RetrieveIntValue(imageData.data(), imageDataIndex, imageDescriptor.m_format); diff --git a/Gems/GradientSignal/Code/Include/GradientSignal/Components/ImageGradientComponent.h b/Gems/GradientSignal/Code/Include/GradientSignal/Components/ImageGradientComponent.h index 0cbd8bd4c7..7ec1c785e5 100644 --- a/Gems/GradientSignal/Code/Include/GradientSignal/Components/ImageGradientComponent.h +++ b/Gems/GradientSignal/Code/Include/GradientSignal/Components/ImageGradientComponent.h @@ -98,6 +98,8 @@ namespace GradientSignal void SetupDependencies(); + void GetSubImageData(); + // ImageGradientRequestBus overrides... AZStd::string GetImageAssetPath() const override; void SetImageAssetPath(const AZStd::string& assetPath) override; @@ -113,5 +115,6 @@ namespace GradientSignal LmbrCentral::DependencyMonitor m_dependencyMonitor; mutable AZStd::shared_mutex m_imageMutex; GradientTransform m_gradientTransform; + AZStd::span m_imageData; }; } diff --git a/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h b/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h index 811d74082d..500251d924 100644 --- a/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h +++ b/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h @@ -62,6 +62,6 @@ namespace GradientSignal } }; - float GetValueFromImageAsset(const AZ::Data::Asset& imageAsset, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue); + float GetValueFromImageAsset(AZStd::span imageData, const AZ::RHI::ImageDescriptor& imageDescriptor, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue); } // namespace GradientSignal diff --git a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp index 468b96e5ad..39a456a277 100644 --- a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp @@ -215,6 +215,16 @@ namespace GradientSignal m_dependencyMonitor.ConnectDependency(m_configuration.m_imageAsset.GetId()); } + void ImageGradientComponent::GetSubImageData() + { + if (!m_configuration.m_imageAsset || !m_configuration.m_imageAsset.IsReady()) + { + return; + } + + m_imageData = m_configuration.m_imageAsset->GetSubImageData(0, 0); + } + void ImageGradientComponent::Activate() { // This will immediately call OnGradientTransformChanged and initialize m_gradientTransform. @@ -226,8 +236,19 @@ namespace GradientSignal GradientRequestBus::Handler::BusConnect(GetEntityId()); AZ::Data::AssetBus::Handler::BusConnect(m_configuration.m_imageAsset.GetId()); + // If the image asset is already ready (e.g. constructed in a unit test), + // then go ahead and retrieve the image data now AZStd::unique_lock imageLock(m_imageMutex); - m_configuration.m_imageAsset.QueueLoad(); + if (m_configuration.m_imageAsset.IsReady()) + { + GetSubImageData(); + } + // Otherwise for normal use-case, we queue the asset to be loaded now + else + { + m_imageData = AZStd::span(); + m_configuration.m_imageAsset.QueueLoad(); + } } void ImageGradientComponent::Deactivate() @@ -267,18 +288,24 @@ namespace GradientSignal { AZStd::unique_lock imageLock(m_imageMutex); m_configuration.m_imageAsset = asset; + + GetSubImageData(); } void ImageGradientComponent::OnAssetMoved(AZ::Data::Asset asset, [[maybe_unused]] void* oldDataPointer) { AZStd::unique_lock imageLock(m_imageMutex); m_configuration.m_imageAsset = asset; + + GetSubImageData(); } void ImageGradientComponent::OnAssetReloaded(AZ::Data::Asset asset) { AZStd::unique_lock imageLock(m_imageMutex); m_configuration.m_imageAsset = asset; + + GetSubImageData(); } void ImageGradientComponent::OnGradientTransformChanged(const GradientTransform& newTransform) @@ -292,6 +319,12 @@ namespace GradientSignal AZ::Vector3 uvw = sampleParams.m_position; bool wasPointRejected = false; + // Return immediately if our cached image data hasn't been retrieved yet + if (m_imageData.empty()) + { + return 0.0f; + } + { AZStd::shared_lock imageLock(m_imageMutex); @@ -300,7 +333,7 @@ namespace GradientSignal if (!wasPointRejected) { return GetValueFromImageAsset( - m_configuration.m_imageAsset, uvw, m_configuration.m_tilingX, m_configuration.m_tilingY, 0.0f); + m_imageData, m_configuration.m_imageAsset->GetImageDescriptor(), uvw, m_configuration.m_tilingX, m_configuration.m_tilingY, 0.0f); } } @@ -315,6 +348,12 @@ namespace GradientSignal return; } + // Return immediately if our cached image data hasn't been retrieved yet + if (m_imageData.empty()) + { + return; + } + AZ::Vector3 uvw; bool wasPointRejected = false; @@ -327,7 +366,7 @@ namespace GradientSignal if (!wasPointRejected) { outValues[index] = GetValueFromImageAsset( - m_configuration.m_imageAsset, uvw, m_configuration.m_tilingX, m_configuration.m_tilingY, 0.0f); + m_imageData, m_configuration.m_imageAsset->GetImageDescriptor(), uvw, m_configuration.m_tilingX, m_configuration.m_tilingY, 0.0f); } else { @@ -353,6 +392,10 @@ namespace GradientSignal { AZStd::unique_lock imageLock(m_imageMutex); + + // Clear our cached image data + m_imageData = AZStd::span(); + m_configuration.m_imageAsset = AZ::Data::AssetManager::Instance().FindOrCreateAsset(assetId, azrtti_typeid(), m_configuration.m_imageAsset.GetAutoLoadBehavior()); } diff --git a/Gems/GradientSignal/Code/Source/ImageAsset.cpp b/Gems/GradientSignal/Code/Source/ImageAsset.cpp index 0f91a3ea08..05ad13d193 100644 --- a/Gems/GradientSignal/Code/Source/ImageAsset.cpp +++ b/Gems/GradientSignal/Code/Source/ImageAsset.cpp @@ -78,11 +78,10 @@ namespace GradientSignal return true; } - float GetValueFromImageAsset(const AZ::Data::Asset& imageAsset, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue) + float GetValueFromImageAsset(AZStd::span imageData, const AZ::RHI::ImageDescriptor& imageDescriptor, const AZ::Vector3& uvw, float tilingX, float tilingY, float defaultValue) { - if (imageAsset.IsReady()) + if (!imageData.empty()) { - auto imageDescriptor = imageAsset->GetImageDescriptor(); auto width = imageDescriptor.m_size.m_width; auto height = imageDescriptor.m_size.m_height; @@ -125,7 +124,7 @@ namespace GradientSignal // Flip the y because images are stored in reverse of our world axes y = (height - 1) - y; - return AZ::RPI::GetSubImagePixelValue(imageAsset, x, y); + return AZ::RPI::GetImageDataPixelValue(imageData, imageDescriptor, x, y); } } From f74e980659f12361337f37df722abc47948b7932 Mon Sep 17 00:00:00 2001 From: carlitosan <82187351+carlitosan@users.noreply.github.com> Date: Wed, 9 Feb 2022 10:23:16 -0800 Subject: [PATCH 032/133] fix errors when generic nodes fail to add slots (#7508) Signed-off-by: carlitosan <82187351+carlitosan@users.noreply.github.com> --- .../Code/Include/ScriptCanvas/Core/Node.h | 7 ++--- .../ScriptCanvas/Core/NodeFunctionGeneric.h | 31 ++++++++++++++----- .../Libraries/Math/Vector2Nodes.h | 2 +- .../Libraries/Math/Vector3Nodes.h | 11 ++++++- .../Libraries/Math/Vector4Nodes.h | 2 +- 5 files changed, 38 insertions(+), 15 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.h index f8b4ca7264..4cafd97237 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Node.h @@ -1098,7 +1098,7 @@ protected: slotConfiguration.SetType(Data::FromAZType>()); slotConfiguration.SetConnectionType(ConnectionType::Output); - node.AddSlot(slotConfiguration); + AZ_VerifyError("ScriptCanvas", node.AddSlot(slotConfiguration).IsValid(), "Node failed to add a required Data Out slot"); } }; @@ -1115,12 +1115,11 @@ protected: static void CreateDataSlot(Node& node, ConnectionType connectionType) { DataSlotConfiguration slotConfiguration; - slotConfiguration.m_name = t_Traits::GetResultName(Index); slotConfiguration.SetType(Data::FromAZType>>()); - slotConfiguration.SetConnectionType(connectionType); - node.AddSlot(slotConfiguration); + + AZ_VerifyError("ScriptCanvas", node.AddSlot(slotConfiguration).IsValid(), "Node failed to add a required Data Out slot"); } template diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeFunctionGeneric.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeFunctionGeneric.h index 549c56d07d..102b255cda 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeFunctionGeneric.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/NodeFunctionGeneric.h @@ -82,15 +82,30 @@ namespace ScriptCanvas static const size_t s_numNames = SCRIPT_CANVAS_FUNCTION_VAR_ARGS(__VA_ARGS__);\ /*static const size_t s_numResults = ScriptCanvas::Internal::extended_tuple_size::value;*/\ \ - static const char* GetArgName(size_t i)\ + static AZStd::string GetArgName(size_t i)\ {\ - return GetName(i).data();\ + AZStd::string_view argName = GetName(i);\ + if (!argName.empty())\ + {\ + return argName;\ + }\ + else\ + {\ + return AZStd::string::format("Input [%zu]", i);\ + }\ }\ \ - static const char* GetResultName(size_t i)\ + static AZStd::string GetResultName(size_t i)\ {\ - AZStd::string_view result = GetName(i + s_numArgs);\ - return !result.empty() ? result.data() : "Result";\ + AZStd::string_view resultName = GetName(i + s_numArgs);\ + if (!resultName.empty())\ + {\ + return resultName;\ + }\ + else\ + {\ + return AZStd::string::format("Result [%zu]", i);\ + }\ }\ \ static const char* GetDependency() { return CATEGORY; }\ @@ -260,7 +275,7 @@ namespace ScriptCanvas slotConfiguration.ConfigureDatum(AZStd::move(Datum(Data::FromAZType(Data::Traits::GetAZType()), Datum::eOriginality::Copy))); slotConfiguration.SetConnectionType(connectionType); - AddSlot(slotConfiguration); + AZ_VerifyError("ScriptCanvas", AddSlot(slotConfiguration).IsValid(), "NodeFunctionGenericMultiReturn failed to add a required data slot"); } template @@ -278,12 +293,12 @@ namespace ScriptCanvas { { ExecutionSlotConfiguration slotConfiguration("In", ConnectionType::Input); - AddSlot(slotConfiguration); + AZ_VerifyError("ScriptCanvas", AddSlot(slotConfiguration).IsValid(), "NodeFunctionGenericMultiReturn failed to add a required Execution In slot"); } { ExecutionSlotConfiguration slotConfiguration("Out", ConnectionType::Output); - AddSlot(slotConfiguration); + AZ_VerifyError("ScriptCanvas", AddSlot(slotConfiguration).IsValid(), "NodeFunctionGenericMultiReturn failed to add a required Execution Out slot"); } AddInputDatumSlotHelper(typename AZStd::function_traits::arg_sequence{}, AZStd::make_index_sequence::arity>{}); diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector2Nodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector2Nodes.h index 9a389404a2..760610b10e 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector2Nodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector2Nodes.h @@ -257,7 +257,7 @@ namespace ScriptCanvas r.SetLength(static_cast(optionalScale)); return std::make_tuple(r, length); } - SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(DirectionTo, DirectionToDefaults, k_categoryName, "{49A2D7F6-6CD3-420E-8A79-D46B00DB6CED}", "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0", "From", "To", "Scale"); + SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(DirectionTo, DirectionToDefaults, k_categoryName, "{49A2D7F6-6CD3-420E-8A79-D46B00DB6CED}", "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0", "From", "To", "Scale", "Direction", "Length"); using Registrar = RegistrarGeneric < AbsoluteNode diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector3Nodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector3Nodes.h index f5e09ef78f..30e6643d44 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector3Nodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector3Nodes.h @@ -343,8 +343,17 @@ namespace ScriptCanvas r.SetLength(static_cast(optionalScale)); return std::make_tuple(r, length); } - SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(DirectionTo, DirectionToDefaults, k_categoryName, "{28FBD529-4C9A-4E34-B8A0-A13B5DB3C331}", "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0", "From", "To", "Scale"); + SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS + ( DirectionTo + , DirectionToDefaults + , k_categoryName, "{28FBD529-4C9A-4E34-B8A0-A13B5DB3C331}" + , "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0" + , "From" + , "To" + , "Scale" + , "Direction" + , "Length"); using Registrar = RegistrarGeneric < AbsoluteNode diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector4Nodes.h b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector4Nodes.h index 30e1b691bf..39e9718824 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector4Nodes.h +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/Libraries/Math/Vector4Nodes.h @@ -228,7 +228,7 @@ namespace ScriptCanvas r.SetLength(static_cast(optionalScale)); return std::make_tuple(r, length); } - SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(DirectionTo, DirectionToDefaults, k_categoryName, "{463762DE-E541-4AFE-80C2-FED1C5273319}", "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0", "From", "To", "Scale"); + SCRIPT_CANVAS_GENERIC_FUNCTION_NODE_WITH_DEFAULTS(DirectionTo, DirectionToDefaults, k_categoryName, "{463762DE-E541-4AFE-80C2-FED1C5273319}", "Returns a direction vector between two points and the distance between them, by default the direction will be normalized, but it may be optionally scaled using the Scale parameter if different from 1.0", "From", "To", "Scale", "Direction", "Length"); using Registrar = RegistrarGeneric < AbsoluteNode, From f5463bd9031e1b9d8453057c19ab96d713c84b38 Mon Sep 17 00:00:00 2001 From: sweeneys Date: Wed, 9 Feb 2022 10:40:11 -0800 Subject: [PATCH 033/133] Prevent unsafe calls to AssetProcessor Signed-off-by: sweeneys --- .../automatedtesting_shared/base.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/base.py b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/base.py index e59282c97b..034930484e 100755 --- a/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/base.py +++ b/AutomatedTesting/Gem/PythonTests/automatedtesting_shared/base.py @@ -49,9 +49,11 @@ class TestAutomationBase: time_info_str += f"{testcase_name}: (Full:{t} sec, Editor:{editor_t} sec)\n" logger.info(time_info_str) + if cls.asset_processor is not None: + cls.asset_processor.teardown() + # Kill all ly processes - cls.asset_processor.teardown() - cls._kill_ly_processes() + cls._kill_ly_processes(include_asset_processor=True) def _run_test(self, request, workspace, editor, testcase_module, extra_cmdline_args=[], batch_mode=True, autotest_mode=True, use_null_renderer=True, enable_prefab_system=True): @@ -62,14 +64,16 @@ class TestAutomationBase: ######### # Setup # - if self.asset_processor is None: + self._kill_ly_processes(include_asset_processor=True) self.__class__.asset_processor = AssetProcessor(workspace) self.asset_processor.backup_ap_settings() - - self._kill_ly_processes(include_asset_processor=False) - self.asset_processor.start() - self.asset_processor.wait_for_idle() + else: + self._kill_ly_processes(include_asset_processor=False) + + if not self.asset_processor.process_exists(): + self.asset_processor.start() + self.asset_processor.wait_for_idle() def teardown(): if os.path.exists(workspace.paths.editor_log()): From 2e762ba0eb2c916b0acdb9a5fa29537922190cc6 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Wed, 9 Feb 2022 14:35:34 -0600 Subject: [PATCH 034/133] Modified activate logic from PR feedback Signed-off-by: Chris Galvan --- .../Components/ImageGradientComponent.cpp | 20 ++++++------------- 1 file changed, 6 insertions(+), 14 deletions(-) diff --git a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp index 39a456a277..0bf914fea3 100644 --- a/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Components/ImageGradientComponent.cpp @@ -234,21 +234,13 @@ namespace GradientSignal ImageGradientRequestBus::Handler::BusConnect(GetEntityId()); GradientRequestBus::Handler::BusConnect(GetEntityId()); - AZ::Data::AssetBus::Handler::BusConnect(m_configuration.m_imageAsset.GetId()); - // If the image asset is already ready (e.g. constructed in a unit test), - // then go ahead and retrieve the image data now - AZStd::unique_lock imageLock(m_imageMutex); - if (m_configuration.m_imageAsset.IsReady()) - { - GetSubImageData(); - } - // Otherwise for normal use-case, we queue the asset to be loaded now - else - { - m_imageData = AZStd::span(); - m_configuration.m_imageAsset.QueueLoad(); - } + // Invoke the QueueLoad before connecting to the AssetBus, so that + // if the asset is already ready, then OnAssetReady will be triggered immediately + m_imageData = AZStd::span(); + m_configuration.m_imageAsset.QueueLoad(); + + AZ::Data::AssetBus::Handler::BusConnect(m_configuration.m_imageAsset.GetId()); } void ImageGradientComponent::Deactivate() From 8fbd2aaaf56573fce07ddb6376c12179137d5ca8 Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Wed, 9 Feb 2022 13:13:40 -0800 Subject: [PATCH 035/133] Tied up a few loose ends to support deeply nested property groups. Simplified the call back for MaterialTypeSourceData::EnumeratePropertyGroups while also providing more data. Made the Material Inspector join nested property group display names to be like "Layer 1 | Base Color", since the leaf property groups are shown as a flat list in the inspector. Fixed CreateMaterialAssetFromSourceData to include the imported json files in the list of sourceDependencies. This triggers the Material Editor to hot-reload when one of these json files changes. Updated a few places that were still assuming only one level of property group. Updated EditorMaterialComponentInspector to apply the per-property-group material functors, before it was still only applying the top-level onces. Moved some accessor function implementations to the cpp files, per feedback on another already-merged PR. Testing: Made changes to MinimalMultilayerPbr (in AtomSampleViewer) to use nested property groups, and saw the correct behavior in the Material Editor's property inspector. Used MaterialComponent's property inspector to edit a StandardPbr material instance. Confrimed that functors were correctly controlling property visibility by enabling and disabling things like emissive and clear coat. Used MaterialComponent's property inspector to edit a MinimalMultilayerPbr material instance. Saw all the expected groups and properties show up. Confirmed that per-group functors were correctly controlling property visibility. Used MaterialComponent's property inspector to export a material instance and confirmed the .material file included the expected properties. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../Material/MaterialTypeSourceData.h | 37 +++-- .../Material/MaterialNameContext.h | 6 +- .../RPI.Edit/Material/MaterialSourceData.cpp | 2 +- .../Material/MaterialTypeSourceData.cpp | 90 ++++++++-- .../Material/MaterialNameContext.cpp | 14 ++ .../Code/Source/Document/MaterialDocument.cpp | 40 +++-- .../EditorMaterialComponentInspector.cpp | 156 +++++++++++------- .../EditorMaterialComponentInspector.h | 4 + .../Material/EditorMaterialComponentUtil.cpp | 4 +- 9 files changed, 241 insertions(+), 112 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h index 900a57746a..507652b9fa 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h @@ -131,15 +131,17 @@ namespace AZ PropertyGroup() = default; AZ_DISABLE_COPY(PropertyGroup) - const AZStd::string& GetName() const { return m_name; } - const AZStd::string& GetDisplayName() const { return m_displayName; } - const AZStd::string& GetDescription() const { return m_description; } - const PropertyList& GetProperties() const { return m_properties; } - const AZStd::vector>& GetPropertyGroups() const { return m_propertyGroups; } - const AZStd::vector>& GetFunctors() const { return m_materialFunctorSourceData; } + const AZStd::string& GetName() const; + const AZStd::string& GetDisplayName() const; + const AZStd::string& GetDescription() const; + const PropertyList& GetProperties() const; + const AZStd::string& GetShaderInputsPrefix() const; + const AZStd::string& GetShaderOptionsPrefix() const; + const AZStd::vector>& GetPropertyGroups() const; + const AZStd::vector>& GetFunctors() const; - void SetDisplayName(AZStd::string_view displayName) { m_displayName = displayName; } - void SetDescription(AZStd::string_view description) { m_description = description; } + void SetDisplayName(AZStd::string_view displayName); + void SetDescription(AZStd::string_view description); //! Add a new property to this PropertyGroup. //! @param name a unique for the property. Must be a C-style identifier. @@ -281,13 +283,13 @@ namespace AZ //! Splits an ID string like "itemA.itemB.itemC" into a vector like ["itemA.itemB", "itemC"]. static AZStd::vector SplitId(AZStd::string_view id); + //! Describes a path in the hierarchy of property groups, with the top level group at the beginning and a leaf-most group at the end. + using PropertyGroupStack = AZStd::vector; + //! Call back function type used with the enumeration functions. + //! The PropertyGroupStack contains the stack of property groups at the current point in the traversal. //! Return false to terminate the traversal. - using EnumeratePropertyGroupsCallback = AZStd::function; + using EnumeratePropertyGroupsCallback = AZStd::function; //! Recursively traverses all of the property groups contained in the material type, executing a callback function for each. //! @return false if the enumeration was terminated early by the callback returning false. @@ -304,6 +306,9 @@ namespace AZ //! @return false if the enumeration was terminated early by the callback returning false. bool EnumerateProperties(const EnumeratePropertiesCallback& callback) const; + //! Returns a MaterialNameContext for a specific path through the property group hierarchy. + static MaterialNameContext MakeMaterialNameContext(const MaterialTypeSourceData::PropertyGroupStack& propertyGroupStack); + Outcome> CreateMaterialTypeAsset(Data::AssetId assetId, AZStd::string_view materialTypeSourceFilePath = "", bool elevateWarnings = true) const; //! If the data was loaded from an old format file (i.e. where "groups" and "properties" were separate sections), @@ -319,10 +324,10 @@ namespace AZ PropertyDefinition* FindProperty(AZStd::span parsedPropertyId, AZStd::span> inPropertyGroupList); // Function overloads for recursion, returns false to indicate that recursion should end. - bool EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const; + bool EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, PropertyGroupStack* propertyGroupStack, const AZStd::vector>& inPropertyGroupList) const; bool EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const; - static MaterialNameContext ExtendNameContext(MaterialNameContext nameContext, const MaterialTypeSourceData::PropertyGroup& propertyGroup); + static void ExtendNameContext(MaterialNameContext& nameContext, const MaterialTypeSourceData::PropertyGroup& propertyGroup); //! Recursively populates a material type asset with properties from the tree of material property groups. //! @param materialTypeSourceFilePath path to the material type file that is being processed, used to look up relative paths @@ -342,7 +347,7 @@ namespace AZ PropertyLayout m_propertyLayout; }; - + //! The wrapper class for derived material functors. //! It is used in deserialization so that derived material functors can be deserialized by name. class MaterialFunctorSourceDataHolder final diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h index 124d73ad7a..ac6adffe2b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Material/MaterialNameContext.h @@ -45,9 +45,9 @@ namespace AZ bool ContextualizeShaderOption(AZStd::string& shaderOptionName) const; //! Returns true if there is some non-default name context. - bool HasContextForProperties() const { return !m_propertyIdContext.empty(); } - bool HasContextForSrgInputs() const { return !m_srgInputNameContext.empty(); } - bool HasContextForShaderOptions() const { return !m_shaderOptionNameContext.empty(); } + bool HasContextForProperties() const; + bool HasContextForSrgInputs() const; + bool HasContextForShaderOptions() const; //! Returns true if the name context is empty. bool IsDefault() const; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp index 7f2c13515a..91a7092362 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceData.cpp @@ -262,7 +262,7 @@ namespace AZ return Failure(); } - auto materialTypeLoadOutcome = MaterialUtils::LoadMaterialTypeSourceData(materialTypeSourcePath); + auto materialTypeLoadOutcome = MaterialUtils::LoadMaterialTypeSourceData(materialTypeSourcePath, nullptr, sourceDependencies); if (!materialTypeLoadOutcome) { AZ_Error("MaterialSourceData", false, "Failed to load MaterialTypeSourceData: '%s'.", materialTypeSourcePath.c_str()); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp index 6bcaa5d519..9153120732 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp @@ -157,6 +157,56 @@ namespace AZ toPropertyGroupList.back()->m_name = name; return toPropertyGroupList.back().get(); } + + const AZStd::string& MaterialTypeSourceData::PropertyGroup::GetName() const + { + return m_name; + } + + const AZStd::string& MaterialTypeSourceData::PropertyGroup::GetDisplayName() const + { + return m_displayName; + } + + const AZStd::string& MaterialTypeSourceData::PropertyGroup::GetDescription() const + { + return m_description; + } + + const MaterialTypeSourceData::PropertyList& MaterialTypeSourceData::PropertyGroup::GetProperties() const + { + return m_properties; + } + + const AZStd::string& MaterialTypeSourceData::PropertyGroup::GetShaderInputsPrefix() const + { + return m_shaderInputsPrefix; + } + + const AZStd::string& MaterialTypeSourceData::PropertyGroup::GetShaderOptionsPrefix() const + { + return m_shaderOptionsPrefix; + } + + const AZStd::vector>& MaterialTypeSourceData::PropertyGroup::GetPropertyGroups() const + { + return m_propertyGroups; + } + + const AZStd::vector>& MaterialTypeSourceData::PropertyGroup::GetFunctors() const + { + return m_materialFunctorSourceData; + } + + void MaterialTypeSourceData::PropertyGroup::SetDisplayName(AZStd::string_view displayName) + { + m_displayName = displayName; + } + + void MaterialTypeSourceData::PropertyGroup::SetDescription(AZStd::string_view description) + { + m_description = description; + } MaterialTypeSourceData::PropertyDefinition* MaterialTypeSourceData::PropertyGroup::AddProperty(AZStd::string_view name) { @@ -377,21 +427,23 @@ namespace AZ return parts; } - bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const + bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, PropertyGroupStack* propertyGroupStack, const AZStd::vector>& inPropertyGroupList) const { for (auto& propertyGroup : inPropertyGroupList) { - MaterialNameContext groupNameContext = ExtendNameContext(nameContext, *propertyGroup); + propertyGroupStack->push_back(propertyGroup.get()); - if (!callback(propertyGroup.get(), groupNameContext, nameContext)) + if (!callback(*propertyGroupStack)) { return false; // Stop processing } - if (!EnumeratePropertyGroups(callback, groupNameContext, propertyGroup->m_propertyGroups)) + if (!EnumeratePropertyGroups(callback, propertyGroupStack, propertyGroup->m_propertyGroups)) { return false; // Stop processing } + + propertyGroupStack->pop_back(); } return true; @@ -404,14 +456,16 @@ namespace AZ return false; } - return EnumeratePropertyGroups(callback, {}, m_propertyLayout.m_propertyGroups); + PropertyGroupStack propertyGroupStack; + return EnumeratePropertyGroups(callback, &propertyGroupStack, m_propertyLayout.m_propertyGroups); } bool MaterialTypeSourceData::EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const { for (auto& propertyGroup : inPropertyGroupList) { - MaterialNameContext groupNameContext = ExtendNameContext(nameContext, *propertyGroup); + MaterialNameContext groupNameContext = nameContext; + ExtendNameContext(groupNameContext, *propertyGroup); for (auto& property : propertyGroup->m_properties) { @@ -529,13 +583,21 @@ namespace AZ return groupDefinitions; } - MaterialNameContext MaterialTypeSourceData::ExtendNameContext(MaterialNameContext nameContext, const MaterialTypeSourceData::PropertyGroup& propertyGroup) + void MaterialTypeSourceData::ExtendNameContext(MaterialNameContext& nameContext, const MaterialTypeSourceData::PropertyGroup& propertyGroup) { - MaterialNameContext materialNameContext2 = nameContext; - materialNameContext2.ExtendPropertyIdContext(propertyGroup.m_name); - materialNameContext2.ExtendShaderOptionContext(propertyGroup.m_shaderOptionsPrefix); - materialNameContext2.ExtendSrgInputContext(propertyGroup.m_shaderInputsPrefix); - return materialNameContext2; + nameContext.ExtendPropertyIdContext(propertyGroup.m_name); + nameContext.ExtendShaderOptionContext(propertyGroup.m_shaderOptionsPrefix); + nameContext.ExtendSrgInputContext(propertyGroup.m_shaderInputsPrefix); + } + + /*static*/ MaterialNameContext MaterialTypeSourceData::MakeMaterialNameContext(const MaterialTypeSourceData::PropertyGroupStack& propertyGroupStack) + { + MaterialNameContext nameContext; + for (auto& group : propertyGroupStack) + { + ExtendNameContext(nameContext, *group); + } + return nameContext; } bool MaterialTypeSourceData::BuildPropertyList( @@ -549,7 +611,7 @@ namespace AZ return false; } - materialNameContext = ExtendNameContext(materialNameContext, *propertyGroup); + ExtendNameContext(materialNameContext, *propertyGroup); for (const AZStd::unique_ptr& property : propertyGroup->m_properties) { @@ -886,6 +948,6 @@ namespace AZ return Failure(); } } - + } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp index 5846c60e05..9ef97c8785 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/MaterialNameContext.cpp @@ -117,6 +117,20 @@ namespace AZ shaderOptionName = m_shaderOptionNameContext + shaderOptionName; return true; } + + bool MaterialNameContext::HasContextForProperties() const + { + return !m_propertyIdContext.empty(); + } + bool MaterialNameContext::HasContextForSrgInputs() const + { + return !m_srgInputNameContext.empty(); + } + + bool MaterialNameContext::HasContextForShaderOptions() const + { + return !m_shaderOptionNameContext.empty(); + } } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index 5605917e42..d122a7fff4 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -354,9 +354,7 @@ namespace MaterialEditor return false; } - // TODO: Support populating the Material Editor with nested property groups, not just the top level. - AZStd::string_view groupName = propertyId.GetStringView().substr(0, propertyId.GetStringView().size() - propertyDefinition->GetName().size() - 1); - sourceData.SetPropertyValue(AZ::RPI::MaterialPropertyId{groupName, propertyDefinition->GetName()}, propertyValue); + sourceData.SetPropertyValue(propertyId, propertyValue); } } return true; @@ -553,27 +551,38 @@ namespace MaterialEditor // Assets must still be used for now because they contain the final accumulated value after all other materials // in the hierarchy are applied bool enumerateResult = m_materialTypeSourceData.EnumeratePropertyGroups( - [this, &parentPropertyValues]( - const AZ::RPI::MaterialTypeSourceData::PropertyGroup* propertyGroup, - const AZ::RPI::MaterialNameContext& groupNameContext, - const AZ::RPI::MaterialNameContext& parentNameContext) + [this, &parentPropertyValues](const AZ::RPI::MaterialTypeSourceData::PropertyGroupStack& propertyGroupStack) { - // Add any material functors that are located inside each property group. + using namespace AZ::RPI; + + const MaterialTypeSourceData::PropertyGroup* propertyGroup = propertyGroupStack.back(); + + MaterialNameContext groupNameContext = MaterialTypeSourceData::MakeMaterialNameContext(propertyGroupStack); + if (!AddEditorMaterialFunctors(propertyGroup->GetFunctors(), groupNameContext)) { return false; } - + + AZStd::vector groupNameVector; + AZStd::vector groupDisplayNameVector; + + for (auto& group : propertyGroupStack) + { + groupNameVector.push_back(group->GetName()); + groupDisplayNameVector.push_back(group->GetDisplayName()); + } + m_groups.emplace_back(aznew AtomToolsFramework::DynamicPropertyGroup); - m_groups.back()->m_name = propertyGroup->GetName(); - parentNameContext.ContextualizeProperty(m_groups.back()->m_name); - m_groups.back()->m_displayName = propertyGroup->GetDisplayName(); m_groups.back()->m_description = propertyGroup->GetDescription(); + AzFramework::StringFunc::Join(m_groups.back()->m_name, groupNameVector.begin(), groupNameVector.end(), "."); + AzFramework::StringFunc::Join(m_groups.back()->m_displayName, groupDisplayNameVector.begin(), groupDisplayNameVector.end(), " | "); for (const auto& propertyDefinition : propertyGroup->GetProperties()) { - // Assign id before conversion so it can be used in dynamic description AtomToolsFramework::DynamicPropertyConfig propertyConfig; + + // Assign id before conversion so it can be used in dynamic description propertyConfig.m_id = propertyDefinition->GetName(); groupNameContext.ContextualizeProperty(propertyConfig.m_id); @@ -587,9 +596,8 @@ namespace MaterialEditor if (propertyIndexInBounds) { AtomToolsFramework::ConvertToPropertyConfig(propertyConfig, *propertyDefinition); - - // TODO: Support populating the Material Editor with nested property groups, not just the top level. - // (Does DynamicPropertyConfig really even need m_groupDisplayName?) + + // (Does DynamicPropertyConfig really even need m_groupName? It doesn't seem to be used anywhere) propertyConfig.m_groupName = m_groups.back()->m_name; propertyConfig.m_groupDisplayName = m_groups.back()->m_displayName; propertyConfig.m_showThumbnail = true; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 376aba2208..1c6410f8c3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -102,29 +102,10 @@ namespace AZ UnloadMaterial(); return false; } + + // Add material functors that are in the top-level functors list. Other functors are also added per-property-group elsewhere. + AddEditorMaterialFunctors(m_editData.m_materialTypeSourceData.m_materialFunctorSourceData, AZ::RPI::MaterialNameContext{}); - // Get a list of all the editor functors to be used for property editor states - auto propertyLayout = m_editData.m_materialAsset->GetMaterialPropertiesLayout(); - AZ::RPI::MaterialNameContext materialNameContext; // There is no name context for top-level functors, only functors inside PropertyGroups - const AZ::RPI::MaterialFunctorSourceData::EditorContext editorContext = - AZ::RPI::MaterialFunctorSourceData::EditorContext(m_editData.m_materialTypeSourcePath, propertyLayout, &materialNameContext); - for (AZ::RPI::Ptr functorData : m_editData.m_materialTypeSourceData.m_materialFunctorSourceData) - { - AZ::RPI::MaterialFunctorSourceData::FunctorResult createResult = functorData->CreateFunctor(editorContext); - - if (createResult.IsSuccess()) - { - AZ::RPI::Ptr& functor = createResult.GetValue(); - if (functor != nullptr) - { - m_editorFunctors.push_back(functor); - } - } - else - { - AZ_Error("AZ::Render::EditorMaterialComponentInspector", false, "Material functors were not created: '%s'.", m_editData.m_materialTypeSourcePath.c_str()); - } - } Populate(); LoadOverridesFromEntity(); @@ -295,47 +276,73 @@ namespace AZ void MaterialPropertyInspector::AddPropertiesGroup() { // Copy all of the properties from the material asset to the source data that will be exported - // TODO: Support populating the Material Editor with nested property groups, not just the top level. - for (const AZStd::unique_ptr& propertyGroup : m_editData.m_materialTypeSourceData.GetPropertyLayout().m_propertyGroups) - { - const AZStd::string& groupName = propertyGroup->GetName(); - const AZStd::string& groupDisplayName = !propertyGroup->GetDisplayName().empty() ? propertyGroup->GetDisplayName() : groupName; - const AZStd::string& groupDescription = !propertyGroup->GetDescription().empty() ? propertyGroup->GetDescription() : groupDisplayName; - auto& group = m_groups[groupName]; - - group.m_properties.reserve(propertyGroup->GetProperties().size()); - for (const auto& propertyDefinition : propertyGroup->GetProperties()) + m_editData.m_materialTypeSourceData.EnumeratePropertyGroups( + [this](const AZ::RPI::MaterialTypeSourceData::PropertyGroupStack& propertyGroupStack) { - AtomToolsFramework::DynamicPropertyConfig propertyConfig; + using namespace AZ::RPI; - // Assign id before conversion so it can be used in dynamic description - propertyConfig.m_id = AZ::RPI::MaterialPropertyId(groupName, propertyDefinition->GetName()); - - AtomToolsFramework::ConvertToPropertyConfig(propertyConfig, *propertyDefinition.get()); - - const auto& propertyIndex = - m_editData.m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); + const MaterialTypeSourceData::PropertyGroup* propertyGroupDefinition = propertyGroupStack.back(); + + MaterialNameContext groupNameContext = MaterialTypeSourceData::MakeMaterialNameContext(propertyGroupStack); - propertyConfig.m_groupName = groupDisplayName; - propertyConfig.m_showThumbnail = true; - propertyConfig.m_defaultValue = AtomToolsFramework::ConvertToEditableType( - m_editData.m_materialTypeAsset->GetDefaultPropertyValues()[propertyIndex.GetIndex()]); - - // There is no explicit parent material here. Material instance property overrides replace the values from the - // assigned material asset. Its values should be treated as parent, for comparison, in this case. - propertyConfig.m_parentValue = AtomToolsFramework::ConvertToEditableType( - m_editData.m_materialTypeAsset->GetDefaultPropertyValues()[propertyIndex.GetIndex()]); - propertyConfig.m_originalValue = AtomToolsFramework::ConvertToEditableType( - m_editData.m_materialAsset->GetPropertyValues()[propertyIndex.GetIndex()]); - group.m_properties.emplace_back(propertyConfig); - } + AddEditorMaterialFunctors(propertyGroupDefinition->GetFunctors(), groupNameContext); - // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties - auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( - &group, &group, group.TYPEINFO_Uuid(), this, this, GetGroupSaveStateKey(groupName), {}, - [this](const auto node) { return GetInstanceNodePropertyIndicator(node); }, 0); - AddGroup(groupName, groupDisplayName, groupDescription, propertyGroupWidget); - } + AZStd::vector groupNameVector; + AZStd::vector groupDisplayNameVector; + + for (auto& group : propertyGroupStack) + { + groupNameVector.push_back(group->GetName()); + groupDisplayNameVector.push_back(!group->GetDisplayName().empty() ? group->GetDisplayName() : group->GetName()); + } + + AZStd::string groupId; + AzFramework::StringFunc::Join(groupId, groupNameVector.begin(), groupNameVector.end(), "."); + + auto& group = m_groups[groupId]; + group.m_name = groupId; + AzFramework::StringFunc::Join(group.m_displayName, groupDisplayNameVector.begin(), groupDisplayNameVector.end(), " | "); + group.m_description = !propertyGroupDefinition->GetDescription().empty() ? propertyGroupDefinition->GetDescription() : group.m_displayName; + + group.m_properties.reserve(propertyGroupDefinition->GetProperties().size()); + for (const auto& propertyDefinition : propertyGroupDefinition->GetProperties()) + { + AtomToolsFramework::DynamicPropertyConfig propertyConfig; + + // Assign id before conversion so it can be used in dynamic description + propertyConfig.m_id = propertyDefinition->GetName(); + groupNameContext.ContextualizeProperty(propertyConfig.m_id); + + AtomToolsFramework::ConvertToPropertyConfig(propertyConfig, *propertyDefinition); + + const auto& propertyIndex = + m_editData.m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); + + // (Does DynamicPropertyConfig really even need m_groupName? It doesn't seem to be used anywhere) + propertyConfig.m_groupName = group.m_name; + propertyConfig.m_groupDisplayName = group.m_displayName; + propertyConfig.m_showThumbnail = true; + + propertyConfig.m_defaultValue = AtomToolsFramework::ConvertToEditableType( + m_editData.m_materialTypeAsset->GetDefaultPropertyValues()[propertyIndex.GetIndex()]); + + // There is no explicit parent material here. Material instance property overrides replace the values from the + // assigned material asset. Its values should be treated as parent, for comparison, in this case. + propertyConfig.m_parentValue = AtomToolsFramework::ConvertToEditableType( + m_editData.m_materialTypeAsset->GetDefaultPropertyValues()[propertyIndex.GetIndex()]); + propertyConfig.m_originalValue = AtomToolsFramework::ConvertToEditableType( + m_editData.m_materialAsset->GetPropertyValues()[propertyIndex.GetIndex()]); + group.m_properties.emplace_back(propertyConfig); + } + + // Passing in same group as main and comparison instance to enable custom value comparison for highlighting modified properties + auto propertyGroupWidget = new AtomToolsFramework::InspectorPropertyGroupWidget( + &group, &group, group.TYPEINFO_Uuid(), this, this, GetGroupSaveStateKey(group.m_name), {}, + [this](const auto node) { return GetInstanceNodePropertyIndicator(node); }, 0); + AddGroup(group.m_name, group.m_displayName, group.m_description, propertyGroupWidget); + + return true; + }); } void MaterialPropertyInspector::Populate() @@ -435,6 +442,37 @@ namespace AZ // m_updatePreview should be set to true here for continuous preview updates as slider/color properties change but needs // throttling } + + bool MaterialPropertyInspector::AddEditorMaterialFunctors( + const AZStd::vector>& functorSourceDataHolders, + const AZ::RPI::MaterialNameContext& nameContext) + { + // Copied from MaterialDocument::AddEditorMaterialFunctors, should be refactored at some point + + const AZ::RPI::MaterialFunctorSourceData::EditorContext editorContext = AZ::RPI::MaterialFunctorSourceData::EditorContext( + m_editData.m_materialTypeSourcePath, m_editData.m_materialAsset->GetMaterialPropertiesLayout(), &nameContext); + + for (AZ::RPI::Ptr functorData : functorSourceDataHolders) + { + AZ::RPI::MaterialFunctorSourceData::FunctorResult result = functorData->CreateFunctor(editorContext); + + if (result.IsSuccess()) + { + AZ::RPI::Ptr& functor = result.GetValue(); + if (functor != nullptr) + { + m_editorFunctors.push_back(functor); + } + } + else + { + AZ_Error("MaterialDocument", false, "Material functors were not created: '%s'.", m_editData.m_materialTypeSourcePath.c_str()); + return false; + } + } + + return true; + } void MaterialPropertyInspector::RunEditorMaterialFunctors() { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h index 82f46ebc90..44f1fb3491 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.h @@ -108,6 +108,10 @@ namespace AZ void RunEditorMaterialFunctors(); void UpdateMaterialInstanceProperty(const AtomToolsFramework::DynamicProperty& property); + bool AddEditorMaterialFunctors( + const AZStd::vector>& functorSourceDataHolders, + const AZ::RPI::MaterialNameContext& nameContext); + AZ::Crc32 GetGroupSaveStateKey(const AZStd::string& groupName) const; bool IsInstanceNodePropertyModifed(const AzToolsFramework::InstanceDataNode* node) const; const char* GetInstanceNodePropertyIndicator(const AzToolsFramework::InstanceDataNode* node) const; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp index 35633068d5..88cbbba87b 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentUtil.cpp @@ -151,9 +151,7 @@ namespace AZ return true; } - // TODO: Support populating the Material Editor with nested property groups, not just the top level. - AZStd::string_view groupName = propertyId.GetStringView().substr(0, propertyId.GetStringView().size() - propertyDefinition->GetName().size() - 1); - exportData.SetPropertyValue(RPI::MaterialPropertyId{groupName, propertyDefinition->GetName()}, propertyValue); + exportData.SetPropertyValue(propertyId, propertyValue); return true; }); From f79fa57b4a350385b148230ef99628eb908f8ee8 Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Wed, 9 Feb 2022 16:09:08 -0600 Subject: [PATCH 036/133] Fix race condition crash with the gradient preview. (#7530) When duplicating an entity with a Gradient SurfaceData Component, it's possible to get a hang/crash due to a race condition between entity deactivation and the gradient preview job refresh. This change ensures that the preview job is canceled on deactivation. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> --- .../Source/Editor/EditorGradientSurfaceDataComponent.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Gems/GradientSignal/Code/Source/Editor/EditorGradientSurfaceDataComponent.cpp b/Gems/GradientSignal/Code/Source/Editor/EditorGradientSurfaceDataComponent.cpp index e318e0fdf6..692576b3b3 100644 --- a/Gems/GradientSignal/Code/Source/Editor/EditorGradientSurfaceDataComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Editor/EditorGradientSurfaceDataComponent.cpp @@ -11,6 +11,7 @@ #include #include #include +#include namespace GradientSignal { @@ -61,6 +62,12 @@ namespace GradientSignal void EditorGradientSurfaceDataComponent::Deactivate() { + // Make sure any previews for this entity aren't currently trying to refresh. Otherwise, the preview job could call + // back into our FilterFunc lambda below after the entity has already been destroyed. + AZ::EntityId canceledEntity; + GradientSignal::GradientPreviewRequestBus::EventResult( + canceledEntity, GetEntityId(), &GradientSignal::GradientPreviewRequestBus::Events::CancelRefresh); + // If the preview shouldn't be active, use an invalid entityId m_gradientEntityId = AZ::EntityId(); AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); From caae0b0ec383a533423e3ebbc46c2e4cd05ad683 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Wed, 9 Feb 2022 23:18:19 +0100 Subject: [PATCH 037/133] Motion Matching: Fix for test build on nightly linux builds (#7522) Signed-off-by: Benjamin Jillich --- Gems/MotionMatching/Code/CMakeLists.txt | 42 ++++++++++++------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/Gems/MotionMatching/Code/CMakeLists.txt b/Gems/MotionMatching/Code/CMakeLists.txt index ae613f5d7f..22d2f28f3b 100644 --- a/Gems/MotionMatching/Code/CMakeLists.txt +++ b/Gems/MotionMatching/Code/CMakeLists.txt @@ -121,27 +121,27 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) ly_add_googletest( NAME Gem::MotionMatching.Tests ) -endif() -# If we are a host platform we want to add tools test like editor tests here -if(PAL_TRAIT_BUILD_HOST_TOOLS) - ly_add_target( - NAME MotionMatching.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE Gem - FILES_CMAKE - motionmatching_editor_tests_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Tests - Source - BUILD_DEPENDENCIES - PRIVATE - AZ::AzTest - Gem::MotionMatching.Editor - ) + # If we are a host platform we want to add tools test like editor tests here + if(PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_target( + NAME MotionMatching.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE Gem + FILES_CMAKE + motionmatching_editor_tests_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Tests + Source + BUILD_DEPENDENCIES + PRIVATE + AZ::AzTest + Gem::MotionMatching.Editor + ) - # Add MotionMatching.Editor.Tests to googletest - ly_add_googletest( - NAME Gem::MotionMatching.Editor.Tests - ) + # Add MotionMatching.Editor.Tests to googletest + ly_add_googletest( + NAME Gem::MotionMatching.Editor.Tests + ) + endif() endif() From 32f9e48ad466fa4f6097d3ee002b2e6a0dbb33f5 Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 9 Feb 2022 22:39:25 +0000 Subject: [PATCH 038/133] add more tests for collider offset and scale manipulators with non-uniform scale Signed-off-by: greerdv --- .../Tests/PhysXColliderComponentModeTests.cpp | 275 ++++++++++++++++++ 1 file changed, 275 insertions(+) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderComponentModeTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderComponentModeTests.cpp index 5722d1a397..e323110d6f 100644 --- a/Gems/PhysX/Code/Tests/PhysXColliderComponentModeTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXColliderComponentModeTests.cpp @@ -17,7 +17,9 @@ #include #include #include +#include #include +#include namespace UnitTest { @@ -437,4 +439,277 @@ namespace UnitTest EXPECT_NEAR(assetScale.GetY(), 1.0f, tolerance); EXPECT_NEAR(assetScale.GetZ(), 1.0f, tolerance); } + + class PhysXEditorColliderComponentFixture : public UnitTest::ToolsApplicationFixture + { + public: + void SetUpEditorFixtureImpl() override; + void TearDownEditorFixtureImpl() override; + void SetupTransform(const AZ::Quaternion& rotation, const AZ::Vector3& translation, float uniformScale); + void SetupCollider( + const Physics::ShapeConfiguration& shapeConfiguration, + const AZ::Quaternion& colliderRotation, + const AZ::Vector3& colliderOffset); + void SetupNonUniformScale(const AZ::Vector3& nonUniformScale); + void EnterColliderSubMode(PhysX::ColliderComponentModeRequests::SubMode subMode); + + AZ::Entity* m_entity = nullptr; + AZ::EntityComponentIdPair m_idPair; + }; + + void PhysXEditorColliderComponentFixture::SetUpEditorFixtureImpl() + { + AZ::SerializeContext* serializeContext = nullptr; + AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); + + UnitTest::CreateDefaultEditorEntity("EditorColliderComponentEntity", &m_entity); + } + + void PhysXEditorColliderComponentFixture::TearDownEditorFixtureImpl() + { + AzToolsFramework::EditorEntityContextRequestBus::Broadcast( + &AzToolsFramework::EditorEntityContextRequestBus::Events::DestroyEditorEntity, m_entity->GetId()); + m_entity = nullptr; + } + + void PhysXEditorColliderComponentFixture::SetupTransform( + const AZ::Quaternion& rotation, const AZ::Vector3& translation, float uniformScale) + { + const AZ::Transform transform = AZ::Transform::CreateFromQuaternionAndTranslation(rotation, translation); + AZ::TransformBus::Event(m_entity->GetId(), &AZ::TransformBus::Events::SetWorldTM, transform); + AZ::TransformBus::Event(m_entity->GetId(), &AZ::TransformBus::Events::SetLocalUniformScale, uniformScale); + } + + void PhysXEditorColliderComponentFixture::SetupCollider( + const Physics::ShapeConfiguration& shapeConfiguration, const AZ::Quaternion& colliderRotation, const AZ::Vector3& colliderOffset) + { + m_entity->Deactivate(); + auto* colliderComponent = + m_entity->CreateComponent(Physics::ColliderConfiguration(), shapeConfiguration); + m_entity->Activate(); + m_idPair = AZ::EntityComponentIdPair(m_entity->GetId(), colliderComponent->GetId()); + PhysX::EditorColliderComponentRequestBus::Event( + m_idPair, &PhysX::EditorColliderComponentRequests::SetColliderOffset, colliderOffset); + PhysX::EditorColliderComponentRequestBus::Event( + m_idPair, &PhysX::EditorColliderComponentRequests::SetColliderRotation, colliderRotation); + } + + void PhysXEditorColliderComponentFixture::SetupNonUniformScale(const AZ::Vector3& nonUniformScale) + { + m_entity->Deactivate(); + m_entity->CreateComponent(AzToolsFramework::Components::EditorNonUniformScaleComponent::RTTI_Type()); + m_entity->Activate(); + AZ::NonUniformScaleRequestBus::Event(m_entity->GetId(), &AZ::NonUniformScaleRequests::SetScale, nonUniformScale); + } + + void PhysXEditorColliderComponentFixture::EnterColliderSubMode(PhysX::ColliderComponentModeRequests::SubMode subMode) + { + AzToolsFramework::SelectEntity(m_entity->GetId()); + EnterComponentMode(); + PhysX::ColliderComponentModeRequestBus::Broadcast(&PhysX::ColliderComponentModeRequests::SetCurrentMode, subMode); + } + + using PhysXEditorColliderComponentManipulatorFixture = + UnitTest::IndirectCallManipulatorViewportInteractionFixtureMixin; + + // use a reasonably large tolerance because manipulator precision is limited by viewport resolution + static const float ManipulatorTolerance = 0.01f; + + TEST_F(PhysXEditorColliderComponentManipulatorFixture, OffsetManipulatorsCorrectlyLocatedRelativeToCollider) + { + const AZ::Vector3 boxDimensions(2.0f, 3.0f, 1.5f); + const AZ::Quaternion boxRotation(0.1f, 0.1f, 0.7f, 0.7f); + const AZ::Vector3 boxOffset(3.0f, 1.0f, 2.0f); + SetupCollider(Physics::BoxShapeConfiguration(boxDimensions), boxRotation, boxOffset); + const AZ::Quaternion entityRotation(0.8f, 0.2f, 0.4f, 0.4f); + const AZ::Vector3 entityTranslation(2.0f, -3.0f, 0.5f); + const float uniformScale = 2.0f; + SetupTransform(entityRotation, entityTranslation, uniformScale); + EnterColliderSubMode(PhysX::ColliderComponentModeRequests::SubMode::Offset); + + // the expected position of the collider centre based on the combination of entity transform and collider offset + const AZ::Vector3 expectedColliderPosition(8.8f, -2.28f, 3.54f); + + // the expected world space direction of the collider offset x-axis based on the entity transform + const AZ::Vector3 expectedXAxis(0.6f, 0.64f, 0.48f); + + // position the camera to look down at the collider from above + AzFramework::SetCameraTransform( + m_cameraState, + AZ::Transform::CreateFromQuaternionAndTranslation( + AZ::Quaternion::CreateRotationX(-AZ::Constants::HalfPi), expectedColliderPosition + AZ::Vector3::CreateAxisZ(10.0f))); + + // position in world space, slightly moved along the x-axis in order to grab the x translation manipulator + const AZ::Vector3 worldStart = expectedColliderPosition + 0.5f * expectedXAxis; + + // position in world space to move to + const AZ::Vector3 worldEnd = worldStart + 2.0f * expectedXAxis; + + const auto screenStart = AzFramework::WorldToScreen(worldStart, m_cameraState); + const auto screenEnd = AzFramework::WorldToScreen(worldEnd, m_cameraState); + + m_actionDispatcher + ->CameraState(m_cameraState) + // move the mouse to the position of the x offset manipulator + ->MousePosition(screenStart) + // drag to move the manipulator + ->MouseLButtonDown() + ->MousePosition(screenEnd) + ->MouseLButtonUp(); + + AZ::Vector3 newColliderOffset = AZ::Vector3::CreateZero(); + PhysX::EditorColliderComponentRequestBus::EventResult( + newColliderOffset, m_idPair, &PhysX::EditorColliderComponentRequests::GetColliderOffset); + + EXPECT_THAT(newColliderOffset, IsCloseTolerance(AZ::Vector3(4.0f, 1.0f, 2.0f), ManipulatorTolerance)); + } + + TEST_F(PhysXEditorColliderComponentManipulatorFixture, OffsetManipulatorsCorrectlyLocatedRelativeToColliderWithNonUniformScale) + { + const float capsuleRadius = 0.5f; + const float capsuleHeight = 2.0f; + const AZ::Quaternion capsuleRotation(0.2f, -0.4f, 0.8f, 0.4f); + const AZ::Vector3 capsuleOffset(-2.0f, 3.0f, -1.0f); + SetupCollider(Physics::CapsuleShapeConfiguration(capsuleHeight, capsuleRadius), capsuleRotation, capsuleOffset); + const AZ::Quaternion entityRotation(-0.1f, 0.7f, -0.7f, 0.1f); + const AZ::Vector3 entityTranslation(-1.0f, 1.0f, -2.5f); + const float uniformScale = 1.5f; + SetupTransform(entityRotation, entityTranslation, uniformScale); + const AZ::Vector3 nonUniformScale(2.0f, 0.5f, 1.5f); + SetupNonUniformScale(nonUniformScale); + EnterColliderSubMode(PhysX::ColliderComponentModeRequests::SubMode::Offset); + + // the expected position of the collider centre based on the combination of entity transform, collider offset and non-uniform scale + const AZ::Vector3 expectedColliderPosition(4.13f, 4.84f, -4.75f); + + // the expected world space direction of the collider offset z-axis based on the entity transform + const AZ::Vector3 expectedZAxis(0.28f, -0.96f, 0.0f); + + // position the camera to look at the collider from underneath + AzFramework::SetCameraTransform( + m_cameraState, + AZ::Transform::CreateFromQuaternionAndTranslation( + AZ::Quaternion::CreateRotationX(AZ::Constants::HalfPi), expectedColliderPosition - AZ::Vector3::CreateAxisZ(10.0f))); + + // position in world space, slightly moved along the z-axis in order to grab the z translation manipulator + // need to go in the negative z direction because the camera angle causes the manipulator to flip + const AZ::Vector3 worldStart = expectedColliderPosition - 0.5f * expectedZAxis; + + // position in world space to move to + const AZ::Vector3 worldEnd = worldStart - 2.25f * expectedZAxis; + + const auto screenStart = AzFramework::WorldToScreen(worldStart, m_cameraState); + const auto screenEnd = AzFramework::WorldToScreen(worldEnd, m_cameraState); + + m_actionDispatcher + ->CameraState(m_cameraState) + // move the mouse to the position of the z offset manipulator + ->MousePosition(screenStart) + // drag to move the manipulator + ->MouseLButtonDown() + ->MousePosition(screenEnd) + ->MouseLButtonUp(); + + AZ::Vector3 newColliderOffset = AZ::Vector3::CreateZero(); + PhysX::EditorColliderComponentRequestBus::EventResult( + newColliderOffset, m_idPair, &PhysX::EditorColliderComponentRequests::GetColliderOffset); + + EXPECT_THAT(newColliderOffset, IsCloseTolerance(AZ::Vector3(-2.0f, 3.0f, -2.0f), ManipulatorTolerance)); + } + + TEST_F(PhysXEditorColliderComponentManipulatorFixture, BoxColliderScaleManipulatorsCorrectlyLocatedRelativeToColliderWithNonUniformScale) + { + const AZ::Vector3 boxDimensions(2.0f, 2.0f, 3.0f); + const AZ::Quaternion boxRotation(0.7f, 0.7f, -0.1f, 0.1f); + const AZ::Vector3 boxOffset(0.5f, 1.5f, 2.0f); + SetupCollider(Physics::BoxShapeConfiguration(boxDimensions), boxRotation, boxOffset); + const AZ::Quaternion entityRotation(0.2f, 0.4f, -0.4f, 0.8f); + const AZ::Vector3 entityTranslation(2.0f, -3.0f, -2.0f); + const float uniformScale = 0.5f; + SetupTransform(entityRotation, entityTranslation, uniformScale); + const AZ::Vector3 nonUniformScale(3.0f, 1.5f, 2.5f); + SetupNonUniformScale(nonUniformScale); + EnterColliderSubMode(PhysX::ColliderComponentModeRequests::SubMode::Dimensions); + + // the expected position of the collider centre based on the combination of entity transform, collider offset and non-uniform scale + const AZ::Vector3 expectedColliderPosition(4.37f, -4.285f, -1.1f); + + // the expected position of the y scale manipulator relative to the centre of the collider, based on collider + // rotation, entity rotation and scale, and non-uniform scale + const AZ::Vector3 scaleManipulatorYDelta(0.54f, -0.72f, -1.2f); + + // position the camera to look at the collider along the x-y diagonal + AzFramework::SetCameraTransform( + m_cameraState, + AZ::Transform::CreateFromQuaternionAndTranslation( + AZ::Quaternion::CreateRotationZ(-AZ::Constants::QuarterPi), expectedColliderPosition - AZ::Vector3(2.0f, 2.0f, 0.0f))); + + const AZ::Vector3 worldStart = expectedColliderPosition + scaleManipulatorYDelta; + const AZ::Vector3 worldEnd = worldStart + 0.1f * scaleManipulatorYDelta; + + const auto screenStart = AzFramework::WorldToScreen(worldStart, m_cameraState); + const auto screenEnd = AzFramework::WorldToScreen(worldEnd, m_cameraState); + + m_actionDispatcher + ->CameraState(m_cameraState) + // move the mouse to the position of the y scale manipulator + ->MousePosition(screenStart) + // drag to move the manipulator + ->MouseLButtonDown() + ->MousePosition(screenEnd) + ->MouseLButtonUp(); + + AZ::Vector3 newBoxDimensions = AZ::Vector3::CreateZero(); + AzToolsFramework::BoxManipulatorRequestBus::EventResult( + newBoxDimensions, m_idPair, &AzToolsFramework::BoxManipulatorRequests::GetDimensions); + + EXPECT_THAT(newBoxDimensions, IsCloseTolerance(AZ::Vector3(2.0f, 2.2f, 3.0f), ManipulatorTolerance)); + } + + TEST_F(PhysXEditorColliderComponentManipulatorFixture, SphereColliderScaleManipulatorsCorrectlyLocatedRelativeToColliderWithNonUniformScale) + { + const float sphereRadius = 1.0f; + const AZ::Quaternion sphereRotation(-0.1f, 0.7f, -0.7f, 0.1f); + const AZ::Vector3 sphereOffset(-2.0f, 1.0f, -3.0f); + SetupCollider(Physics::SphereShapeConfiguration(sphereRadius), sphereRotation, sphereOffset); + const AZ::Quaternion entityRotation(-0.4f, -0.2f, 0.4f, 0.8f); + const AZ::Vector3 entityTranslation(-1.0f, -3.0f, 3.0f); + const float uniformScale = 1.5f; + SetupTransform(entityRotation, entityTranslation, uniformScale); + const AZ::Vector3 nonUniformScale(1.5f, 0.5f, 2.0f); + SetupNonUniformScale(nonUniformScale); + EnterColliderSubMode(PhysX::ColliderComponentModeRequests::SubMode::Dimensions); + + // the expected position of the collider centre based on the combination of entity transform, collider offset and non-uniform scale + const AZ::Vector3 expectedColliderPosition(1.7f, -10.65f, -3.0f); + + // position the camera to look at the collider along the y-axis + AzFramework::SetCameraTransform( + m_cameraState, AZ::Transform::CreateTranslation(expectedColliderPosition - AZ::Vector3(0.0f, 5.0f, 0.0f))); + + // the expected position of the scale manipulator relative to the centre of the collider, based on collider + // rotation, entity scale, non-uniform scale and camera state + const AZ::Vector3 scaleManipulatorDelta(-1.1952f, -1.8036f, 0.168f); + + const AZ::Vector3 worldStart = expectedColliderPosition + scaleManipulatorDelta; + const AZ::Vector3 worldEnd = worldStart - 0.1f * scaleManipulatorDelta; + + const auto screenStart = AzFramework::WorldToScreen(worldStart, m_cameraState); + const auto screenEnd = AzFramework::WorldToScreen(worldEnd, m_cameraState); + + m_actionDispatcher + ->CameraState(m_cameraState) + // move the mouse to the position of the y scale manipulator + ->MousePosition(screenStart) + // drag to move the manipulator + ->MouseLButtonDown() + ->MousePosition(screenEnd) + ->MouseLButtonUp(); + + float newSphereRadius = 0.0f; + PhysX::EditorColliderComponentRequestBus::EventResult( + newSphereRadius, m_idPair, &PhysX::EditorColliderComponentRequests::GetSphereRadius); + + EXPECT_NEAR(newSphereRadius, 0.9f, ManipulatorTolerance); + } } // namespace UnitTest From 51bac9a6c01426a5bd27904e3e9e8bfcd1622903 Mon Sep 17 00:00:00 2001 From: carlitosan <82187351+carlitosan@users.noreply.github.com> Date: Wed, 9 Feb 2022 14:45:56 -0800 Subject: [PATCH 039/133] remove code that loads member variables on SC editor component twice (#7506) * remove code that loads member variables on SC editor component twice Signed-off-by: carlitosan <82187351+carlitosan@users.noreply.github.com> * fix unused variable release build error Signed-off-by: carlitosan <82187351+carlitosan@users.noreply.github.com> --- .../Components/EditorScriptCanvasComponentSerializer.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Editor/Include/ScriptCanvas/Components/EditorScriptCanvasComponentSerializer.cpp b/Gems/ScriptCanvas/Code/Editor/Include/ScriptCanvas/Components/EditorScriptCanvasComponentSerializer.cpp index 596c2d9dbf..069b7a5f48 100644 --- a/Gems/ScriptCanvas/Code/Editor/Include/ScriptCanvas/Components/EditorScriptCanvasComponentSerializer.cpp +++ b/Gems/ScriptCanvas/Code/Editor/Include/ScriptCanvas/Components/EditorScriptCanvasComponentSerializer.cpp @@ -5,7 +5,7 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ - + #include #include #include @@ -17,7 +17,7 @@ namespace AZ JsonSerializationResult::Result EditorScriptCanvasComponentSerializer::Load ( void* outputValue - , const Uuid& outputValueTypeId + , [[maybe_unused]] const Uuid& outputValueTypeId , const rapidjson::Value& inputValue , JsonDeserializerContext& context) { @@ -32,9 +32,7 @@ namespace AZ JsonSerializationResult::ResultCode result = BaseJsonSerializer::Load(outputValue , azrtti_typeid(), inputValue, context); - // load child data one by one... - result.Combine(BaseJsonSerializer::Load(outputValue, outputValueTypeId, inputValue, context)); - + // load child data one by one if (result.GetProcessing() != JSR::Processing::Halted) { result.Combine(ContinueLoadingFromJsonObjectField From 4f06be88f61c6f0c1f22339d4b50dcf938ec1e3e Mon Sep 17 00:00:00 2001 From: puvvadar Date: Wed, 9 Feb 2022 15:11:32 -0800 Subject: [PATCH 040/133] Fix Rewindable volume bounds and missing component notification Signed-off-by: puvvadar --- Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index 59dddf5652..899640895d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -113,7 +113,7 @@ namespace Multiplayer NetworkEntityTracker* networkEntityTracker = GetNetworkEntityTracker(); AzFramework::IEntityBoundsUnion* entityBoundsUnion = AZ::Interface::Get(); AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(expandedVolume, - [this, debugDisplay, networkEntityTracker, entityBoundsUnion, rewindVolume](const AzFramework::IVisibilityScene::NodeData& nodeData) + [this, debugDisplay, networkEntityTracker, entityBoundsUnion, expandedVolume](const AzFramework::IVisibilityScene::NodeData& nodeData) { m_rewoundEntities.reserve(m_rewoundEntities.size() + nodeData.m_entries.size()); for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) @@ -156,9 +156,10 @@ namespace Multiplayer debugDisplay->DrawWireBox(rewoundAabb.GetMin(), rewoundAabb.GetMax()); } - if (AZ::ShapeIntersection::Overlaps(rewoundAabb, rewindVolume)) // Validate the rewound aabb intersects our rewind volume + if (AZ::ShapeIntersection::Overlaps(rewoundAabb, expandedVolume)) // Validate the rewound aabb intersects our rewind volume { m_rewoundEntities.push_back(entityHandle); + entityHandle.GetNetBindComponent()->NotifySyncRewindState(); } } } From 9d6062d96fb80d5fbed7550aecc909c278b585ba Mon Sep 17 00:00:00 2001 From: dmcdiarmid-ly <63674186+dmcdiarmid-ly@users.noreply.github.com> Date: Wed, 9 Feb 2022 16:18:43 -0700 Subject: [PATCH 041/133] Added an RPISystemInterface method to set the application-wide MSAA state The Editor will now properly apply the MSAA state from MainRenderPipeline.azasset Corrected a race condition with the cubemap baking pipeline Signed-off-by: dmcdiarmid-ly <63674186+dmcdiarmid-ly@users.noreply.github.com> --- .../Code/Source/BootstrapSystemComponent.cpp | 6 ++--- .../Passes/EnvironmentCubeMapDepthMSAA.pass | 6 ++--- .../DiffuseProbeGridRender.precompiledshader | 18 +++++++++++++ ...begridrender-nomsaa_dx12_0.azshadervariant | Bin 0 -> 29668 bytes ...begridrender-nomsaa_null_0.azshadervariant | Bin 0 -> 589 bytes ...gridrender-nomsaa_vulkan_0.azshadervariant | Bin 0 -> 24013 bytes .../diffuseprobegridrender.azshader | Bin 219075 -> 436794 bytes ...fuseprobegridrender_dx12_0.azshadervariant | Bin 30575 -> 30575 bytes ...fuseprobegridrender_null_0.azshadervariant | Bin 589 -> 589 bytes ...seprobegridrender_vulkan_0.azshadervariant | Bin 24081 -> 24081 bytes .../ReflectionProbe/ReflectionProbe.cpp | 16 ++++++++---- .../Source/ReflectionProbe/ReflectionProbe.h | 1 + .../ReflectionProbeFeatureProcessor.cpp | 12 +++++++++ .../ReflectionProbeFeatureProcessor.h | 1 + .../Code/Include/Atom/RPI.Public/RPISystem.h | 5 ++++ .../Atom/RPI.Public/RPISystemInterface.h | 4 +++ .../RPI/Code/Source/RPI.Public/RPISystem.cpp | 24 ++++++++++++++++++ .../PreviewRenderer/PreviewRenderer.cpp | 4 +-- 18 files changed, 82 insertions(+), 15 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender-nomsaa_dx12_0.azshadervariant create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender-nomsaa_null_0.azshadervariant create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender-nomsaa_vulkan_0.azshadervariant diff --git a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp index ef03a839d7..60ca6ff429 100644 --- a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp +++ b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp @@ -318,10 +318,8 @@ namespace AZ RPI::RenderPipelineDescriptor renderPipelineDescriptor = *RPI::GetDataFromAnyAsset(pipelineAsset); renderPipelineDescriptor.m_name = AZStd::string::format("%s_%i", renderPipelineDescriptor.m_name.c_str(), viewportContext->GetId()); - // Make sure non-msaa super variant is used for non-msaa pipeline - bool isNonMsaaPipeline = (renderPipelineDescriptor.m_renderSettings.m_multisampleState.m_samples == 1); - const char* supervariantName = isNonMsaaPipeline ? AZ::RPI::NoMsaaSupervariantName : ""; - AZ::RPI::ShaderSystemInterface::Get()->SetSupervariantName(AZ::Name(supervariantName)); + // The default pipeline determines the initial MSAA state for the application + AZ::RPI::RPISystemInterface::Get()->SetApplicationMultisampleState(renderPipelineDescriptor.m_renderSettings.m_multisampleState); if (!scene->GetRenderPipeline(AZ::Name(renderPipelineDescriptor.m_name))) { diff --git a/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapDepthMSAA.pass b/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapDepthMSAA.pass index 5abbe7d62d..cb94e75389 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapDepthMSAA.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/EnvironmentCubeMapDepthMSAA.pass @@ -34,11 +34,11 @@ "Attachment": "Output" } }, + "MultisampleSource": { + "Pass": "Pipeline" + }, "ImageDescriptor": { "Format": "D32_FLOAT_S8X24_UINT", - "MultisampleState": { - "samples": 4 - }, "SharedQueueMask": "Graphics" } } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRender.precompiledshader b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRender.precompiledshader index 97c58091a2..613714b0b6 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRender.precompiledshader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/DiffuseProbeGridRender.precompiledshader @@ -29,6 +29,24 @@ "RootShaderVariantAssetFileName": "diffuseprobegridrender_null_0.azshadervariant" } ] + }, + { + "Name": "NoMSAA", + "RootShaderVariantAssets": + [ + { + "APIName": "dx12", + "RootShaderVariantAssetFileName": "diffuseprobegridrender-nomsaa_dx12_0.azshadervariant" + }, + { + "APIName": "vulkan", + "RootShaderVariantAssetFileName": "diffuseprobegridrender-nomsaa_vulkan_0.azshadervariant" + }, + { + "APIName": "null", + "RootShaderVariantAssetFileName": "diffuseprobegridrender-nomsaa_null_0.azshadervariant" + } + ] } ] } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender-nomsaa_dx12_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender-nomsaa_dx12_0.azshadervariant new file mode 100644 index 0000000000000000000000000000000000000000..31ca52ba02b7f81f6bbe2fbb57f4f21bf897008b GIT binary patch literal 29668 zcmeFad011|*7$!ikc5zgFeii|3?h>n2E!m~5)e^AgP?+A!Xzpn0#fH@1XR$Vpdi`? z1&dW%P#mzeO#l%P6s)#Es6~qwTkWOPT5P@TcbxpJTdltsc>Gwr+a>q+FlYb?@;KHL+_~8ZU0AP%|VrtPx$P)9MXj&B5LN( zODER-)>yb}_7`gZ6yslvz5F-tQk^{E(Y}vqGqCDLx&QYaD|VVR&V{(9LgLlbQ>9{T7WZ_Xz0u@!vFsZBr{v z`z0ekVpJU6< zcg4hKn$&H4;P7_*pj z7%sbx-fxKU>hpIv&@?a@^dEv?;ScS7^c(#fJI0@**C^=6%Mu#OhF(JNMbkkK3=;aX zY=+-qI2;~9OyS4aA9_6|mLE%TMvw%!Lk=wy7B?pn3yGjXbp!-?|k{I*IzF7qkDob`~ zctJJ7^c4(5&{V}P%|d>(wD6w%!7hAII3b#0=oD6AKiVWj9=3+67(!2R>~u~Zdg6!} z*C2Bs9@^d(GLe8CNkaP{*~vzbe?obEom-9BNlN^FmnsE(e66TdS(-=gDKt?GMAB;; zDH;wI0oGleG#K=REM#SJF-|s(OVD9$&EYj|x!cSe^ zdBodo>U5wI=Z088%ZV;>RIh^HUBSP;rph?gZRZi^xn*=NgF=vNC3KP{St-CE?&#OO z%%0tJYZi0nN3z48MObu2vKCo}DX{nnS?tUMwaC5!KaHi+!ByTg&hra2K6<0w>Aa6zOzAcy^ql}f@+(lDR9$kF^n#$qeSXBD0Qe0 z4c0V;yueN$z(Iy&vfq*aL3(T_)ujdcZnAOm=KAii7Qds6u&*kg+Z^Z?Mn~|P$V?9H zF`f1!$25au@|11*6NmOxXgVyU4Y0{SiD(anv|$bLyo&Z9)ATIc^qV1*vntvX#PqR{ zRy#y{)K7b=AwSBb4f0HPNMyG+-?WTw9Qc$Zt}FiGEa^vY{I7vAI~i9M6s!bcBPmHs>ijLL{46#xx`vp|$CUsa~eNhNL) zHhx95?sbW6Z=Om@fB@D#F(q+C7fx zkNt$RJgAB3*F4jo*rpG7w4*}Pha%bow&^yJ$s-}{XO78mChb$i9_dL^6D%v*^ z+S7ib`=%okqs%5m{-z%iZ`%eLJ4H5Y95nrL5ll<6M24!Izg-uJ(dJFWjqYfbv)K9Z zy!=dd{#zH(x}-7q?$^hS=HEjP>?~Nw#xfF|opUTx(2-R3h}t5xZxlN`)KXKV4g-}A zEmDVX`3~(;yRb@!4y|1~-(f^!eY4W;d$IMvJ-Z!R%bQaB!AiRUjCCX5p|R4wUFraF zULZ#Gt_)X9e>?A$O#DXMNfHYV6XH;rc!m(J3W_>&ah7C+S1E*wp81=d##ZJ)mokW3 zBJ$tL%+C}N7f0l0^N3r@jB-fCtWEh_hj5ntv~l(QG}N^^tT0hP#_$k288ikb#`f=y zzN)5>Q#h}xrXV$LI*h@b3*$!i4b0xKNnzu}FyU|3h@s4s1^rhQ43H;W(?4JLG1Un07k`Y$q#$^z5N%@=0 zhyi6rFnqQ^Th|abyA!kM$}JpXwmWfiKWe%8hOcvXJ(h*8`oVs2}G_9o(6uSO6i z^SJ+CNM@^EVBdmq$sy)$%Fk32xd<+J2*-gIz|*Kz9!C{zZ<{qHxP1Nd2Um-03i=PH z>^eNb$XVj#=De>91_~l+OgqkbnUh+Xr5P=45ZmZwqBFa2(^K4ypZJC%ZwdsS06Vzx8Ug*9&PQhM~?TR%wXOgftlW|3F7O z?eP%p9?vulA>{NEMg7DrYT^?WZHQy~DbMsdV){TLYm7{I*=0PF2NF|*63pU}w~0(2 zfKD7j_25Gd?H_bdc?1!UxC0^VkSHWSI2bgMb@lQ5LqdAsZ2iDGXjK8fc&)NVJB&ND z0%BpArOD3`<#SW>H>cv@oce)~mfl6%0-uN}bX%61n9U}pt7sd>PBy8Do4N>(=)_z# zaf1jAf(U3#xF|yPU@niCE}}uu7KqbDc=$3A5eAMh% z7uh13Kt$9UsyFA*A|e{qH&`rNe+vEPw19w@jQ&7E9ZX3Qv^&uwFGPgkdHPfM2z|!~ z!HPzINxZ=rTM9pX9m?2Dvq)8;vD@qxeCSeZHk*x&Cril_gm@R^icoE=j1v}Ml7+Mh z(F~)7Jmn%$wJ_Cai3FouNK(f1V~m)>GK`U}uok0a2{jm{osgqEB9!2b3WS3sqrJir zl2Mtkz}To+_1_N+B4J3FSQDqV& zd45RPVT}4d1!1m61_N=tRwgnRg0fB}u;2N{NrT$fo59YU3sZzGE>abawFsNaNHocw zhO6`1UomfMHm-a_1BPE|GOc23v1fuO`H<%?hZ>}tedcAGB+l!h<1G||a<=6)f|%__ zGCIrWP{_I27K)=i9Ja9!U${kDzG!LBmnD5YUzFVH?yBguTT#Y3B0N$aU*3nW%;d6L z8tE-vhy~um?&9>FCrXRDquP#akD6moz1+~*t!(HvzFl5k+7?CMwHoIeq7qZgYWbN} zR6G)?!DFb`#WEp}(&a{)RWFU0+)>6pEDcJdQ_@3g)9I9qCQ-6|>G>%aFEsdHst>qe zEO3Hk*2s&um0<{CP1Td{sFTyYizcs^35Be}BnrnDk#pFeJ+oS36TZaln*+}ta{2D> zQ^OMoI;Mor5U%-EV3O!pG50gC3by6v1eZCuNUDZSaX+_R*>I$;)Tq0=wBfe0yZUki zWV23QT#NafAfgkt-TCC<-GRXa?ZfKEme1Q;p_L%rGt}^50>e(ix654n>rt%ZqiGT%w3hjJ)$n ze`9Ow&A#i9>;-MaF!C9WQy{1Anm|aF5Z3h*vV_D$mT$R(3|w$-X*~tEcod9(tb}j1O!wE?4g~7T9+*;ia?zv>}`GkcrT)^V1l&*q<3sPG7Yqdsc=xAuTzHRj8QA z!BOr@;(EWZTgvF^U9pVOw}1Ja_(RL~^;#~w69+Q!gE7Sl2IWZo_RdOW@#QbiDYa46 zk4izXYf-_zFG=WncI7~BUij=1?rfWf+{Mq5xR#$UcC$$-U7WkxbxFYNC10G^Ml@rm z;h;es(pP1yN?DZwIeT+vqP6UP_TX7ED2OhoU71m?HPp`T&Ln;N<-X#@YmC%Y#-p%h*BJpFjj zx9McG+dr5@`M{%a{^ayiX&JbE9Y%Ggs5<1Ge)8S-QG1FCzb*0@z2RjnnXpDna6Ms? z;K=z1irD|zv#D2~5tg7LIMI^31Pc2(6t>^!fQ`N@WK<|@glH?I%Hg};fgp*|=MY59 zx${X&ga7%Hj)!-q}da3GE~Pp)}K zet&XO=jn{^ubuXe1X1h&QCvgqn5tJZM)pvM5RC{&X%xvnv(DLIvqfvO!_2lyY+F-j zd+G<7HzO{@!C`B9ij*fn-g`ll1qRJhTF7S^(+3lU45j8gE2MGEx&ng_S;Y>x_ zs{2`Ti*+s+RM{q+VXTAlLG?bWe6loysPc*JJs4+S!MKGg!aEhc`^$TlGruIbU`!u_ z`lsl|ByCLl2Sa1rmlhEj&Dy+Krp+SjwfunGV*%T~4rr8zxRJK2OfB#;z&Mm`aA0Ad zf@XeHCzi+~r?)~v-O9FZ{^jZhmzkwuu^IwYUd zYqPAJX&-$E6neL*UZG#C-(IP#D_>Dv++7K||E5X9K;38eF0r@MNBhB4Kb=A;(P&Pk z)kiAPQqr||&^B85+H~qTFK>Zx_=#`%;f|2eq#cT%yLQ?aqY z{b>^(V>trD{%~s^G7E)Heu3z=PAB?y3yM@&S9-%Nh2P^ByL%}Ci$(HtktX1SLMQ)Fl+tVA!L_t^>s+};JGvnu&@nL9c?!<;n%SvVkltrYepeHBZ47$B3& z3?+%z7way*QUm3|x+Cx6vHkN< zgJyFrW=@MjM=XqlCfyYOvRq$YZmTQiU+%0nSWe{W&;u#5BgQZ#JkY$XDLQiJe+MJk z@Uh$T^y#$gC&qrB^nlT=|G7>kd<;D|$09NcvKe`m&FzL)4KQX~qBGD8$SzHG4$aQv zWc`_sJQ~h^cz(*6Gj*Kvl^22oE`ilVgy9^;3Bdl9wr9uO}6#~#Xhc9tv3hSTLy35?Q7J% zRx5X?RkSw32x^rqdYSgrd^F*M1L2GFW|z1v;f5c4_RzYer3B_kn8hO?hca?5aib9`%YptTx3<4!_r(OoX$PtWM1twQR6fT*l5*qO(}S22IOLaoqj5GfgI} zY9u(HuC0m-oimE{kEd`g8V|x?E^R2PuA8dVGA|e1?$m4a=+b*dmoK*!F9M~xN_*X)G{LH6-0ro9j1^-&9?1YW$|`U1zj)`ZO~rFqVr!R;iH>gpPEnp+LzBzz759a zqCDcy+$9s2d|vXfcr7>n_3E0S5XZxtEuV%a)H&1O17t7&Xu@od3`_1Rl|X8+=c4&R;rH zd4YS;_d){)ePV+-e6s%8t84AAp4YrgoK57%Oi=sYE6cn^to1KcC@qhLUmjh;P%$&wcr9BNaR` zHbz9!Bl)gwq^>FSt>&oaGN`h(TV1>ok8SyA%l<@{UXG}Slg8WkwiAzl)_&yGqw2Zs z=PnnQ)k|?p#Azv!$r-D2QlaM+NwsCD)%UaO z@x|P5gJ!Y%-0c8ZxL?Fx4L?Y@dSI~|jFQFZD52!~!Z_@Er}-9)K7)Q~?`v$AGq7xt{Q$g*gnwy@Fw~MrW1LAd8#pn z`Sa8%56S{h@4fEmlL{Ec^5PQeLvv_o!)=G}4%}(fDQ-5RxAlm8(Ax;;Z5^Nt=DSZy zgD1TzDi?hUIi=61;O4`@#=e&JT|@nM``Yzpt`{h;b6On%#s=eXUqxK}zQfC5NSF1- zF|7_Q@3FhXV!@Ne2G-*wkgWokr*@VaLw{6uHyqu?YT;!;W-aqGVR;=B?Dwh&-J0kE3a}Ow z;J1XcEa;LHeKSX`$q3I{pOKRyPD~D41I7`wwuQpk8mz0kqRlv%=k=|Xwl?znqM|2l z9cdpFqEESxsRvx3jZ5@(uWB4FXdG-TMB5Ct@4cbopJ-nYKxe!0b}LAkT8v=|mf zmcnFyTz-VcpeXd^Io>jGSEtLmlpI<7zMxKTju zDWl%0iR%40s;{f_%R%Z_FNy|BXy2Z?j>lL<$gY*#wiz?d39ipMIIHDER9R*cKJ?>9 zDEG0kKlzu2l|CJ)$IO}0!87WCxmCwjX&*<@%{SS2vjl5^MSZb9}X_e_@vyE@lanDYNu^$jS3|Bg=ZFI}M@AkQD(m>;+q(p9} zoZH?M^7+>x59Kq4kIk6d9JY8MOynA#loXyhVM%NC^1K+He(gSE!3Gl+zHmF&JMTNy zjpt=IexZDqShC>PG*aK{CiRSe;3DaZF+FU?4`(a;kNhBYoVz2ntnRY18#TF>i;5p| zX9vI_&62h(ztdyGViq;jpZzfC5|#ANTYLZ6XZoAyxtzR6r+a*7`OQ`sL&x!aE8h^C zk9->%U|R6NbSo$~u1qfM{2(%8uIQFiQ+9c%iHq0%bz4AXSD3pdw+=0bk$(5v0a$N2 zj*poD_g)IQc!nKtA>fjJW@+${eg9&!p$K?MIT>HQ%#KvBXR-2n|#;6$&Io*r3ZU+dz4Um_C6; zehJNwB5-Kb+F!4oj5pioOF(5TR z3qB?JnJRSS4ECFHM~ooZw9&>OBt+2~iY1g6u z>=WCyJJ~f$?c2qK&sDJL92!)n|Gd}~SP~jofSXp*GzBt!A)9s!H?6jb((FXsmWkWq zo}VkpXLg6uM*0Z@Y}z;dglBZv@1WgNnf^m)`V`u00~O{5T@u!FGNrjZ>n)kjhr|owtu@dN6J8lrTKU%&CiFBF24|`TY9V zQ)rxm&d{hG8+yZq)Pw&B`NTiSOuFzh{go6pdgZsUFbixLq`-yJ7#NUd*!V}85Fda~ z#xo(O;JRRx32}$8zr=(v3`|J#OC}`YUziZH@l1%%|C|XCK|Oq(3-nBg1gF zz=SkM($!iL&ln-6=-H1wh(`;L9>!NiQzYzy1olA9z2S+Eom}7Ttx1^R_UXm+FiI0g zxZy_TbBky6eU8}9TDp52xsp!dM|ltu7=$ekNwNe^7@ux72Zw1QHLLKq;~TLN`)(jH zisd`%0yP6)&)9=q#}G5}%oO)#jN50QcE6lfKSEDn28*ylDYZ$pf)Viwpcw1){mt`X z@0|3}2j5-#z~rQ-j7>^lkl<7B(PKTVG6sJfFY+Wi3$)?OX|bz~P1tj0;3Cbko?p3- z?0@^$K=Q|8g|roOpQF$IBbw!^)s>8+F0Po!6(!<$q%}plmD1OT$`y1s03dRWg5E23Q4|26w_ zoB?B0tPO{#H4(v}bQ5}LR74Dxhn~R!yK^|aMt=$)q3;k$lCd9oA?Ea#I8~AqE~5+; z?8jM-+mCaet0s{v8Q}=ozmjfJP-t)fME*heWYqx3gc$ABg@!Q9(RirkZQAuqGA|WA^>FrqS#F0~*7>6+& zexN*6UR$NjJ9@uMvQX}smX@17c})_S$T2cCnfcCcbX^CQ`bs3Jg1m1MY+6#5xCKn$ ze5<!~|h$=2}!)sDy^g=gEV=C5XG$4ks&zW${7{fWl#ve15a}Mz+E(9WE*HxqasZ5(H zKnmSR+SEpNp&MNuv~OED1pqK@|7P5cVwo8Lm#`hz-=AHj!4iW%j~izC0Ly}xuckGt z>&AiyMHE}FTD5eK&!Mrq8*qN2dQmfi;n67$A%VDX6K|2)FCi1HPN#!fJDd2%5=jIs z72mP&jnyD$sR)&vLv-Yrv4C@kLpo;M%rPWbb^M_wQAftgve{^6*~_xTjmRI7 zz01^z3mL7e4dr_$o^I4;GFt6QWwh$N25TH_T`C<*pus4npqb4u)SPHD-{}{uiSr<% zgz&O8Y+^CK^0Df!j5A85U`^PAhAzWkX(uHn7kMU~hF)X$*OD(vOpdEw3(h28c`f)X zoegrKKjPj57Na2%Xuux{=r><&MWgtU~R(F(Zs3H)7xz?A^ayorncOL#M+fga=WW)zL~g==WO zU=`{Q$U=Yc;1g#!MaH4gvEr=N$vJv38a04jM`Qf)3nhNhYk<+fKSS!M0)R%+|G}63 zK!1-v(75Q|*nyVdO~1$Djg@eGeDwT};bZyYM;DCT{7XJwi->95Q*TGKGgpcT$Jzzb)yX zAa4=wjKR$P{$LP4_tu1%nAKTu%-l&rXJhgotna;GeOot?aGXLm^7A;1@+-3&IqEC< z^lM!h3&}15f@CiL6Z1cjgHq<*?v_|7kBuOB^lRwio1OqL3THsc=fxp&hMA&Ws%ulM ziDfT(uSRp2;S8A_$xaVK?)XA_|2uEX&>V%Uf@I2D07TQWQ54ipjBr(v6tCy&Y|h~ml$V(0Um}a8mhED@MyWlZ#LeXc zB3RY1dnk73lUTQ790w}_O|~15SPJ+K15S3sQq#wkc0elMMd@Ta-97t8se=xo3~Ed@ z8q=pd(>qS~{bGk5QioxTLp#PuT7Lb1ke*7&xjPQqp1GTILr_J#8L8)HZ6ySeTi{C! z^)GR=%J>La7C~2G;x^^OTF*HC95Wm;?zuQ#vDsR-{qPBt01n4>A^wQp<(J65*1Jm{ za;quO;02(PyWf)Q*JQv8KoDHgG`&L>a=2+qhaec1gK9&AIc!2V&1GItsySyLl9|jN2U6#U zDL78^ao(s*Y(?aWl_|m1SS$u%(@9X#p1;{?DnT$Tuz@E>RnxSKp@Fqy0D1>DSb+=r zxCtfE-_IXc->;nZEp%@2ajM3oBDT=B^fHgX$@NPuZ;Bm0ms;JtXV)b~asDrQ$Bpc7 zB(slN9~~!#b$_!)g@Qm$QwS^#mWo9fjH`iF z(s2@)wtl<>ZnW;mJcRmkm=*DG91GUp^aJqz7&mR8DG1hAUyUI3w7=v|FdY@xrfID> z$1>csk3$2ya4ZSNegwmS79i&v)|U*9EnC0%IwCeKbH3lK>-(@~8oGtqoIzA{dB~Q% z`myS<8(pzSE6}p#GP^>H6+?kdi>P*FEXF>91DTm=hSW40`1vkn=Lm1m5{${hj`EPFJ4iPK)Y@hf5ZwDH*`5_twcLx{~8 zXoKv)I?*4D;i1>EdjZ*v1_8ycM(~=kU-4`>Ll?RJ0Iqx5umM~*g5|PsWLKqYyPB?F zF(dn^?a0S?*``urMz*VDlc%ZaMDkR%8b_Y4?#Gd5syRmFShdiIyjU$UYCjgXtG05m zHHPhiD20Rxd_dF%9f&Z2AhGmAo|a+QtrTQd3KHRq;~iuojS!SVkofx{No5#yBLy)_ zK~gz5o{Wh&Uq^%+2$DiSBAUO;P0-`=hLFTMRYJzdR z&zZ=j>j*uUAUWfQR2{*npHPqu5HtPx!68Id4< zXh)!nT-C60@?S1ADv$~`zK4Lq?9%fn%$^A_yQo(Wv$IE}rm?!dK7iSm^xDKT?d=naiDc2S6 z&url_uH&5s$06`~U~6aTgtj)|r=I{uGvQ?r_0#4aeiY!kjIH*z(5CG;sgX&2K$}$1-^DDok#h=rBI7=BQ2eg z`6|^z`+{w^WTQzQvv}Xn4?F?bcu_5e3H#HOL^@6+A1cz~`8$b=h2rdN6m5uHlaVaW zGBCkeEc!7@hloSK>F9^GgalkGLUkimBjy$g07uloopWmnjjDg$+# zQ+!r4<~3fQ4fJmk%~MXZbxU8hK2w~yCTBDB1^|CM?PK5K5vk?pKfDM#cfLUvU|Y~w zz=Qa%rk>N)^1QjdHcJ^5J+X&Y_TZh|fd*|PE^_SRhn{%i)$ye8w0FUt4?0dyE(CHe zT}CehegrlgEeF;2fNlNRZT5xO14JwC`NiQ}J_#k{)eyls#?BglUSxAyZZ2X%3`?d(^@A4 z*ibVXD{n?BZiDEHXTW~hgw0;^aIqfiaI*?Ous9$9oFLqmgafwGT6qZn|#QS_b|9{Wtv(j z7W07q@j49IcjZ&HGa&mN`s|6?}d!uOluWfltTOPYctiipBy{5`AK1R4FJ7O%Bhm;j7va~?7Q^ugRTM&way ztSs7~B@O}7yxf3J=3$!hs1c3kVe?`M_Wu8l)Nh*?dzweA`gf#$bJ#folnES5nt`Kk zZ5$Xr-qNURhjm$$r!KEamC3W=M=iG^d>dNkC6Al0j z$R`betPX|Uw#excuKm@Z*D3@iE?Ymcm}>&$H9i{%jU7j^Cc&w|E0=bjvjRA*p|qhp zijGBj<%H-WBYS@fg&J}<_KHpB6Fc*+xGu-KB^`CkOqjUM*}JvT+l_Qa13DruZYNb% zY|X-+194qfCmxh@MJBIf`puI-DMU#B1k;!9CLhBsL{W7;eF#`1N;HBz4;%$~W*hC| z1ECC%rG4}r@JQ;7>)GEUj9XT|ybNf}BgMpGb4@`h=$ZUy58&>{M|T+o zr^eN9Z`fWARhtG?+Z6o(s%BvH+g8R7@`#;;D$~2plOG6cEJqeLvuMy`O(Ds@9Klf*b1V z&VVMD5Lv1L|AGTGLQt0|-JG^QGg+`koGlP%1INQQg>GLPdlDKR@6-ia#n)odx-PyS zpY#lRwsqD|wjfde0_bB!mlsFHnMWMBI&Z3&?wyK z2Lw=sFv`yO)?M;*IbVAg%80-?N(%72i;g3at55W1$WsB%4UGez+_~BJ?ZZ#{^q>wO zhsmuQs<^!kO&n7Is>PGm9dk|&bo+YJlmxKeLHgIeq$iW}cd|5P9 z>uL0DqP?myuiENcwcT~;^gCZq?{}H;uxW-H=@Q$*Lb1F66>mot_Maf$zt)KvN^ZZY z?rad@^nH7`m2h}|y*8!mv3w7EPJ+hZx zoNso5XkN}9!bU~XbH#34Qp?UXk}ydws%p)vw7SEaRaU>fuC%<{thxTqb9F)m+P{635Ur_Y`#ty@y^Vo}!?Xn>?DEHnW4zKx$2f~vdG zDZ%zcxRiE?8h+nl(e^HkM_R==3|=#%=bJf$#$;FAN!Nt3t;sKw<(Hbcz4~wY5?}3{K@*ZWj_~V%@~P{1Ih^ zjx#9r?guFU(0_*VnIk#^HTtCn&#dRfWn~l0Rip}zIv764^~MgnWd_l z4^8n{L9<=?DxbI3XQd^Lz0<`)fdKz({7&p<0g?J&;rMibq+NRU?^*zQ^c8Qu=o`Ys zpHbu$1{L=y&|o&;(go8@EKr*xbAFnb)1^A|5_Na>VwoiBDR-D?PQpYZs5Z9(9X_tm zIcw6AXJ@TR(hISLLV_0hL~OMHe7JACgtpgBK26FY%qGI~9f zFsPKg2o%8Jt3L0nKBuiKjnZE3_CZlh>gC(|*=z|6@%I;=CWCf+X;`B^rv3rJs8+tD zcN(CE-}Jn_7Gz)bN-z!qqPF#;btZC?qlqwO>fK23A3|+bR?Dn{Q^&a~fd6FFm~WX; zH<($dgBeI%9AtfFVJF$%|39<%d=$N0dLm5;n)|P^_@pFg{rS$roo4BPu&w?Bl2_!AZ%e-0Xz2Y~s_=**%>fMsQDl<7F zaZOs3I1`ZL#P#d5l493~u1{Pz<}0;AuaL(f`-i)GH6AZ~E zOozVSsuYA|s> zI8|6U_~bgc5xWKv2|drLMO&mwws{3I>K?_+9x9>tp${}k`BChFy9#4 zWx>MZlDT*f@DPtp!I_zW_o9~{pZ-ED%e>fx2m9O@n`_!U{t5Zc-PU$p&D{^~4(M9B z6e}+9_hn8=$9+MOjK}3~KMP;n68=-}Pi|LX(m+9)CFe17Qu9>h@Vut3d^V1(|H;iQ z&$1<@B^LE=Lw)knj@zOZ>v)=9d2VMl*sW7<*L7EG>#9-LbJ=njc!4nwDE9t;4&S$3 zk9Fe{|1Erf)9?17w7_Oj%G!r1IeDwMrN}aSn!p+}vR$9GX7w7BwNKN}`>)`8MVkI; zmX5;H<*{+^+#02R2rfPqqtkNAlFz|gV0I}HwQjqP+Zw?z^3@aFG3XO>#%f45{rwn_ z6%#a-9=%r)m^|W&_pJsI7d@r_ioEYTe#tmkV_?vOZl8O#`~dDHrFH1+e(^+(jK*0y zhUSl<;s!7up3ZH+(CmxN4ka=iQO5({s*i&Jojub~506<30~Rd+8GJK#-xpbuVcu3Q)n4m5~qcHwm^f7|!rO)JOJuGWns5|2vauHm;QLinH z3HUj!_x!X{p7$rrJ?4n#YA|kKG6LTQ*Mnf&e6yGvFk1<3O8L)P(C6Q<_k4|mQ(N`e z`K#8jYACu~T-|WQUU}}E5+r0LNJv#oDGi2+zL*Md_3vnGX|L%54!P^D4!r)QQ$THg zc0!m>v;8yRz8`JBZ(~n}5~&mPjvFU@8UncIC;FXj@I{|gZwB8!)P)JxH(?~|woo{^ zV=(H2Nrf+s-NBX-t-hP9ia#G?>38>6`9^@A(ULdMMiY z0>|gPFZhVDY0!4Lp1qZFsjXgS=-`>Z{80RzI21WsR=li?v5X1pDvW&aOq;go`z|ey zgt|l+d;`)8^j@}f6_lpu$gZ~rMLM;zQ&-a2Q`LE=zO%QP`lXI~7lrJj1`GE*s-k^& zasK13>rV#f|09y#=rnOt{q~~Eb(hHYmBuGvCn+;c?_JD=e}_5!oKL;`1vjzrT_+KQDRdahv6CHY<K6Q8W4A)qJTaKW~nCV_3U}3Eie3O5gW##tPVsP3Ux+&JbHKH=B zlDbFy(|6-n;Y)PjPtB$r9FLkCl1jz zC2hSpC)@jG-^0O&uyPTkia>dLHhz$oIQhwAcp)9?8SsUjz1bz-kEfi!!0~m?N#3+7 zV|`Y-_qX6p`H&mI%?S;R^$e;Coz@&WJ#2*jER?}86NeH1Kl2+%74D?mP);`ez`M2c zNs(c(Fk_c`=I=52sQba`$CG!a?V4QpLE2opU?aF3fTO~|u-?}boDTeNDJeISAA^Mn zP6`=w>EWYm)6ww#e~tsVzwS7|kpsl-*vCUX6dJ|$=m~6l>YWKx@I6&clztU+YVzJk zG0&g({?_v_MF&BrGYD88e{QjRU zPhLy>C3eSe=ReJSzHGVM@o%2iZe32muKwI{=hBwXz8gMMNUHxW;@NQ7ZwGJ{t~v_9 z74lgK`H$HJc^u4dd-R`gouDR29sNVzUGU(WDSl5T=Rf!?lXZRaHK`_kqisf0PxA8; zhvNsKY?u;$KaqOl8-0EDUCRu%B^{1`+jT8-!H3tb`8wAc;|X4B8g^#trWxnexx#n&gnnlc!uO;C;6@Y0BP5>w{|N$U0F(BbAhA%#Lcmqs=40i|Bv? zcudZk?-IrHO9zUzn3-fi175qx=b@OZBb!PWgDZtK2E|!-Nc;g+ZB6fOexpA|^c%?7 z*7OSH>tyWtE(+>{A&J1!sn7cL=lzivz@1}iB%0%TdQ3hi%*AQGOMIjL#@#qd!jD1# zX3o!v)swfFj=XH7U_LLW}0;?5VMDX-BR?}?Skg1(Pq)X zntr%K1Gk3jU&k2g1rlUn(o*dVjG8UH5_LSICWPx_jG7sQ{cmN|8lfJ4&Zsq_4j`6g zm@*ec9)zu8z(5ePRh0|`z8Um{J#2TJM6JFOWq9}HZ*wC63c8YhECDDiQtZXm7hf1} zCAFDKQ{qULfxB+9Lr_Ku7^8vX2H%lSLm5Yl>F*WO`9MM_RdfgZp%O8VA*^QO8bv6{ zmE+MY;V^{9>F9kGjsB#)SK&IHq`++4GYUF26nQRA7~b6*-V7m@_d_?)NjbL+PAE6h zW9!WK@9pC{L%x-C=SDg2*g^^kUP3ze$|gD)FO$v3Vf>UYVFk=$YuiR&`UWp)lkQp!jxL;-S2#hJAgJH)Mo+n&3j6n7 z$Vu|s`EN`5ClrDC(#cyU@W1=lx4Oa$Ape7}jSq`Ls5ddZLe=of%O0zN!{LV{Df@Kr z20ml4Z+WEK{V^L|y1tHLU;w=en0qtua7cj4>9Rfgs!~1fmu2CiEr9z%?+&I{=mN%q#^yg-A&l(=t`y zWG&Rg4d4)@C@>G$cw>QRRv*r&$}?ilvzj~ioIg&3(ZmY+_yULAUd(^*St9*(56^g5s+`(vv^Ux8U|O5w7lDcTxP9Outlb>PhgqP$uN*G8)Otvx!JbWqcY>XY{NPd1slxQR zsuJ*nE%vI|dU8L@3%pPjQVyWo()c^?)r-|k^W-A+b&QpgM(Hkp=Rg_-=j=mXYk$8 zGOMtRA*s7s_VPlFfbkULSv34{@vHaT5OKFJ}k8+8!Nn{pBBRV#3))fy{;q#PFl72La! z=K?1CLpFZ>5CQ(7?p6tU_p8sQbV$ujM%}O8qI|oDZ|_s%LP%Ed99{6g6fzj7H`zwo zM)v5bl9tOZ)3ja1awK~4-&VZGuZUvta#m+O6 ziNPN9Kw8A5p|wQAH@y*X^i$+|;g{d!nhj0z`Equ@{n87s zz2BQB>&BWez%31R7{oA68O<5Q#*cHhE6`$~O(oi8YQ>b2E3Y{QHjRd1R@65KUVL*H ze`PB^Sl#^Eee$5gFN^z2quXKcvEmNxuE;#4_bHT&`Pr!{g3yVFCXdCS7ad8h*H=jO zD#qNViDewpSffOKJ&`e`RwBJ#AVo_a`=O6*+vsU6-?nA+v@Y6KULMA1zB=ETazD}C zjPL_<4~KA{_41=4Bf_|pahw&KFd^?zUa4rOI8YXig9xHql94iZOMGc0}t5vKVRIVHx*Mho!i{ZL^69*D;ajjPgXC!;6$rwlY{{=u0O(302ZGI|6 zz#(ZzYcpJIBejxlJ4GKzyuyBWbg0QkghlU4ie3%F+IYtO#9B`C)urNs8wFZ)tSoH$7y*ZI-lmNdz_$rs23@R;O^|ONy|bNN*}$D#OUyqXz61zRvWST@vMx0 zk+DMU?y9S+23uaqN*|||MaXT^j46l={EW!ZkZ|~qGW_}UaEmGo#MkgHJQr5jMlxd)P-@yqCIr8->}Q*oruY5=P1hZC8UMX1L*hsN<*x z5?4-ew2+OIF_sV4`CbIUqC5894V#gNANC1V?KP8cquBN*b|H>(!bpcX8)t=^!f5dk z`V7j%cJN~|qeXm?qq&+PmhA0mL>yT<=?rcyZhM-D_)8y8%_8OCq=xE=63bUG!%_^w zeEz__QgPB~Kz8{`X2e*)!AGTH`_TY7a~1P*@#r08&mka#p`+qH5{u58%D1IC5}xa3 zfZSEu-%rF%YrdMdvEYWcd|yH1s6ymlZ#8*e)A33Q!HXJ{rGCIAgidK@)8!%=+tEZZ z5?9-LRWWM@*BjJx9O^@DlK%9{8pZ^^_n_7DI8EzSeE1A5XV@o6veyZxZ%MNWj=Q~| zm(iQA9*>-nA|Cc}D%dNo*hcwI-+)bbX8oH6bcZ(cVu$+*eQL1@u7)28KY}ulHGrI_ zm^q%zcLw>HwauHidqg+g?uWYm$@debOPg08kjCF1Z3_*uvGL)`-%>z`!eI~4UkszL zKpUA?u=fbX%rTVdJf@$z_w=CpNou9s=1qrWTpcag&vpHvQbeft_vA0d6?3db?KfPp$1Qv)2tdp1${XjzO?mM2an| zGZwCX)tGC$>}$ktsR?(b3twR7{y=oU;wUo272&rl^@YQ(m@q)`dBwSCuVv=TmLmCu;=UooRdl5W`9i()8jY5%Xa^AAe;jN`Z< z(%1On@JH;6)Bu~Nh7(fKRxyyBI&zEBoIgrY{2eRnyyk9XfMliyHchQoVwas$yD-jb zb?rb+X}Me0+S$4`Os`p24c%%`+uDbK?6%u~`{#Sl^L@VD_rvG&dETGb^BnikHKBxy zSsl!FUY7N+jKRx{A5m03-bgq7xO%M|5x6l?CP{pry7EEHAqp}`#$hTmdvKBvMwBtt zk@%$|y?-?k6i#_Jc~{k*1`YgnwpNo|63fEgVqPs584{(OE2h=vo!%F=N`EKIUACE| z+KgnyAK(O_K|)?^9-KWpB^zWh=zfmR7orcQq|znxyp2;;Q!*Tjkvf~irv}aT74Djn zsaOnIogEVmjkL{`ozCAxj{`-nveOsC(0MS*{tROY70KflywZKIuIQDJz*zh1sZr!G>3KEu-S{$gz|cdAYYqmw8x`g4~g{ zEny6r1kRh>-aY@3tio8x&jFbLl9j!R=q@nyPj^Wqcsw2_p zC~;k*j(m&>nlI$H#M=6lN?nAXf*o#^UGZj+P_4-hi=zAI-Z{@5dr$rWuUeFe zj#fp0LRo`epXn>FtG8pD&>8M|Ae;&ykWQ$eAJ%6-|uM+_U0nhH`X2bu8(=tDif~0JfarxsSg4bz36~| zU$a)I7)6H#{1ecSw_BJXfKJepbWn5s-ObMQTrw50(YPF^?v(ZaRmWi|b$_M`7^EOa zTcf4;Tn9N>+*YXXmJXSm>!kXvrMN{8VL`-)L6OwgPPkM6tG-p&({!z8Ov5z%peOq`Zz5C-n%G?t z_Ou*p&4HXL;=wIJAqJ_JkbE(3n0}F^CJ~EpA?+lcDpPOyS*yCu8hAdEdV`k($VlhoK~4y#0U(AHR3AgBC0s|lg{+QP{OtaA3nU1bFx3(oxfoS zgcGRK#pKU3AI0igm+{JOe1wlK9vAZdVsDVbVoKW=bM0yFhitc znR!560aVWS?8m1{Dew@{NRBf=hyutmP6e z zv_vP&z+9>E;BEjffbNFV;Qp7*5MCf%uJ?9~OXfj7_<=%nn?`EVR66n(c*gbWG!>NJ zI4Hl()pGFp2P-V_Rp&ZIC%2bzur0`T6fL5i55u%rA{(N`k2VA>o|fT&0w|7grDdc> z$X^cjykgV!anJYxvdl`~MW+AeEm}w;ZB)BB4%wJdmZ<*M??J7A9ttlQB z#<}(~q}I(Jf1iJL`5_8Ar#(f!CaGS=;ji$Uzrs(W(wgnl@!`|)6yn>&N#ms6Fe$*M zF&oEjRbQ- literal 0 HcmV?d00001 diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender-nomsaa_null_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender-nomsaa_null_0.azshadervariant new file mode 100644 index 0000000000000000000000000000000000000000..299490c1bd28c50ad68e8f24e11146bb75b6f6f3 GIT binary patch literal 589 zcmZQzU|?YGU<}-ML)7esBj1D%@+<$B#qTaHI<}jSt z*Hfs^cq=A3WL0B;cgOy|uZ>c>5@XJ^+(>o4H6gq9z0Zp26IvbFF8^!>nhOLTzV_dv z)HnV+)YIjDeSt|D=Pyoelgh3Mt5<5Cnj|UyB>wzNlXqugJGplXKr|qcmG$|D4G1e^ zh>Uw|{AR(a4xaT-oKH{6iCp91nJ5Ib`sF2O@h8UTj~Q}CKiYPB@%%sjt~DNx4sn*N zE-imFsXyL*_Ue+={uP>`CqROXyJAbH=lpk7++wkBZE|1y4@eMPzrk?POT@>1`IAj4 zf#$!CRr-rZ%)Ay^Y3zR1|HMwgb%(UWwx|)$8M$`P}XY4@%bP+bov5V5dNlYL| Zli(xY4%42Sx#fn}M&Iz^+J?I}{p_-1ruMmI#_0#_Fm2X87ruV&sL{tA z`^D6zdoMnDzdp~eXso~StlFb4xbKoT&f58|^ol3WeJ(Tm`3)zX{*U?BU$No5nFF7B z=N!dVnY&=dTgUEw+kYOs_@bI;ubI+3wtd!^RuNJ$BhnBVKBF>Z&QPK5_ho zL+{)=b_o7={h9fPCVf0DwfuxXOn&8>$1WIl%S*E#zpQ2XO>^g^w^i3KKRtWIOOu~^ zc>f{Cy?DptU;E1Y3+J3RcV^WI2i^GebuV6aX+zD`8w(p3t{b;x6JXzO4y?K8ikGYQ zy>9IVueLw`@H_DoJo{Ygr$=r-f5vq$eY+L2c=SdG#Oi_W+hXyO{#B#^otOzTct!(L0^#0 z=9bo_#L|jJ(l0eYb&G%jiql_uVSQU>;_Q5`qma%OW_30(nKJ!xKukA6Ogx#I=z*OAFz>n~$ZO^Q= zgXe*jDfV$nzP+WXHs6tD%9O{}Q67VPaB`V+`>_qp{-646Yo_DqZfrp|*BLj9>oTN= ze`l^ZL)}ZMzT$P+q6fDr)0l3Vo$t(Pm5XaPv+h!J8 z(j9f#Q!_Gm=gOs0T!UZk)rsTvKLUb%|S) zOFX{qdiXSDJ5CA$2fXcj@EX%?9i1(ifa>|$p$G5e&U8~i3gYe9gV&aCS-(1;3#bEi zhj4yI^x!q+o7Enmy%V05>P%Z<&BEp*vYD2q>U1G3ispK7#6fRuXiT?e+S9e^cGU%) z<#;WK!M)Jh(3Z(HW?L4d+v+px8uR(~ruzKseB$zhPHH5L%MLllz2?xSq|>K_(l|eKytH|yDt~6 z;^OP=#-!gZl3O{IDso#JTJuermiqiLTmxx#|ZmO{3zC7WrN-7%S;kekV+SG8oSv(3$&9hsVW;th%N zWDP@}?wVE6^&otJ7~Eym)iv{$=36>jGu4@n#+q6!ll%unHmRw6dv6N&$QS#wlSW_x2`SSn9Z$@ZE=5$A+kl+ zREPSDeb^5XespK6y3|a@^Fxlzr)~4v+qF~ExyFn(Vx}eG4T*AwYhHDhCv1`Bez>nA z&fN7KIvtsgEIGtu=6;TB3)1V9gF|%Z$lV;r&$qXxTV`d`#r(OGBO8}pWFh}JFYe&T z=7@9FwdHe~IN|I8^5*W1IKcqdD7`g#@70*c-5c>{X(87Xa+!{f`kuU@Q9SP5l6Z4+ zjrk@mM@_o5HMuw9{J3}HnCZron$w!JVnpZ1eH(G~5ImwipDV!gcx3Y&ZfBluf_zKM z!sh0VOd&cK@f>rvMsb*6-CsvAm6{086?bY$-llYOxKHC4nU;KGv~}l1M@FaG`Er*= zoY{IPb!3~foAKg&Mw%DrJG(_sdqFxeL-c>)dE5M!8lc`dC)wP@wdwYWwF~R!)z4da zw0!&b_0zKG2(!+KE^o5V9XI1Z3-AA#5kjIy#C!hax%wxRFz<*e(*v+=h_wcftC7! zg?=8-{ed4?sUKMA=P|Q@&K<1O4=nUUXI`oTKd@3iu+Wcn#;+^z11t3d3;nR;cYol= zJp%TV0At^Py%1pBb6~Fp7<&`!-vP#+0ed^ZxXZxa4>0a7FgCB}jC%^Ke}J(+zy=2x zcMsUG0OPI!+d9CwSHQLpF!n0g$N=O10NXXdxG%se0*rG7Hc42GP7&)VH9A|&5A*Hw z!Msx7Qy3$drXa#X9xx+Url(?m6|^pB7+V`>p`<+Fu-C zUi%FJ=C!{(z`XWX1{il7`CXG>%rOOw!kQbSW;}DXYmE79()PZX6!?La`hkUh-a9J; zzkbrm!ShQD@13@Q=e^S~w` zoKdNrBOm;G6a0vckawv#UMcQ2eOIU#_6qrsBRTJ+nwX4%oOf2uoYVH0cS+j2%FY=i zCfF$bFK4$jH`q~8h3j5xbX z*r)6@i*0)(SZKFx&wy{cZF>baVq(X}IQEv%C$WhEcbax1Ve-zS8Z_xwHR7>DcVQpL8(dke~f0 zNw+`e(Ej^N$7cTnq=ONM{1<7g?7PVl#zZkTMLHP$7@L}4_|_(CHcdMI@Ub($8x)uE zPnTe)-=5Z-VLpc@SeVaY!tjTWJru4qCqVYPMf)djY-c;H-fED%?_U(=(Pd+p@cn86={Jzmq}M=|fCUem)R z|DIgGz>fcng+q?zIN@t4c#OKp(;vQ@eHs`RjghhU&T~}yA0F|EUF5I**w^&%IkLU^ zl)k2i&l(i@o4=-q!{e#Q`M&=->Nmdbm6)i`>m$)5GC$T;y#2njQ|D zYkIg`C8gYQuj%1(O%=K2U(>_mIx6yde@zdUUjd5T-e1$h<*`%b_Wqh4E|1Y7_v2sF zSIjU(>_m@lxcKe@zdMUpI@q;%oYF-}m;K9uB3q z*Yw!A7lK#se&N2^YkIic4*|E=*Yt3?BYJyHkDa@r^fi5WHiLUFcugO_){XAV1DYmg zThpsEio>fh&RnftzVV{IwV{a*7s3Zc=c|b4qIapHMn0UYC{{P? zr4+g4KS{u25A??KEzPS=xa@(DTkewtJk~$t_4Y{uE_)&5mir_DkMj`nqF1hbv5ahk zqPwEEPZHcCl<<=T7-KK}BmvGiajdNjJaU1pgBms}-mU-SvX7Nb^4(BA|lzfuF#D!23Y(s5btStJZB=_M|_fi$9^e^SN4+xTqKTJ{*wfD zo-GmQBR)yM<9QPC%6yW*&T}NPm-!@to##hnFU~`cPZDr=cEmBtf0BU1b0gw>#3u=O z{COPl%6yVw%*FE-+%?IK%>Bw<&vzE0ZxVG&8|u^Tt22d3?DP1ugMSx>%iIL_ZTAJv zCkDMA{@pxm_H!OpC0MB+ywK0Nb_IT5rG8+cpT~25;0IRf2NwEy z%q+Zf2P^dh3;ocUm#V-Itke%I^kd!d>k9n9O8vk>KkWG3ANX;=Fa=1(qQ+=pNlL4Mo|VE*I+k3GcMB`)*r^FfXj_!Pzn zrYViEkVlNDuYlJt!6pTm_t}&HBL{q|0?hkket>!HYXi({Umsvz`(**3J^V**lU|##K0Ar1acX5Du?KcFN*Z%SV z^V(k-VBB%UyC%WNmjXs%&5ea;(->=Kj`zi+60Fn@Ug+n&voi4OC!HKTzx3z5(-!c& zce;e}$ps$q_)NmQR7mKLPXM%;7mC}=NoZ$2@VA{;^yI=P8eZvFNU)*v=^&MSqS;j% z7&+R`EA(G&^=K8j@XW4|P_WbXYiqYFFsj(UGHynnGsZ|KKDkZM?9pa^;2_5KkWOBR z$4VT-aqt@_VJ#hJAL-1${l-goKGg6S=L89P z)8D?TiRJ!iPmFBw?<}l`^WIOo$_)3%zT&*oAAb8wSWk=n4iJ{#_MC&A*JQQ9EapuS z_T&@u4|jWN+&;|hX=>jy{gYGOp04%-*Izt?&rJtPXU#p2yrO2TjFV4f++Uts<`-ej z_(aB>;oqC!M{IHpSyx~m1^dI@z9>BnsL$Q^V%%cd|sQa8hv|V)vDRgb5xTz@$fw&(OFyC zHA$O1XwOaB8uz0<*MPcS8P94I_u~5ane~^w^vAKkGg%l^w9qV zwYmFjZ;&28&-z85%vP$+=h0cJ>6^kH=JRM;HJ|fXqg4{tY@xClqq;G{z$twst>SXW zHA%4ZIgUM?NibF2SaX8mcbfdjd9?(t+iRr5t4;3mtaLcwjEP)0TPI4eArxYgH}iCo zg#F$iF5_rPFnky4S8oR^Gq zopkU$CFdmAdgA)y~^%r!PXA#)#| zDPf=QC1LG2r(F_oK0V`qmV_8x66bifbnt!>_j8VP@KBgTVw@|156698+821jv{-2U=|IyOzf3b9I_W!hW zFyi!)*#8pg_Maf#{+CL}X8#S+!HCmW!nkWxe@248$Gx}o%M#r4`&qRaJH^=L(!t2Z z*yj?A_+E$4OUEBRcGlbTd4+WB%@%xelUpOAumlIr7H};hTBaY9&HPYc?v+uRiiOCqu z`>OP7B-rj!ztyV0CIPRMT(2>KeO&_nmUi|xR8!uS4g8xDFz#sd_cbDPF!liV-gS~K zB)<2qPp}hJlh2M4&-)G1u_F}51?Q4vUT%~QXHSXeYNK@Uu@bM(P15n5Bf-wS&Ai?$ z3HO2b-?xMhl8lp(H{4q!;O^&E>G*@YpWCFnAMBimd8)rH*;cZTq)tN2omGEFg3Y|! zrJGkT-MsHg$L4Y0A)PVd@4fat>GW^T_oaj3dsZ@EcS^?>o7dwm>01WvA4uOSX%AI> zw`5q-9<2Hv$#4mCHCOe$5^~;4Ld;RB?~{OUO!m?J309$+ee-~73j5}M)elO**emGF zM~&)-B%Y57>BMI(ekj3a-jAf4w?w*m4@<`eZ>j1>B<39>9p1jGHzhXn9u0WQ0^VcN zu`!0nRa4%RUZMI43Hej!lRTf4jt^&yynieKBQLMXQ_>j^wzI_}pPxv`X`;ljewyHp z^|ac=0r#3eBOQD{iTCNxq~9!|AMewjOJ|?>^d{u(`iKNQXmz*efMre=j9%c)m~n zD4jg8xxYV2Cx^ZP_Gjtj0OlP2A{{O^=kT(0=YYL5hrbFVCwR``Z_>#FTeuFa#~Zrg zn5$PL_&qOy&l>su|GRYT^u=1gs+z)DWBZ2$jI~AQ{2ZzJHHpvJXz84@T~+@xvB8@w z{a+IE4wnvZlL zlh~Z!y8-X`ghzhwNwAsszI4YsLAuBBfpl!<{U_ix1iTNWWAlBn)_S#t22tXkYsoHB4q^_`}Ce zeCM`}bnFO)3g63gct(wq zPHgrOeAd_gqorf#`M_NTzd~(r?y#Kp$G)m7)duJ8qCG~se!6Y@OXnHqXWQ;F!eKnb z+(SATF}-j1R2!VW*^_%or+829tu`2Y65Z=QR(iQT>2(?>I~>G&YoEl2ed#$KFAN;< zUYH;qoEToueWjBtHuo_x!RW*B_LCmr>chU1gu%h)Ip1G8F|m0s93Wjk(O!U0e~vp@ zIyr`WVT#)LU~}B5(us|Yz2Lc{_FkAKo!EmV@R?WpPnV9Jd&FyWpxXT<*jS^3R8zc0 z2dfRn8liiQ4v}7NjeKt$Dmxsn&tVBayf+RP29ILij06KVR+V7ky)jc5{_wFA-?`0_ zjvb*;h4;p60dNqnLA7*ZAl@r;q=UovdLJR3Im70?Qj=g|yt%@_!!@0!HXLkTlOv@Q z6Px$SQPTAj?G^a+=RD_2C&w`E0=4nM=D0^oCpI?rir0|Zdu5??VzYnXv%bC~YNcc6 zJaZ>-#uurrpXhfg?EG#uRzm#6YO_bE9ltK&&}Y45Nn+!S7XyN*ljYDRk&`w9s-`Jg`}U*aAw9p4esjh&ESBZc|hU_*kz z$Nq@?xf54P$HwpYT?v*}dyE8|@6J`y^%MDE_uXlqMqzOHJHuF$+TfdnU6jPms0|Lr zSzrv!Nn2_+wmQL7>Ah0STcZYCZ1&AcCnjgX*og_IsvA2g!31^3YY|2)Y~)NXt4*N!%S#7`&mGgIn!+8^NBYSUFxCs*xwT7Y?BwhC9m2>18}mdS1?lvGjrYC$ zzSk)o{QQKoR(dJt6k*`C;v6KOb<*(zC(ayU>!pL!hI6WPFux1=g!Fq7oIEQeI zO*ZV@c|2#y^>nqt{d?RQ(!to1%*~n7Da;MFE(sWOgU(swtk4Fh?YX1&^Z6|4>@n^Q z&hFXL!NTYBIckIZ`FyT)itqmO)CQw3bl~Ijz#RZ8^_24F{X=#!ICW6Pxec4bt@!-MR4T&v8E^ zogBlsm#K{pHpl&}bYf#;T|9Txz7sE(PHff+KJ#k-&q>G5^O?QydFd3^gXFG|fUzFv zJ||a7FFhw$3FDk#^Evr~bj|=apOdSlgZrF(QF$ z*#7~w^%M1l-Tn_sCkA$Z=X^*y{?1ow_xqzCs=*xL$Gta3`j4dJgN=84)xsW@PCu2> zxg#EtPT`Kgwn+lU9f9t?AC*o#L_bks4D|C@f-wj1*puLoOWz~0dk&ruMhwcmNls6y z4PGhihGd`rSZ#2|v?!8zKRhMOIoSUv!oVv7|DUQ2ZhxN9l? zo#lC9^a0Pm6a7j${@5Jv*V6HCmN4JkwZD;Gdbj^p7_qQ9-``0G_ZfRZIyr-z^Ly#U zHs?j@aKO#^gLHB;=OyW2@XYz6baFN4Ptw8Qc%A+%9batb{Y5$)&b@grs|}7Y*R0iF zrQ?syzJHU>{NwBM@rv54D>nQ7T{`~Q+{dfZnGeRx-#7H}59x5REfuz%u-ByjK=s{{ zW!g8ps{W@iaQJ=Iu9WyJ{7V>iit~J3ZE(cAe@lm_pXh9{zur&-E;ipKZ%WrsbeCZF zJKeXWZKHimXKj-(JFmS|s`+e#3jm__~KS(fa_Wh4^ zaKzY$(v9;RqF*LTaP%C)UMZb(=^Uv!mvH-t%Nc(J2kGSRIDLaSQxmTH?I+uv;=(b% zf54w6J{;eh1Egc;S;8C+luls|u?>=dF^A~xhkrwjA7X5XbnwOUH?~E>!Nyn}i`ruy zns69D{IDPXT{iaHW%Irnt~Sq7iucHt!bFMo2zGO~O1Rj}<==Iii{0zJjdbE*xBs@% z=}T3&|8{EFAG`hex8cOV?&r%6((!k`_<1kwC>v{xpU>_H>G)vt8u9PT>8Da$)@Uc` z6xIma&Jr-z2;F_}BAs{${ZjmFTl*k-&dG)%FE>om4KE~s_f2wr2*nIa- zlYW=_5AXiz!ocC{Ct5@Q4Sb*g>&wWT- zc>de>Q0dsY9~dWpn;a&+P7c_-u7^usDhwX`WQlan2{ro!zk2ETbxDZfJw(692*V#6 zv9S4fmF2>gNq9#=?8VZFeVppsl~c9w8RFw#DV?)hr8b4Li*2R^3_o<@^iAS``>vQJ zopV7f&%tbA&B>t|sKp435Ia)d~ z!0E%^aH-wLLfPo!aS43-hx>rqjE@>F>s>2*rRr};UXg@x7A0}85fhv5xW#H?rx>eC zFm>0B)h8HKf9qSK2LAA|lLP;$l>Xvi`|tjzQuJT`_;38DQuMknKlPoloBg-Pb!5-D Lqv`BVDEI#XoPY6L literal 0 HcmV?d00001 diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender.azshader b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender.azshader index 4676c42e8da1743b54f491e17ccc3347aa0fb277..16db49af1ba018c19dc432a74e38029272a65a5a 100644 GIT binary patch delta 996 zcmX@So_E(3sSR2zEZb6=syFMgRJyT+d8ZbZmu_C`wTc7Ajt!P?fU(zlad2$zx_yEP zCJ-Aesk8l$8q+amjwS4ye`hF3E!}R<$Ji${c|MC6W8CDx0ueU9eBWS4$IYi$?z+OX zt@Y|-nl2#DTr*krCfD?HtxOUip5Nq#0G3VH>sUB~id>#(=-x`0yfJ7QOb@C%h||Aa z@CV}=Y>wsnci>vP__0kO$EFA|I!vD$&aA!tyaHn~EDW~ueqiL_nC_6zxCrWk=|BnSNjmqv-SiQ6`Sb{~xn%3YntLu_knRgy#AqzjhJ+udVr9$h zyB|+)W!P@x#vCp>w@}kb;p^PY`DTN;u=S0`6VQ3(~W6GH1#_z01S^ zjRSuhCU_i7Uh5@0y+DjvW&0j(=9BD`w+6*e&u?OKhK4IhdOJ}1pZ50F?MxqFVUMC~ zA}kVMijU}XeA=?aslwQ97AT;b1hIwjG{)`Oc1-RrNEX4};g2`vZc(v)$u)h-L12(4 jlj>IDOy1ro%nVP{NWN<76*uhFS?>VyRfHfUN$UXsAzyR5 delta 336 zcmdmWMe6W+-VItTELok8Pi@v?sdQsYDU66JtK9xDjj@kuv%s|~*2!Cg7QsX(<}=DS zz&J1^P8={1ptPjUb^~YTW6T_H@?|Hl$>{#J-JXxJPiXq8Viu?E&bCa-a2p(Xm^nC* z44)1Zu-|?mpYf~q_JAEsuY+Nx0>v+IK{;?mx3r=5_}p?@v%K^5yX|$_Oc8?9!y=fq zw*xIph1oOx;ayh8?FCm^{XyQzW1TL1h-DqjXrLT7%s=P~w_o#Oy~2c~Qd(#G=}K0h d*H*eKC*1b?`e=K-HdDCZ^bdWk+N=y9005llg7p9Z diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender_dx12_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender_dx12_0.azshadervariant index 9bf8e7f53fcde322f5ff225146544c70979e16c0..23b0c807bf9bc68cb6ac3b7e255aea8829905ac4 100644 GIT binary patch delta 17 YcmaF=j`96F#tj+e?AubBsu>s<08`=zY5)KL delta 17 ZcmaF=j`96F#tj+e>{*?UPcbks0033Z2lD^` diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender_null_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender_null_0.azshadervariant index 98402384db1e019e435ea7756543150375580091..299490c1bd28c50ad68e8f24e11146bb75b6f6f3 100644 GIT binary patch delta 15 WcmX@ha+YO-8x#Asl%{G11_l5vK?Jz~ delta 15 WcmX@ha+YO-8xwn0=i^fh3=9A-ECoUU diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender_vulkan_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridrender_vulkan_0.azshadervariant index 5caf3084766a8bd2be7d63394f0257af6e304dd6..447f0712d32462d676490ea7496c0233fd1b1b3c 100644 GIT binary patch delta 17 YcmbQZhjHQ_#tmF??AubBsu>s<06s|t(*OVf delta 17 ZcmbQZhjHQ_#tmF?>{*?UPcbks002NV23!CD diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp index f5aaec4faa..539531b5a0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp @@ -115,10 +115,6 @@ namespace AZ // all faces of the cubemap have been rendered, invoke the callback m_callback(m_environmentCubeMapPass->GetTextureData(), m_environmentCubeMapPass->GetTextureFormat()); - // remove the pipeline - m_scene->RemoveRenderPipeline(m_environmentCubeMapPipelineId); - m_environmentCubeMapPass = nullptr; - // restore exposures sceneSrg->SetConstant(m_globalIblExposureConstantIndex, m_previousGlobalIblExposure); sceneSrg->SetConstant(m_skyBoxExposureConstantIndex, m_previousSkyBoxExposure); @@ -223,6 +219,16 @@ namespace AZ } } + void ReflectionProbe::OnRenderEnd() + { + if (m_environmentCubeMapPass && m_environmentCubeMapPass->IsFinished()) + { + // remove the cubemap pipeline + // Note: this must be done here (not in Simulate) to avoid a race condition with other feature processors + m_scene->RemoveRenderPipeline(m_environmentCubeMapPipelineId); + m_environmentCubeMapPass = nullptr; + } + } void ReflectionProbe::SetTransform(const AZ::Transform& transform) { @@ -282,7 +288,7 @@ namespace AZ AZ::RPI::RenderPipelineDescriptor environmentCubeMapPipelineDesc; environmentCubeMapPipelineDesc.m_mainViewTagName = "MainCamera"; - environmentCubeMapPipelineDesc.m_renderSettings.m_multisampleState.m_samples = 4; + environmentCubeMapPipelineDesc.m_renderSettings.m_multisampleState = RPI::RPISystemInterface::Get()->GetApplicationMultisampleState(); environmentCubeMapPipelineDesc.m_renderSettings.m_size.m_width = RPI::EnvironmentCubeMapPass::CubeMapFaceSize; environmentCubeMapPipelineDesc.m_renderSettings.m_size.m_height = RPI::EnvironmentCubeMapPass::CubeMapFaceSize; diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h index 17ef54367b..6ec9368167 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h @@ -75,6 +75,7 @@ namespace AZ void Init(RPI::Scene* scene, ReflectionRenderData* reflectionRenderData); void Simulate(uint32_t probeIndex); + void OnRenderEnd(); const Vector3& GetPosition() const { return m_transform.GetTranslation(); } const AZ::Transform& GetTransform() const { return m_transform; } diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp index 155a159447..cfe807610b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp @@ -166,6 +166,18 @@ namespace AZ } } + void ReflectionProbeFeatureProcessor::OnRenderEnd() + { + // call OnRenderEnd on all reflection probes + for (uint32_t probeIndex = 0; probeIndex < m_reflectionProbes.size(); ++probeIndex) + { + AZStd::shared_ptr& reflectionProbe = m_reflectionProbes[probeIndex]; + AZ_Assert(reflectionProbe.use_count() > 1, "ReflectionProbe found with no corresponding owner, ensure that RemoveProbe() is called before releasing probe handles"); + + reflectionProbe->OnRenderEnd(); + } + } + ReflectionProbeHandle ReflectionProbeFeatureProcessor::AddProbe(const AZ::Transform& transform, bool useParallaxCorrection) { AZStd::shared_ptr reflectionProbe = AZStd::make_shared(); diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.h index ded36f5496..92fb3fe604 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.h @@ -46,6 +46,7 @@ namespace AZ void Activate() override; void Deactivate() override; void Simulate(const FeatureProcessor::SimulatePacket& packet) override; + void OnRenderEnd() override; // find the reflection probe volumes that contain the position using ReflectionProbeVector = AZStd::vector>; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystem.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystem.h index 57f595ccba..dbf70fb0cc 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystem.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystem.h @@ -86,6 +86,8 @@ namespace AZ const RPISystemDescriptor& GetDescriptor() const override; Name GetRenderApiName() const override; uint64_t GetCurrentTick() const override; + void SetApplicationMultisampleState(const RHI::MultisampleState& multisampleState) override; + const RHI::MultisampleState& GetApplicationMultisampleState() const override; // AZ::Debug::TraceMessageBus::Handler overrides... bool OnPreAssert(const char* fileName, int line, const char* func, const char* message) override; @@ -136,6 +138,9 @@ namespace AZ bool m_systemAssetsInitialized = false; uint64_t m_renderTick = 0; + + // Application multisample state + RHI::MultisampleState m_multisampleState; }; } // namespace RPI diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystemInterface.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystemInterface.h index 693185b6d2..7853e8f51e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystemInterface.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RPISystemInterface.h @@ -90,6 +90,10 @@ namespace AZ //! Get the index of current render tick virtual uint64_t GetCurrentTick() const = 0; + + //! Application multisample state + virtual void SetApplicationMultisampleState(const RHI::MultisampleState& multisampleState) = 0; + virtual const RHI::MultisampleState& GetApplicationMultisampleState() const = 0; }; } // namespace RPI diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp index 3416b2895d..57bef2c7e5 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RPISystem.cpp @@ -434,5 +434,29 @@ namespace AZ return m_renderTick; } + void RPISystem::SetApplicationMultisampleState(const RHI::MultisampleState& multisampleState) + { + m_multisampleState = multisampleState; + + bool isNonMsaaPipeline = (m_multisampleState.m_samples == 1); + const char* supervariantName = isNonMsaaPipeline ? AZ::RPI::NoMsaaSupervariantName : ""; + AZ::RPI::ShaderSystemInterface::Get()->SetSupervariantName(AZ::Name(supervariantName)); + + // reinitialize pipelines for all scenes + for (auto& scene : m_scenes) + { + for (auto& renderPipeline : scene->GetRenderPipelines()) + { + renderPipeline->GetRenderSettings().m_multisampleState = multisampleState; + renderPipeline->SetPassNeedsRecreate(); + } + } + } + + const RHI::MultisampleState& RPISystem::GetApplicationMultisampleState() const + { + return m_multisampleState; + } + } //namespace RPI } //namespace AZ diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp index 27d468e64b..638e8da87c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/PreviewRenderer/PreviewRenderer.cpp @@ -63,10 +63,8 @@ namespace AtomToolsFramework pipelineDesc.m_mainViewTagName = "MainCamera"; pipelineDesc.m_name = pipelineName; pipelineDesc.m_rootPassTemplate = "ToolsPipelineRenderToTexture"; + pipelineDesc.m_renderSettings.m_multisampleState = AZ::RPI::RPISystemInterface::Get()->GetApplicationMultisampleState(); - // We have to set the samples to 4 to match the pipeline passes' setting, otherwise it may lead to device lost issue - // [GFX TODO] [ATOM-13551] Default value sand validation required to prevent pipeline crash and device lost - pipelineDesc.m_renderSettings.m_multisampleState.m_samples = 4; m_renderPipeline = AZ::RPI::RenderPipeline::CreateRenderPipeline(pipelineDesc); m_scene->AddRenderPipeline(m_renderPipeline); m_scene->Activate(); From e5800d738a34a2ed2358cef381d3b9b94954cabd Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Wed, 9 Feb 2022 15:27:53 -0800 Subject: [PATCH 042/133] Fix position of newly created UI element (#7510) Signed-off-by: abrmich --- Gems/LyShine/Code/Editor/HierarchyMenu.cpp | 8 ++++++-- Gems/LyShine/Code/Editor/HierarchyWidget.cpp | 6 ++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/Gems/LyShine/Code/Editor/HierarchyMenu.cpp b/Gems/LyShine/Code/Editor/HierarchyMenu.cpp index 004fe53354..4fb09ea1f8 100644 --- a/Gems/LyShine/Code/Editor/HierarchyMenu.cpp +++ b/Gems/LyShine/Code/Editor/HierarchyMenu.cpp @@ -387,7 +387,9 @@ void HierarchyMenu::New_ElementFromSlice(HierarchyWidget* hierarchy, AZ::Vector2 viewportPosition(-1.0f,-1.0f); // indicates no viewport position specified if (optionalPos) { - viewportPosition = QtHelpers::QPointFToVector2(*optionalPos); + // Convert position to render viewport coords + QPointF scaledPosition = *optionalPos * hierarchy->GetEditorWindow()->GetViewport()->WidgetToViewportFactor(); + viewportPosition = QtHelpers::QPointFToVector2(scaledPosition); } SliceMenuHelpers::CreateInstantiateSliceMenu(hierarchy, @@ -405,7 +407,9 @@ void HierarchyMenu::New_ElementFromSlice(HierarchyWidget* hierarchy, AZ::Vector2 viewportPosition(-1.0f,-1.0f); // indicates no viewport position specified if (optionalPos) { - viewportPosition = QtHelpers::QPointFToVector2(*optionalPos); + // Convert position to render viewport coords + QPointF scaledPosition = *optionalPos * hierarchy->GetEditorWindow()->GetViewport()->WidgetToViewportFactor(); + viewportPosition = QtHelpers::QPointFToVector2(scaledPosition); } hierarchy->GetEditorWindow()->GetSliceManager()->InstantiateSliceUsingBrowser(hierarchy, viewportPosition); } diff --git a/Gems/LyShine/Code/Editor/HierarchyWidget.cpp b/Gems/LyShine/Code/Editor/HierarchyWidget.cpp index 30cb7e51dc..cd80e5a278 100644 --- a/Gems/LyShine/Code/Editor/HierarchyWidget.cpp +++ b/Gems/LyShine/Code/Editor/HierarchyWidget.cpp @@ -1239,11 +1239,13 @@ void HierarchyWidget::AddElement(const QTreeWidgetItemRawPtrQList& selectedItems this, selectedItems, childIndex, - [optionalPos](AZ::Entity* element) + [this, optionalPos](AZ::Entity* element) { if (optionalPos) { - EntityHelpers::MoveElementToGlobalPosition(element, *optionalPos); + // Convert position to render viewport coords + QPoint scaledPosition = *optionalPos * GetEditorWindow()->GetViewport()->WidgetToViewportFactor(); + EntityHelpers::MoveElementToGlobalPosition(element, scaledPosition); } }); } From dc5d50a4ce163af54f0547bdf8f223ded1297f6c Mon Sep 17 00:00:00 2001 From: Ken Pruiksma Date: Wed, 9 Feb 2022 17:41:38 -0600 Subject: [PATCH 043/133] Terrain default surface material (#7481) Terrain default surface material This adds the ability to set a default material on detail material regions as a fallback material for when there are no materials for an assigned surface tag, or there's only one surface tag but its weight is less than 1.0. This also fixes some issues - The terrain surface list component now correctly sends notifications on tag changes. - The terrain area material notifications bus now has two separate change notifications - one for material, the other for tag - The terrain renderer will now only consider a single region per point queried instead of any region that might have a matching surface tag. --- .../TerrainSurfaceMaterialsListComponent.cpp | 233 ++++++++++++----- .../TerrainSurfaceMaterialsListComponent.h | 27 +- .../TerrainAreaMaterialRequestBus.h | 34 ++- .../TerrainDetailMaterialManager.cpp | 245 +++++++++++++----- .../TerrainDetailMaterialManager.h | 34 ++- 5 files changed, 437 insertions(+), 136 deletions(-) diff --git a/Gems/Terrain/Code/Source/TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.cpp b/Gems/Terrain/Code/Source/TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.cpp index 5f2a50f903..fc4b821578 100644 --- a/Gems/Terrain/Code/Source/TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.cpp +++ b/Gems/Terrain/Code/Source/TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.cpp @@ -8,21 +8,19 @@ #include -#include -#include #include +#include #include -#include -#include -#include +#include #include +#include +#include #include -#include -#include - #include +#include +#include #include namespace Terrain @@ -38,15 +36,14 @@ namespace Terrain if (auto edit = serialize->GetEditContext()) { - edit->Class("Terrain Surface Gradient Mapping", "Mapping between a surface and a material.") + edit->Class("Terrain surface gradient mapping", "Mapping between a surface and a material.") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) - - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &TerrainSurfaceMaterialMapping::m_surfaceTag, "Surface Tag", "Surface type to map to a material.") - ->DataElement(AZ::Edit::UIHandlers::Default, &TerrainSurfaceMaterialMapping::m_materialAsset, "Material Asset", "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::ShowProductAssetFileName, true) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + + ->DataElement(AZ::Edit::UIHandlers::ComboBox, &TerrainSurfaceMaterialMapping::m_surfaceTag, "Surface tag", "Surface type to map to a material.") + ->DataElement(AZ::Edit::UIHandlers::Default, &TerrainSurfaceMaterialMapping::m_materialAsset, "Material asset", "") + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::ShowProductAssetFileName, true) ; } } @@ -60,7 +57,8 @@ namespace Terrain if (serialize) { serialize->Class() - ->Version(1) + ->Version(2) + ->Field("DefaultMaterial", &TerrainSurfaceMaterialsListConfig::m_defaultSurfaceMaterial) ->Field("Mappings", &TerrainSurfaceMaterialsListConfig::m_surfaceMaterials); AZ::EditContext* edit = serialize->GetEditContext(); @@ -68,10 +66,13 @@ namespace Terrain { edit->Class( "Terrain Surface Material List Component", "Provide mapping between surfaces and render materials.") + ->SetDynamicEditDataProvider(&TerrainSurfaceMaterialsListConfig::GetDynamicData) ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::Show) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->DataElement(AZ::Edit::UIHandlers::Default, &TerrainSurfaceMaterialsListConfig::m_defaultSurfaceMaterial, + "Default Material", "The default material to fall back to where no other material surface mappings exist.") ->DataElement( AZ::Edit::UIHandlers::Default, &TerrainSurfaceMaterialsListConfig::m_surfaceMaterials, "Material Mappings", "Maps surfaces to materials."); @@ -79,6 +80,26 @@ namespace Terrain } } + TerrainSurfaceMaterialsListConfig::TerrainSurfaceMaterialsListConfig() + { + m_hideSurfaceTagData.m_attributes.push_back( + { + AZ::Edit::Attributes::Visibility, + aznew AZ::Edit::AttributeData(AZ::Edit::PropertyVisibility::Hide) + } + ); + } + + const AZ::Edit::ElementData* TerrainSurfaceMaterialsListConfig::GetDynamicData(const void* handlerPtr, const void* elementPtr, const AZ::Uuid& ) + { + const TerrainSurfaceMaterialsListConfig* owner = reinterpret_cast(handlerPtr); + if (elementPtr == &owner->m_defaultSurfaceMaterial.m_surfaceTag) + { + return &owner->m_hideSurfaceTagData; + } + return nullptr; + } + void TerrainSurfaceMaterialsListComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services) { services.push_back(AZ_CRC_CE("TerrainMaterialProviderService")); @@ -116,15 +137,21 @@ namespace Terrain { m_cachedAabb = AZ::Aabb::CreateNull(); + auto checkLoadMaterial = [&](TerrainSurfaceMaterialMapping& material) + { + if (material.m_materialAsset.GetId().IsValid()) + { + material.m_active = false; + material.m_materialAsset.QueueLoad(); + AZ::Data::AssetBus::MultiHandler::BusConnect(material.m_materialAsset.GetId()); + } + }; + // Set all the materials as inactive and start loading. + checkLoadMaterial(m_configuration.m_defaultSurfaceMaterial); for (auto& surfaceMaterialMapping : m_configuration.m_surfaceMaterials) { - if (surfaceMaterialMapping.m_materialAsset.GetId().IsValid()) - { - surfaceMaterialMapping.m_active = false; - surfaceMaterialMapping.m_materialAsset.QueueLoad(); - AZ::Data::AssetBus::MultiHandler::BusConnect(surfaceMaterialMapping.m_materialAsset.GetId()); - } + checkLoadMaterial(surfaceMaterialMapping); } // Announce initial shape using OnShapeChanged @@ -135,24 +162,35 @@ namespace Terrain { TerrainAreaMaterialRequestBus::Handler::BusDisconnect(); + auto checkResetMaterial = [&](TerrainSurfaceMaterialMapping& material) + { + if (material.m_materialAsset.GetId().IsValid()) + { + AZ::Data::AssetBus::MultiHandler::BusDisconnect(material.m_materialAsset.GetId()); + material.m_materialAsset.Release(); + material.m_materialInstance.reset(); + material.m_activeMaterialAssetId = AZ::Data::AssetId(); + } + }; + + checkResetMaterial(m_configuration.m_defaultSurfaceMaterial); for (auto& surfaceMaterialMapping : m_configuration.m_surfaceMaterials) { - if (surfaceMaterialMapping.m_materialAsset.GetId().IsValid()) - { - AZ::Data::AssetBus::MultiHandler::BusDisconnect(surfaceMaterialMapping.m_materialAsset.GetId()); - surfaceMaterialMapping.m_materialAsset.Release(); - surfaceMaterialMapping.m_materialInstance.reset(); - surfaceMaterialMapping.m_activeMaterialAssetId = AZ::Data::AssetId(); - } + checkResetMaterial(surfaceMaterialMapping); } HandleMaterialStateChanges(); } - int TerrainSurfaceMaterialsListComponent::CountMaterialIDInstances(AZ::Data::AssetId id) const + int TerrainSurfaceMaterialsListComponent::CountMaterialIdInstances(AZ::Data::AssetId id) const { int count = 0; + if (m_configuration.m_defaultSurfaceMaterial.m_activeMaterialAssetId == id) + { + count++; + } + for (const auto& surfaceMaterialMapping : m_configuration.m_surfaceMaterials) { if (surfaceMaterialMapping.m_activeMaterialAssetId == id) @@ -169,28 +207,63 @@ namespace Terrain bool anyMaterialIsActive = false; bool anyMaterialWasAlreadyActive = false; - for (auto& surfaceMaterialMapping : m_configuration.m_surfaceMaterials) { - const bool wasPreviouslyActive = surfaceMaterialMapping.m_active; - const bool isNowActive = (surfaceMaterialMapping.m_materialInstance != nullptr); + // Handle default material first + auto& defaultMaterial = m_configuration.m_defaultSurfaceMaterial; - if (wasPreviouslyActive) - { - anyMaterialWasAlreadyActive = true; - } + const bool wasPreviouslyActive = defaultMaterial.m_active; + defaultMaterial.m_active = (defaultMaterial.m_materialInstance != nullptr); - if (isNowActive) - { - anyMaterialIsActive = true; - } - - surfaceMaterialMapping.m_active = isNowActive; - - if (!wasPreviouslyActive && !isNowActive) + anyMaterialWasAlreadyActive = wasPreviouslyActive; + anyMaterialIsActive = defaultMaterial.m_active; + + if (!wasPreviouslyActive && !defaultMaterial.m_active) { // A material has been assigned but has not yet completed loading. } - else if (!wasPreviouslyActive && isNowActive) + else if (!wasPreviouslyActive && defaultMaterial.m_active) + { + TerrainAreaMaterialNotificationBus::Broadcast( + &TerrainAreaMaterialNotificationBus::Events::OnTerrainDefaultSurfaceMaterialCreated, GetEntityId(), + defaultMaterial.m_materialInstance); + defaultMaterial.m_previousChangeId = defaultMaterial.m_materialInstance->GetCurrentChangeId(); + } + else if (wasPreviouslyActive && !defaultMaterial.m_active) + { + // Don't disconnect from the AssetBus if this material is mapped more than once. + if (CountMaterialIdInstances(defaultMaterial.m_activeMaterialAssetId) == 1) + { + AZ::Data::AssetBus::MultiHandler::BusDisconnect(defaultMaterial.m_activeMaterialAssetId); + } + defaultMaterial = {}; + + TerrainAreaMaterialNotificationBus::Broadcast( + &TerrainAreaMaterialNotificationBus::Events::OnTerrainDefaultSurfaceMaterialDestroyed, GetEntityId()); + } + else if (defaultMaterial.m_materialInstance->GetAssetId() != defaultMaterial.m_activeMaterialAssetId || + defaultMaterial.m_materialInstance->GetCurrentChangeId() != defaultMaterial.m_previousChangeId) + { + defaultMaterial.m_previousChangeId = defaultMaterial.m_materialInstance->GetCurrentChangeId(); + defaultMaterial.m_activeMaterialAssetId = defaultMaterial.m_materialInstance->GetAssetId(); + + TerrainAreaMaterialNotificationBus::Broadcast( + &TerrainAreaMaterialNotificationBus::Events::OnTerrainDefaultSurfaceMaterialChanged, GetEntityId(), defaultMaterial.m_materialInstance); + } + } + + for (auto& surfaceMaterialMapping : m_configuration.m_surfaceMaterials) + { + const bool wasPreviouslyActive = surfaceMaterialMapping.m_active; + surfaceMaterialMapping.m_active = surfaceMaterialMapping.m_materialInstance != nullptr; + + anyMaterialWasAlreadyActive = anyMaterialWasAlreadyActive || wasPreviouslyActive; + anyMaterialIsActive = anyMaterialIsActive || surfaceMaterialMapping.m_active; + + if (!wasPreviouslyActive && !surfaceMaterialMapping.m_active) + { + // A material has been assigned but has not yet completed loading. + } + else if (!wasPreviouslyActive && surfaceMaterialMapping.m_active) { // Remember the asset id so we can disconnect from the AssetBus if the material asset is removed. surfaceMaterialMapping.m_activeMaterialAssetId = surfaceMaterialMapping.m_materialAsset.GetId(); @@ -199,27 +272,47 @@ namespace Terrain &TerrainAreaMaterialNotificationBus::Events::OnTerrainSurfaceMaterialMappingCreated, GetEntityId(), surfaceMaterialMapping.m_surfaceTag, surfaceMaterialMapping.m_materialInstance); + + surfaceMaterialMapping.m_previousChangeId = surfaceMaterialMapping.m_materialInstance->GetCurrentChangeId(); + surfaceMaterialMapping.m_previousTag = surfaceMaterialMapping.m_surfaceTag; } - else if (wasPreviouslyActive && !isNowActive) + else if (wasPreviouslyActive && !surfaceMaterialMapping.m_active) { // Don't disconnect from the AssetBus if this material is mapped more than once. - if (CountMaterialIDInstances(surfaceMaterialMapping.m_activeMaterialAssetId) == 1) + if (CountMaterialIdInstances(surfaceMaterialMapping.m_activeMaterialAssetId) == 1) { AZ::Data::AssetBus::MultiHandler::BusDisconnect(surfaceMaterialMapping.m_activeMaterialAssetId); } - surfaceMaterialMapping.m_activeMaterialAssetId = AZ::Data::AssetId(); + surfaceMaterialMapping.m_activeMaterialAssetId = {}; + surfaceMaterialMapping.m_previousChangeId = AZ::RPI::Material::DEFAULT_CHANGE_ID; + surfaceMaterialMapping.m_previousTag = {}; TerrainAreaMaterialNotificationBus::Broadcast( &TerrainAreaMaterialNotificationBus::Events::OnTerrainSurfaceMaterialMappingDestroyed, GetEntityId(), surfaceMaterialMapping.m_surfaceTag); } - else + else { - TerrainAreaMaterialNotificationBus::Broadcast( - &TerrainAreaMaterialNotificationBus::Events::OnTerrainSurfaceMaterialMappingChanged, GetEntityId(), - surfaceMaterialMapping.m_surfaceTag, - surfaceMaterialMapping.m_materialInstance); + if (surfaceMaterialMapping.m_previousTag != surfaceMaterialMapping.m_surfaceTag) + { + TerrainAreaMaterialNotificationBus::Broadcast( + &TerrainAreaMaterialNotificationBus::Events::OnTerrainSurfaceMaterialMappingTagChanged, GetEntityId(), + surfaceMaterialMapping.m_previousTag, + surfaceMaterialMapping.m_surfaceTag); + surfaceMaterialMapping.m_previousTag = surfaceMaterialMapping.m_surfaceTag; + } + if (surfaceMaterialMapping.m_materialInstance->GetAssetId() != surfaceMaterialMapping.m_activeMaterialAssetId || + surfaceMaterialMapping.m_materialInstance->GetCurrentChangeId() != surfaceMaterialMapping.m_previousChangeId) + { + surfaceMaterialMapping.m_previousChangeId = surfaceMaterialMapping.m_materialInstance->GetCurrentChangeId(); + surfaceMaterialMapping.m_activeMaterialAssetId = surfaceMaterialMapping.m_materialInstance->GetAssetId(); + + TerrainAreaMaterialNotificationBus::Broadcast( + &TerrainAreaMaterialNotificationBus::Events::OnTerrainSurfaceMaterialMappingMaterialChanged, GetEntityId(), + surfaceMaterialMapping.m_surfaceTag, + surfaceMaterialMapping.m_materialInstance); + } } } @@ -290,14 +383,28 @@ namespace Terrain void TerrainSurfaceMaterialsListComponent::OnAssetReady(AZ::Data::Asset asset) { // Find the missing material instance with the correct id. - for (auto& surfaceMaterialMapping : m_configuration.m_surfaceMaterials) + auto checkUpdateMaterialAsset = [](TerrainSurfaceMaterialMapping& mapping, const AZ::Data::Asset& asset) -> bool { - if (surfaceMaterialMapping.m_materialAsset.GetId() == asset.GetId() && - (!surfaceMaterialMapping.m_materialInstance || - surfaceMaterialMapping.m_materialInstance->GetAssetId() != surfaceMaterialMapping.m_materialAsset.GetId())) + if (mapping.m_materialAsset.GetId() == asset.GetId() && + (!mapping.m_materialInstance || mapping.m_materialInstance->GetAssetId() != mapping.m_materialAsset.GetId())) { - surfaceMaterialMapping.m_materialInstance = AZ::RPI::Material::FindOrCreate(surfaceMaterialMapping.m_materialAsset); - surfaceMaterialMapping.m_materialAsset.Release(); + mapping.m_materialInstance = AZ::RPI::Material::FindOrCreate(mapping.m_materialAsset); + mapping.m_materialAsset.Release(); + return true; + } + return false; + }; + + // First check the default material + if (!checkUpdateMaterialAsset(m_configuration.m_defaultSurfaceMaterial, asset)) + { + // If the default materail wasn't updated, then check all the surface material mappings. + for (auto& surfaceMaterialMapping : m_configuration.m_surfaceMaterials) + { + if (checkUpdateMaterialAsset(surfaceMaterialMapping, asset)) + { + break; + } } } HandleMaterialStateChanges(); diff --git a/Gems/Terrain/Code/Source/TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.h b/Gems/Terrain/Code/Source/TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.h index 0e32cb12c0..96a7da60de 100644 --- a/Gems/Terrain/Code/Source/TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.h +++ b/Gems/Terrain/Code/Source/TerrainRenderer/Components/TerrainSurfaceMaterialsListComponent.h @@ -8,15 +8,18 @@ #pragma once -#include -#include #include #include +#include + +#include +#include + #include + #include #include - namespace LmbrCentral { template @@ -27,16 +30,20 @@ namespace Terrain { struct TerrainSurfaceMaterialMapping final { - public: AZ_CLASS_ALLOCATOR(TerrainSurfaceMaterialMapping, AZ::SystemAllocator, 0); AZ_RTTI(TerrainSurfaceMaterialMapping, "{37D2A586-CDDD-4FB7-A7D6-0B4CC575AB8C}"); static void Reflect(AZ::ReflectContext* context); - SurfaceData::SurfaceTag m_surfaceTag; - AZ::Data::AssetId m_activeMaterialAssetId; AZ::Data::Asset m_materialAsset; AZ::Data::Instance m_materialInstance; + AZ::Data::AssetId m_activeMaterialAssetId; + AZ::RPI::Material::ChangeId m_previousChangeId = AZ::RPI::Material::DEFAULT_CHANGE_ID; + + // Surface tags not used by default material + SurfaceData::SurfaceTag m_surfaceTag; + SurfaceData::SurfaceTag m_previousTag; + bool m_active = false; }; @@ -47,7 +54,13 @@ namespace Terrain AZ_RTTI(TerrainSurfaceMaterialsListConfig, "{68A1CB1B-C835-4C3A-8D1C-08692E07711A}", AZ::ComponentConfig); static void Reflect(AZ::ReflectContext* context); + TerrainSurfaceMaterialsListConfig(); + + TerrainSurfaceMaterialMapping m_defaultSurfaceMaterial; AZStd::vector m_surfaceMaterials; + private: + static const AZ::Edit::ElementData* GetDynamicData(const void* handlerPtr, const void* elementPtr, const AZ::Uuid& elementType); + AZ::Edit::ElementData m_hideSurfaceTagData; }; class TerrainSurfaceMaterialsListComponent @@ -78,7 +91,7 @@ namespace Terrain private: void HandleMaterialStateChanges(); - int CountMaterialIDInstances(AZ::Data::AssetId id) const; + int CountMaterialIdInstances(AZ::Data::AssetId id) const; //////////////////////////////////////////////////////////////////////// // ShapeComponentNotificationsBus diff --git a/Gems/Terrain/Code/Source/TerrainRenderer/TerrainAreaMaterialRequestBus.h b/Gems/Terrain/Code/Source/TerrainRenderer/TerrainAreaMaterialRequestBus.h index ae36a2639e..a2225702ef 100644 --- a/Gems/Terrain/Code/Source/TerrainRenderer/TerrainAreaMaterialRequestBus.h +++ b/Gems/Terrain/Code/Source/TerrainRenderer/TerrainAreaMaterialRequestBus.h @@ -45,6 +45,27 @@ namespace Terrain static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; ////////////////////////////////////////////////////////////////////////// + //! The default surface material has been assigned and loaded + virtual void OnTerrainDefaultSurfaceMaterialCreated( + [[maybe_unused]] AZ::EntityId entityId, + [[maybe_unused]] AZ::Data::Instance material) + { + } + + //! The default surface material has been unassigned + virtual void OnTerrainDefaultSurfaceMaterialDestroyed( + [[maybe_unused]] AZ::EntityId entityId) + { + } + + //! The default surface material has been changed to a different material + virtual void OnTerrainDefaultSurfaceMaterialChanged( + [[maybe_unused]] AZ::EntityId entityId, + [[maybe_unused]] AZ::Data::Instance newMaterial) + { + } + + //! A loaded material mapped to a valid surface tag has been created virtual void OnTerrainSurfaceMaterialMappingCreated( [[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] SurfaceData::SurfaceTag surface, @@ -52,19 +73,30 @@ namespace Terrain { } + //! Either the material or surface tag was unassigned, making this mapping invalid virtual void OnTerrainSurfaceMaterialMappingDestroyed( [[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] SurfaceData::SurfaceTag surface) { } - virtual void OnTerrainSurfaceMaterialMappingChanged( + //! The surface tag has changed to tag for an existing material + virtual void OnTerrainSurfaceMaterialMappingTagChanged( + [[maybe_unused]] AZ::EntityId entityId, + [[maybe_unused]] SurfaceData::SurfaceTag oldSurface, + [[maybe_unused]] SurfaceData::SurfaceTag newSurface) + { + } + + //! The material has changed for an existing surface tag + virtual void OnTerrainSurfaceMaterialMappingMaterialChanged( [[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] SurfaceData::SurfaceTag surface, [[maybe_unused]] AZ::Data::Instance material) { } + //! The bounds of this set of surface material mappings has changed virtual void OnTerrainSurfaceMaterialMappingRegionChanged( [[maybe_unused]] AZ::EntityId entityId, [[maybe_unused]] const AZ::Aabb& oldRegion, diff --git a/Gems/Terrain/Code/Source/TerrainRenderer/TerrainDetailMaterialManager.cpp b/Gems/Terrain/Code/Source/TerrainRenderer/TerrainDetailMaterialManager.cpp index a00d2efe59..f817c138a7 100644 --- a/Gems/Terrain/Code/Source/TerrainRenderer/TerrainDetailMaterialManager.cpp +++ b/Gems/Terrain/Code/Source/TerrainRenderer/TerrainDetailMaterialManager.cpp @@ -106,6 +106,8 @@ namespace Terrain return; } + InitializePassthroughDetailMaterial(); + ClipmapBoundsDescriptor desc; desc.m_clipmapUpdateMultiple = 1; desc.m_clipToWorldScale = DetailTextureScale; @@ -260,20 +262,73 @@ namespace Terrain m_dirtyDetailRegion.AddAabb(dirtyRegion); } } + + bool TerrainDetailMaterialManager::ForSurfaceTag(DetailMaterialListRegion& materialRegion, + SurfaceData::SurfaceTag surfaceTag, DefaultMaterialSurfaceCallback callback) + { + for (DetailMaterialSurface& surface : materialRegion.m_materialsForSurfaces) + { + if (surface.m_surfaceTag == surfaceTag) + { + callback(surface); + return true; + } + } + return false; + } + void TerrainDetailMaterialManager::OnTerrainDefaultSurfaceMaterialCreated(AZ::EntityId entityId, MaterialInstance material) + { + DetailMaterialListRegion& materialRegion = FindOrCreateByEntityId(entityId, m_detailMaterialRegions); + AZ_Error("TerrainDetailMaterialManager", materialRegion.m_defaultDetailMaterialId == InvalidDetailMaterailId, + "Default detail material created but was already set for this region."); + + materialRegion.m_defaultDetailMaterialId = CreateOrUpdateDetailMaterial(material); + m_detailMaterials.GetData(materialRegion.m_defaultDetailMaterialId).refCount++; + m_dirtyDetailRegion.AddAabb(materialRegion.m_region); + } + + void TerrainDetailMaterialManager::OnTerrainDefaultSurfaceMaterialDestroyed(AZ::EntityId entityId) + { + DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions); + if (materialRegion == nullptr) + { + AZ_Assert(false, "OnTerrainDefaultSurfaceMaterialDestroyed() called for region that doesn't exist."); + return; + } + + CheckDetailMaterialForDeletion(materialRegion->m_defaultDetailMaterialId); + materialRegion->m_defaultDetailMaterialId = InvalidDetailMaterailId; + } + + void TerrainDetailMaterialManager::OnTerrainDefaultSurfaceMaterialChanged(AZ::EntityId entityId, MaterialInstance newMaterial) + { + DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions); + if (materialRegion == nullptr) + { + AZ_Assert(false, "OnTerrainDefaultSurfaceMaterialChanged() called for region that doesn't exist."); + return; + } + + // Update existing entry or create a new material entry + uint16_t materialId = CreateOrUpdateDetailMaterial(newMaterial); + if (materialRegion->m_defaultDetailMaterialId != materialId) + { + ++m_detailMaterials.GetData(materialId).refCount; + CheckDetailMaterialForDeletion(materialRegion->m_defaultDetailMaterialId); + materialRegion->m_defaultDetailMaterialId = materialId; + } + } + void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingCreated(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag, MaterialInstance material) { DetailMaterialListRegion& materialRegion = FindOrCreateByEntityId(entityId, m_detailMaterialRegions); // Validate that the surface tag is new - for (DetailMaterialSurface& surface : materialRegion.m_materialsForSurfaces) + ForSurfaceTag(materialRegion, surfaceTag, [](DetailMaterialSurface&) { - if (surface.m_surfaceTag == surfaceTag) - { - AZ_Error(TerrainDetailMaterialManagerName, false, "Already have a surface material mapping for this surface tag."); - return; - } - } + AZ_Error(TerrainDetailMaterialManagerName, false, "Already have a surface material mapping for this surface tag."); + }); uint16_t detailMaterialId = CreateOrUpdateDetailMaterial(material); materialRegion.m_materialsForSurfaces.push_back({ surfaceTag, detailMaterialId }); @@ -284,52 +339,71 @@ namespace Terrain void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingDestroyed(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag) { DetailMaterialListRegion& materialRegion = FindOrCreateByEntityId(entityId, m_detailMaterialRegions); - - for (DetailMaterialSurface& surface : materialRegion.m_materialsForSurfaces) + + [[maybe_unused]] bool found = ForSurfaceTag(materialRegion, surfaceTag, + [&](DetailMaterialSurface& surface) { - if (surface.m_surfaceTag == surfaceTag) - { - CheckDetailMaterialForDeletion(surface.m_detailMaterialId); + CheckDetailMaterialForDeletion(surface.m_detailMaterialId); - if (surface.m_surfaceTag != materialRegion.m_materialsForSurfaces.back().m_surfaceTag) - { - AZStd::swap(surface, materialRegion.m_materialsForSurfaces.back()); - } - materialRegion.m_materialsForSurfaces.pop_back(); - m_dirtyDetailRegion.AddAabb(materialRegion.m_region); - return; + if (surface.m_surfaceTag != materialRegion.m_materialsForSurfaces.back().m_surfaceTag) + { + AZStd::swap(surface, materialRegion.m_materialsForSurfaces.back()); } + materialRegion.m_materialsForSurfaces.pop_back(); + m_dirtyDetailRegion.AddAabb(materialRegion.m_region); + return; + }); + + AZ_Error(TerrainDetailMaterialManagerName, found, "Could not find surface tag to destroy for OnTerrainSurfaceMaterialMappingDestroyed()."); + } + + void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingMaterialChanged( + AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag, MaterialInstance material) + { + DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions); + if (materialRegion == nullptr) + { + AZ_Assert(false, "OnTerrainSurfaceMaterialMappingMaterialChanged() called for region that doesn't exist."); + return; } - AZ_Error(TerrainDetailMaterialManagerName, false, "Could not find surface tag to destroy for OnTerrainSurfaceMaterialMappingDestroyed()."); + + // Update existing entry or create a new material entry + uint16_t materialId = CreateOrUpdateDetailMaterial(material); + + [[maybe_unused]] bool found = ForSurfaceTag(*materialRegion, surfaceTag, + [&](DetailMaterialSurface& surface) + { + if (surface.m_detailMaterialId != materialId) + { + // Updated material was a different asset than the old material, decrement ref count and + // delete if no other surface tags are using it. + ++m_detailMaterials.GetData(materialId).refCount; + CheckDetailMaterialForDeletion(surface.m_detailMaterialId); + surface.m_detailMaterialId = materialId; + } + m_dirtyDetailRegion.AddAabb(materialRegion->m_region); + }); + + AZ_Assert(found, "OnTerrainSurfaceMaterialMappingMaterialChanged() called for tag that doesn't exist."); } - void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingChanged(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag, MaterialInstance material) + void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingTagChanged( + AZ::EntityId entityId, SurfaceData::SurfaceTag oldTag, SurfaceData::SurfaceTag newTag) { - DetailMaterialListRegion& materialRegion = FindOrCreateByEntityId(entityId, m_detailMaterialRegions); - - bool found = false; - uint16_t materialId = CreateOrUpdateDetailMaterial(material); - for (DetailMaterialSurface& surface : materialRegion.m_materialsForSurfaces) + DetailMaterialListRegion* materialRegion = FindByEntityId(entityId, m_detailMaterialRegions); + if (materialRegion == nullptr) { - if (surface.m_surfaceTag == surfaceTag) - { - found = true; - if (surface.m_detailMaterialId != materialId) - { - ++m_detailMaterials.GetData(materialId).refCount; - CheckDetailMaterialForDeletion(surface.m_detailMaterialId); - surface.m_detailMaterialId = materialId; - } - break; - } + AZ_Assert(false, "OnTerrainSurfaceMaterialMappingTagChanged() called for region that doesn't exist."); + return; } - - if (!found) + + [[maybe_unused]] bool found = ForSurfaceTag(*materialRegion, oldTag, + [&](DetailMaterialSurface& surface) { - ++m_detailMaterials.GetData(materialId).refCount; - materialRegion.m_materialsForSurfaces.push_back({ surfaceTag, materialId }); - } - m_dirtyDetailRegion.AddAabb(materialRegion.m_region); + surface.m_surfaceTag = newTag; + m_dirtyDetailRegion.AddAabb(materialRegion->m_region); + }); + AZ_Assert(found, "OnTerrainSurfaceMaterialMappingTagChanged() called for tag that doesn't exist."); } void TerrainDetailMaterialManager::OnTerrainSurfaceMaterialMappingRegionChanged(AZ::EntityId entityId, const AZ::Aabb& oldRegion, const AZ::Aabb& newRegion) @@ -667,23 +741,38 @@ namespace Terrain bool isFirstMaterial = true; float firstWeight = 0.0f; AZ::Vector2 position(surfacePoint.m_position.GetX(), surfacePoint.m_position.GetY()); + const DetailMaterialListRegion* region = FindRegionForPosition(position); + + if (region == nullptr) + { + pixels.at(index).m_material1 = m_passthroughMaterialId; + ++index; + return; + } + for (const auto& surfaceTagWeight : surfacePoint.m_surfaceTags) { if (surfaceTagWeight.m_weight > 0.0f) { AZ::Crc32 surfaceType = surfaceTagWeight.m_surfaceType; - uint16_t materialId = GetDetailMaterialForSurfaceTypeAndPosition(surfaceType, position); - if (materialId != m_detailMaterials.NoFreeSlot && materialId < 255) + uint16_t materialId = GetDetailMaterialForSurfaceType(*region, surfaceType); + if (materialId < 255) { if (isFirstMaterial) { + // First material is valid. Save its weight to calculate blend later pixels.at(index).m_material1 = aznumeric_cast(materialId); firstWeight = surfaceTagWeight.m_weight; - // m_blend only needs to be calculated is material 2 is found, otherwise the initial value of 0 is correct. isFirstMaterial = false; + static constexpr float MaxValueBeforeRounding = 254.5f / 255.0f; + if (firstWeight >= MaxValueBeforeRounding) + { + break; + } } else { + // Second material is valid, weight is relative based on first material's weight. pixels.at(index).m_material2 = aznumeric_cast(materialId); float totalWeight = firstWeight + surfaceTagWeight.m_weight; float blendWeight = 1.0f - (firstWeight / totalWeight); @@ -691,11 +780,37 @@ namespace Terrain break; } } + continue; // search for second material } else { - break; // since the list is ordered, no other materials are in the list with positive weights. + // No more valid materials in list since surfaceTagWeight is ordered. + + uint8_t defaultMaterial = region->m_defaultDetailMaterialId == InvalidDetailMaterailId ? m_passthroughMaterialId : + aznumeric_cast(m_detailMaterials.GetData(region->m_defaultDetailMaterialId).m_detailMaterialBufferIndex); + + if (isFirstMaterial) + { + // Only one material and it's the default material. + pixels.at(index).m_material1 = defaultMaterial; + } + else + { + // Second material is default, weight is exactly what the first material requested + pixels.at(index).m_material2 = defaultMaterial; + float blendWeight = 1.0f - AZStd::clamp(firstWeight, 0.0f, 1.0f); + pixels.at(index).m_blend = aznumeric_cast(AZStd::round(blendWeight * 255.0f)); + } } + + if (pixels.at(index).m_material1 == pixels.at(index).m_material2) + { + // If the materials are the same, then make the blend 100% on the first id so the shader + // doesn't blend identical materials + pixels.at(index).m_blend = 0; + } + + break; } ++index; }; @@ -723,23 +838,37 @@ namespace Terrain m_detailTextureImage->UpdateImageContents(imageUpdateRequest); } - - uint16_t TerrainDetailMaterialManager::GetDetailMaterialForSurfaceTypeAndPosition(AZ::Crc32 surfaceType, const AZ::Vector2& position) + + uint16_t TerrainDetailMaterialManager::GetDetailMaterialForSurfaceType(const DetailMaterialListRegion& materialRegion, AZ::Crc32 surfaceType) const + { + for (const auto& materialSurface : materialRegion.m_materialsForSurfaces) + { + if (materialSurface.m_surfaceTag == surfaceType) + { + return m_detailMaterials.GetData(materialSurface.m_detailMaterialId).m_detailMaterialBufferIndex; + } + } + return InvalidDetailMaterailId; + } + + auto TerrainDetailMaterialManager::FindRegionForPosition(const AZ::Vector2& position) const -> const DetailMaterialListRegion* { for (const auto& materialRegion : m_detailMaterialRegions.GetDataVector()) { if (materialRegion.m_region.Contains(AZ::Vector3(position.GetX(), position.GetY(), 0.0f))) { - for (const auto& materialSurface : materialRegion.m_materialsForSurfaces) - { - if (materialSurface.m_surfaceTag == surfaceType) - { - return m_detailMaterials.GetData(materialSurface.m_detailMaterialId).m_detailMaterialBufferIndex; - } - } + return &materialRegion; } } - return m_detailMaterials.NoFreeSlot; + return nullptr; + } + + void TerrainDetailMaterialManager::InitializePassthroughDetailMaterial() + { + m_passthroughMaterialId = aznumeric_cast(m_detailMaterialShaderData.Reserve()); + DetailMaterialShaderData& materialShaderData = m_detailMaterialShaderData.GetElement(m_passthroughMaterialId); + // Material defaults to white (1.0, 1.0, 1.0), set the blend mode to multiply so it passes through to the macro material. + materialShaderData.m_flags = DetailTextureFlags::BlendModeMultiply; } auto TerrainDetailMaterialManager::FindByEntityId(AZ::EntityId entityId, AZ::Render::IndexedDataVector& container) @@ -784,5 +913,5 @@ namespace Terrain } AZ_Assert(false, "Entity Id not found in container.") } - + } diff --git a/Gems/Terrain/Code/Source/TerrainRenderer/TerrainDetailMaterialManager.h b/Gems/Terrain/Code/Source/TerrainRenderer/TerrainDetailMaterialManager.h index 3f63812e47..16423251ec 100644 --- a/Gems/Terrain/Code/Source/TerrainRenderer/TerrainDetailMaterialManager.h +++ b/Gems/Terrain/Code/Source/TerrainRenderer/TerrainDetailMaterialManager.h @@ -11,6 +11,7 @@ #include #include #include +#include #include @@ -151,7 +152,11 @@ namespace Terrain AZ::EntityId m_entityId; AZ::Aabb m_region{AZ::Aabb::CreateNull()}; AZStd::vector m_materialsForSurfaces; + uint16_t m_defaultDetailMaterialId; }; + + using DetailMaterialContainer = AZ::Render::IndexedDataVector; + static constexpr auto InvalidDetailMaterailId = DetailMaterialContainer::NoFreeSlot; // System-level parameters static constexpr int32_t DetailTextureSize{ 1024 }; @@ -162,9 +167,14 @@ namespace Terrain void OnTerrainDataChanged(const AZ::Aabb& dirtyRegion, TerrainDataChangedMask dataChangedMask) override; // TerrainAreaMaterialNotificationBus overrides... + void OnTerrainDefaultSurfaceMaterialCreated(AZ::EntityId entityId, AZ::Data::Instance material) override; + void OnTerrainDefaultSurfaceMaterialDestroyed(AZ::EntityId entityId) override; + void OnTerrainDefaultSurfaceMaterialChanged(AZ::EntityId entityId, AZ::Data::Instance newMaterial) override; void OnTerrainSurfaceMaterialMappingCreated(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag, MaterialInstance material) override; void OnTerrainSurfaceMaterialMappingDestroyed(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag) override; - void OnTerrainSurfaceMaterialMappingChanged(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag, MaterialInstance material) override; + void OnTerrainSurfaceMaterialMappingMaterialChanged(AZ::EntityId entityId, SurfaceData::SurfaceTag surfaceTag, MaterialInstance material) override; + void OnTerrainSurfaceMaterialMappingTagChanged( + AZ::EntityId entityId, SurfaceData::SurfaceTag oldSurfaceTag, SurfaceData::SurfaceTag newSurfaceTag) override; void OnTerrainSurfaceMaterialMappingRegionChanged(AZ::EntityId entityId, const AZ::Aabb& oldRegion, const AZ::Aabb& newRegion) override; //! Removes all images from all detail materials from the bindless image array @@ -186,22 +196,32 @@ namespace Terrain //! Updates the detail texture in a given area void UpdateDetailTexture(const AZ::Aabb& worldUpdateAabb, const Aabb2i& textureUpdateAabb); - //! Finds the detail material Id for a surface type and position - uint16_t GetDetailMaterialForSurfaceTypeAndPosition(AZ::Crc32 surfaceType, const AZ::Vector2& position); + //! Finds the detail material Id for a region and surface type + uint16_t GetDetailMaterialForSurfaceType(const DetailMaterialListRegion& materialRegion, AZ::Crc32 surfaceType) const; + //! Finds a region for a position. Returns nullptr if none found. + const DetailMaterialListRegion* FindRegionForPosition(const AZ::Vector2& position) const; + + //! Initializes shader data for the default passthrough material which is used when no other detail material is found. + void InitializePassthroughDetailMaterial(); + + using DefaultMaterialSurfaceCallback = AZStd::function; + bool ForSurfaceTag(DetailMaterialListRegion& materialRegion, + SurfaceData::SurfaceTag surfaceTag, DefaultMaterialSurfaceCallback callback); DetailMaterialListRegion* FindByEntityId(AZ::EntityId entityId, AZ::Render::IndexedDataVector& container); DetailMaterialListRegion& FindOrCreateByEntityId(AZ::EntityId entityId, AZ::Render::IndexedDataVector& container); void RemoveByEntityId(AZ::EntityId entityId, AZ::Render::IndexedDataVector& container); - + AZStd::shared_ptr m_bindlessImageHandler; AZ::Data::Instance m_detailTextureImage; - AZ::Render::IndexedDataVector m_detailMaterials; + DetailMaterialContainer m_detailMaterials; AZ::Render::IndexedDataVector m_detailMaterialRegions; AZ::Render::SparseVector m_detailMaterialShaderData; AZ::Render::GpuBufferHandler m_detailMaterialDataBuffer; - + uint8_t m_passthroughMaterialId = 0; + AZ::Aabb m_dirtyDetailRegion{ AZ::Aabb::CreateNull() }; ClipmapBounds m_detailMaterialIdBounds; @@ -212,6 +232,6 @@ namespace Terrain bool m_isInitialized{ false }; bool m_detailMaterialBufferNeedsUpdate{ false }; bool m_detailImageNeedsUpdate{ false }; - + }; } From 214b53de7398cdc113985b25e9c66280f501f2bf Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Wed, 9 Feb 2022 16:22:44 -0800 Subject: [PATCH 044/133] Fixed a unit test. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../Material/MaterialTypeSourceDataTests.cpp | 44 ++++++++----------- 1 file changed, 18 insertions(+), 26 deletions(-) diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp index c187660377..67b468d5bb 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp @@ -486,45 +486,37 @@ namespace UnitTest struct EnumeratePropertyGroupsResult { - const MaterialTypeSourceData::PropertyGroup* m_propertyGroup; - MaterialNameContext m_groupNameContext; - MaterialNameContext m_parentNameContext; + MaterialNameContext m_nameContext; - void Check(AZStd::string expectedIdContext, const MaterialTypeSourceData::PropertyGroup* expectedPropertyGroup) + void Check(AZStd::string expectedGroupId) { - Name groupFullId{m_propertyGroup->GetName()}; - m_parentNameContext.ContextualizeProperty(groupFullId); + Name imaginaryProperty{"someChildProperty"}; + m_nameContext.ContextualizeProperty(imaginaryProperty); - AZStd::string expectedPropertyId = expectedIdContext + expectedPropertyGroup->GetName(); - - EXPECT_EQ(expectedPropertyId, groupFullId.GetStringView()); - EXPECT_EQ(expectedPropertyGroup, m_propertyGroup); - - Name imaginaryPropertyName{"someChildProperty"}; - m_groupNameContext.ContextualizeProperty(imaginaryPropertyName); - EXPECT_EQ(AZStd::string(groupFullId.GetStringView()) + ".someChildProperty", imaginaryPropertyName.GetStringView()); + EXPECT_EQ(expectedGroupId + ".someChildProperty", imaginaryProperty.GetStringView()); } }; AZStd::vector enumeratePropertyGroupsResults; sourceData.EnumeratePropertyGroups([&enumeratePropertyGroupsResults]( - const MaterialTypeSourceData::PropertyGroup* propertyGroup, const MaterialNameContext& groupNameContext, const MaterialNameContext& parentNameContext) + const MaterialTypeSourceData::PropertyGroupStack& propertyGroupStack) { - enumeratePropertyGroupsResults.push_back(EnumeratePropertyGroupsResult{propertyGroup, groupNameContext, parentNameContext}); + MaterialNameContext nameContext = MaterialTypeSourceData::MakeMaterialNameContext(propertyGroupStack); + enumeratePropertyGroupsResults.push_back(EnumeratePropertyGroupsResult{nameContext}); return true; }); int resultIndex = 0; - enumeratePropertyGroupsResults[resultIndex++].Check("", layer1); - enumeratePropertyGroupsResults[resultIndex++].Check("layer1.", layer1_baseColor); - enumeratePropertyGroupsResults[resultIndex++].Check("layer1.", layer1_roughness); - enumeratePropertyGroupsResults[resultIndex++].Check("", layer2); - enumeratePropertyGroupsResults[resultIndex++].Check("layer2.", layer2_baseColor); - enumeratePropertyGroupsResults[resultIndex++].Check("layer2.", layer2_roughness); - enumeratePropertyGroupsResults[resultIndex++].Check("layer2.", layer2_clearCoat); - enumeratePropertyGroupsResults[resultIndex++].Check("layer2.clearCoat.", layer2_clearCoat_roughness); - enumeratePropertyGroupsResults[resultIndex++].Check("layer2.clearCoat.", layer2_clearCoat_normal); - enumeratePropertyGroupsResults[resultIndex++].Check("", blend); + enumeratePropertyGroupsResults[resultIndex++].Check("layer1"); + enumeratePropertyGroupsResults[resultIndex++].Check("layer1.baseColor"); + enumeratePropertyGroupsResults[resultIndex++].Check("layer1.roughness"); + enumeratePropertyGroupsResults[resultIndex++].Check("layer2"); + enumeratePropertyGroupsResults[resultIndex++].Check("layer2.baseColor"); + enumeratePropertyGroupsResults[resultIndex++].Check("layer2.roughness"); + enumeratePropertyGroupsResults[resultIndex++].Check("layer2.clearCoat"); + enumeratePropertyGroupsResults[resultIndex++].Check("layer2.clearCoat.roughness"); + enumeratePropertyGroupsResults[resultIndex++].Check("layer2.clearCoat.normal"); + enumeratePropertyGroupsResults[resultIndex++].Check("blend"); EXPECT_EQ(resultIndex, enumeratePropertyGroupsResults.size()); // Check EnumerateProperties From 5ef2b12dca45b5ca396cf55de747c5ad4b27fe65 Mon Sep 17 00:00:00 2001 From: evanchia-ly-sdets <80914607+evanchia-ly-sdets@users.noreply.github.com> Date: Wed, 9 Feb 2022 18:13:01 -0800 Subject: [PATCH 045/133] Collects failed assets on LyTestTools test failures (#7368) * Collects failed assets on LyTestTools test failures Signed-off-by: evanchia * Changed query to all lines because of current asset logging bug Signed-off-by: evanchia * fixes per pr feedback Signed-off-by: evanchia * testing removing change for AR failure Signed-off-by: evanchia * Moved asset log artifact collection to after the results have been collected Signed-off-by: evanchia * Adding debug line to help debug AR failure Signed-off-by: evanchia * Made asset log collection non failing Signed-off-by: evanchia * moved asset log collection after test result collection Signed-off-by: evanchia * changed asset saving to non failing Signed-off-by: evanchia * improved logging and comments Signed-off-by: evanchia --- .../managers/abstract_resource_locator.py | 9 ++- .../ly_test_tools/o3de/editor_test.py | 24 +++++++- .../ly_test_tools/o3de/editor_test_utils.py | 39 +++++++++++++ .../tests/unit/test_editor_test_utils.py | 56 +++++++++++++++++++ .../tests/unit/test_o3de_editor_test.py | 7 +++ 5 files changed, 132 insertions(+), 3 deletions(-) diff --git a/Tools/LyTestTools/ly_test_tools/_internal/managers/abstract_resource_locator.py b/Tools/LyTestTools/ly_test_tools/_internal/managers/abstract_resource_locator.py index 4514e5d812..6e0923b916 100755 --- a/Tools/LyTestTools/ly_test_tools/_internal/managers/abstract_resource_locator.py +++ b/Tools/LyTestTools/ly_test_tools/_internal/managers/abstract_resource_locator.py @@ -175,13 +175,20 @@ class AbstractResourceLocator(object): return os.path.join(self.build_directory(), 'AssetProcessor') def asset_processor_batch(self): - """" + """ Return path for the AssetProcessorBatch compatible with this build platform and configuration ex. engine_root/dev/mac/bin/profile/AssetProcessorBatch :return: path to AssetProcessorBatch """ return os.path.join(self.build_directory(), 'AssetProcessorBatch') + def ap_job_logs(self): + """ + Return path to the Asset Processor JobLogs directory. + :return: path to /user/log/JobLogs + """ + return os.path.join(self.project_log(), 'JobLogs') + def editor(self): """ Return path to the editor executable compatible with the current build. diff --git a/Tools/LyTestTools/ly_test_tools/o3de/editor_test.py b/Tools/LyTestTools/ly_test_tools/o3de/editor_test.py index f363689066..3c4e2b49a4 100644 --- a/Tools/LyTestTools/ly_test_tools/o3de/editor_test.py +++ b/Tools/LyTestTools/ly_test_tools/o3de/editor_test.py @@ -851,11 +851,11 @@ class EditorTestSuite(): workspace.artifact_manager.save_artifact(os.path.join(editor_utils.retrieve_log_path(run_id, workspace), log_name), f'({run_id}){log_name}') if return_code == 0: - # No need to scrap the output, as all the tests have passed + # No need to scrape the output, as all the tests have passed for test_spec in test_spec_list: results[test_spec.__name__] = Result.Pass.create(test_spec, output, editor_log_content) else: - # Scrap the output to attempt to find out which tests failed. + # Scrape the output to attempt to find out which tests failed. # This function should always populate the result list, if it didn't find it, it will have "Unknown" type of result results = self._get_results_using_output(test_spec_list, output, editor_log_content) assert len(results) == len(test_spec_list), "bug in _get_results_using_output(), the number of results don't match the tests ran" @@ -940,6 +940,9 @@ class EditorTestSuite(): editor_test_data.results.update(results) test_name, test_result = next(iter(results.items())) self._report_result(test_name, test_result) + # If test did not pass, save assets with errors and warnings + if not isinstance(test_result, Result.Pass): + editor_utils.save_failed_asset_joblogs(workspace) def _run_batched_tests(self, request: Request, workspace: AbstractWorkspace, editor: Editor, editor_test_data: TestData, test_spec_list: list[EditorSharedTest], extra_cmdline_args: list[str] = []) -> None: @@ -961,6 +964,11 @@ class EditorTestSuite(): extra_cmdline_args) assert results is not None editor_test_data.results.update(results) + # If at least one test did not pass, save assets with errors and warnings + for result in results: + if not isinstance(result, Result.Pass): + editor_utils.save_failed_asset_joblogs(workspace) + return def _run_parallel_tests(self, request: Request, workspace: AbstractWorkspace, editor: Editor, editor_test_data: TestData, test_spec_list: list[EditorSharedTest], extra_cmdline_args: list[str] = []) -> None: @@ -1007,8 +1015,14 @@ class EditorTestSuite(): for t in threads: t.join() + save_asset_logs = False for result in results_per_thread: editor_test_data.results.update(result) + if not isinstance(result, Result.Pass): + save_asset_logs = True + # If at least one test did not pass, save assets with errors and warnings + if save_asset_logs: + editor_utils.save_failed_asset_joblogs(workspace) def _run_parallel_batched_tests(self, request: Request, workspace: AbstractWorkspace, editor: Editor, editor_test_data: TestData, test_spec_list: list[EditorSharedTest], extra_cmdline_args: list[str] = []) -> None: @@ -1056,8 +1070,14 @@ class EditorTestSuite(): for t in threads: t.join() + save_asset_logs = False for result in results_per_thread: editor_test_data.results.update(result) + if not isinstance(result, Result.Pass): + save_asset_logs = True + # If at least one test did not pass, save assets with errors and warnings + if save_asset_logs: + editor_utils.save_failed_asset_joblogs(workspace) def _get_number_parallel_editors(self, request: Request) -> int: """ diff --git a/Tools/LyTestTools/ly_test_tools/o3de/editor_test_utils.py b/Tools/LyTestTools/ly_test_tools/o3de/editor_test_utils.py index 7b36a82c07..4e678151bd 100644 --- a/Tools/LyTestTools/ly_test_tools/o3de/editor_test_utils.py +++ b/Tools/LyTestTools/ly_test_tools/o3de/editor_test_utils.py @@ -10,6 +10,7 @@ from __future__ import annotations import os import time import logging +import re import ly_test_tools.environment.process_utils as process_utils import ly_test_tools.environment.waiter as waiter @@ -151,3 +152,41 @@ def retrieve_last_run_test_index_from_output(test_spec_list: list[EditorTestBase else: index += 1 return index + +def save_failed_asset_joblogs(workspace: AbstractWorkspace) -> None: + """ + Checks all asset logs in the JobLogs directory to see if the asset has any warnings or errors. If so, the asset is + saved via ArtifactManager. + + :param workspace: The AbstractWorkspace to access the JobLogs path + :return: None + """ + for walk_tuple in os.walk(workspace.paths.ap_job_logs()): + for log_file in walk_tuple[2]: + full_log_path = os.path.join(walk_tuple[0], log_file) + # Only save asset logs that contain errors or warnings + if _check_log_errors_warnings(full_log_path): + try: + workspace.artifact_manager.save_artifact(full_log_path) + except Exception as e: # Purposefully broad + logger.warning(f"Error when saving log at path:{full_log_path}\n{e}") + +def _check_log_errors_warnings(log_path: str) -> bool: + """ + Checks to see if the asset log contains any errors or warnings. Also returns True is no regex is found because + something probably went wrong. + Example log lines: ~~1643759303647~~1~~00000000000009E0~~AssetBuilder~~S: 0 errors, 1 warnings + + :param log_path: The full path to the asset log file to read + :return: True if the regex finds an error or warning, else False + """ + log_regex = "(\\d+) errors, (\\d+) warnings" + with open(log_path, 'r') as opened_asset_log: + for log_line in opened_asset_log: + regex_match = re.search(log_regex, log_line) + if regex_match is not None: + break + # If we match any non zero numbers in: n error, n warnings + if regex_match is None or (int)(regex_match.group(1)) != 0 or (int)(regex_match.group(2)) != 0: + return True + return False diff --git a/Tools/LyTestTools/tests/unit/test_editor_test_utils.py b/Tools/LyTestTools/tests/unit/test_editor_test_utils.py index f81d2fd8e6..cca9a161c8 100644 --- a/Tools/LyTestTools/tests/unit/test_editor_test_utils.py +++ b/Tools/LyTestTools/tests/unit/test_editor_test_utils.py @@ -170,3 +170,59 @@ class TestEditorTestUtils(unittest.TestCase): mock_test_list.append(mock_test) assert 0 == editor_test_utils.retrieve_last_run_test_index_from_output(mock_test_list, mock_editor_output) + + @mock.patch('ly_test_tools.o3de.editor_test_utils._check_log_errors_warnings') + @mock.patch('os.walk') + def test_SaveFailedAssetJoblogs_ManyValidLogs_SavesCorrectly(self, mock_walk, mock_check_log): + mock_workspace = mock.MagicMock() + mock_walk.return_value = [['MockDirectory', None, ['mock_log.log']], + ['MockDirectory2', None, ['mock_log2.log']]] + mock_check_log.return_value = True + + editor_test_utils.save_failed_asset_joblogs(mock_workspace) + + assert mock_workspace.artifact_manager.save_artifact.call_count == 2 + + @mock.patch('ly_test_tools.o3de.editor_test_utils._check_log_errors_warnings') + @mock.patch('os.walk') + def test_SaveFailedAssetJoblogs_ManyInvalidLogs_NoSaves(self, mock_walk, mock_check_log): + mock_workspace = mock.MagicMock() + mock_walk.return_value = [['MockDirectory', None, ['mock_log.log']], + ['MockDirectory2', None, ['mock_log2.log']]] + mock_check_log.return_value = False + + editor_test_utils.save_failed_asset_joblogs(mock_workspace) + + assert mock_workspace.artifact_manager.save_artifact.call_count == 0 + + def test_CheckLogErrorWarnings_ValidLine_ReturnsTrue(self): + mock_log = '~~1643759303647~~1~~00000000000009E0~~AssetBuilder~~S: 0 errors, 1 warnings' + mock_log_path = mock.MagicMock() + + with mock.patch('builtins.open', mock.mock_open(read_data=mock_log)) as mock_file: + expected = editor_test_utils._check_log_errors_warnings(mock_log_path) + assert expected + + def test_CheckLogErrorWarnings_MultipleValidLine_ReturnsTrue(self): + mock_log = 'foo\nfoo\n~~1643759303647~~1~~00000000000009E0~~AssetBuilder~~S: 1 errors, 1 warnings' + mock_log_path = mock.MagicMock() + + with mock.patch('builtins.open', mock.mock_open(read_data=mock_log)) as mock_file: + expected = editor_test_utils._check_log_errors_warnings(mock_log_path) + assert expected + + def test_CheckLogErrorWarnings_InvalidLine_ReturnsFalse(self): + mock_log = 'foo\n~~1643759303647~~1~~00000000000009E0~~AssetBuilder~~S: 0 errors, 0 warnings' + mock_log_path = mock.MagicMock() + + with mock.patch('builtins.open', mock.mock_open(read_data=mock_log)) as mock_file: + expected = editor_test_utils._check_log_errors_warnings(mock_log_path) + assert not expected + + def test_CheckLogErrorWarnings_InvalidRegex_ReturnsTrue(self): + mock_log = 'Invalid last line' + mock_log_path = mock.MagicMock() + + with mock.patch('builtins.open', mock.mock_open(read_data=mock_log)) as mock_file: + expected = editor_test_utils._check_log_errors_warnings(mock_log_path) + assert expected diff --git a/Tools/LyTestTools/tests/unit/test_o3de_editor_test.py b/Tools/LyTestTools/tests/unit/test_o3de_editor_test.py index 973366aa94..f63ec315eb 100644 --- a/Tools/LyTestTools/tests/unit/test_o3de_editor_test.py +++ b/Tools/LyTestTools/tests/unit/test_o3de_editor_test.py @@ -871,6 +871,7 @@ class TestRunningTests(unittest.TestCase): @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._report_result') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._exec_editor_test') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._setup_editor_test') + @mock.patch('ly_test_tools.o3de.editor_test_utils.save_failed_asset_joblogs', mock.MagicMock()) def test_RunSingleTest_ValidTest_ReportsResults(self, mock_setup_test, mock_exec_editor_test, mock_report_result): mock_test_suite = ly_test_tools.o3de.editor_test.EditorTestSuite() mock_test_data = mock.MagicMock() @@ -903,6 +904,7 @@ class TestRunningTests(unittest.TestCase): @mock.patch('threading.Thread') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._get_number_parallel_editors') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._setup_editor_test') + @mock.patch('ly_test_tools.o3de.editor_test_utils.save_failed_asset_joblogs', mock.MagicMock()) def test_RunParallelTests_TwoTestsAndEditors_TwoThreads(self, mock_setup_test, mock_get_num_editors, mock_thread): mock_test_suite = ly_test_tools.o3de.editor_test.EditorTestSuite() mock_get_num_editors.return_value = 2 @@ -919,6 +921,7 @@ class TestRunningTests(unittest.TestCase): @mock.patch('threading.Thread') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._get_number_parallel_editors') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._setup_editor_test') + @mock.patch('ly_test_tools.o3de.editor_test_utils.save_failed_asset_joblogs', mock.MagicMock()) def test_RunParallelTests_TenTestsAndTwoEditors_TenThreads(self, mock_setup_test, mock_get_num_editors, mock_thread): mock_test_suite = ly_test_tools.o3de.editor_test.EditorTestSuite() mock_get_num_editors.return_value = 2 @@ -937,6 +940,7 @@ class TestRunningTests(unittest.TestCase): @mock.patch('threading.Thread') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._get_number_parallel_editors') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._setup_editor_test') + @mock.patch('ly_test_tools.o3de.editor_test_utils.save_failed_asset_joblogs', mock.MagicMock()) def test_RunParallelTests_TenTestsAndThreeEditors_TenThreads(self, mock_setup_test, mock_get_num_editors, mock_thread): mock_test_suite = ly_test_tools.o3de.editor_test.EditorTestSuite() @@ -956,6 +960,7 @@ class TestRunningTests(unittest.TestCase): @mock.patch('threading.Thread') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._get_number_parallel_editors') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._setup_editor_test') + @mock.patch('ly_test_tools.o3de.editor_test_utils.save_failed_asset_joblogs', mock.MagicMock()) def test_RunParallelBatchedTests_TwoTestsAndEditors_TwoThreads(self, mock_setup_test, mock_get_num_editors, mock_thread): mock_test_suite = ly_test_tools.o3de.editor_test.EditorTestSuite() @@ -973,6 +978,7 @@ class TestRunningTests(unittest.TestCase): @mock.patch('threading.Thread') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._get_number_parallel_editors') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._setup_editor_test') + @mock.patch('ly_test_tools.o3de.editor_test_utils.save_failed_asset_joblogs', mock.MagicMock()) def test_RunParallelBatchedTests_TenTestsAndTwoEditors_2Threads(self, mock_setup_test, mock_get_num_editors, mock_thread): mock_test_suite = ly_test_tools.o3de.editor_test.EditorTestSuite() @@ -992,6 +998,7 @@ class TestRunningTests(unittest.TestCase): @mock.patch('threading.Thread') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._get_number_parallel_editors') @mock.patch('ly_test_tools.o3de.editor_test.EditorTestSuite._setup_editor_test') + @mock.patch('ly_test_tools.o3de.editor_test_utils.save_failed_asset_joblogs', mock.MagicMock()) def test_RunParallelBatchedTests_TenTestsAndThreeEditors_ThreeThreads(self, mock_setup_test, mock_get_num_editors, mock_thread): mock_test_suite = ly_test_tools.o3de.editor_test.EditorTestSuite() From 6b047fd89f657513652e689ba34b549d761a0f22 Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Wed, 9 Feb 2022 19:43:25 -0800 Subject: [PATCH 046/133] Addressed code review feedback, minor updates. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../Atom/RPI.Edit/Material/MaterialTypeSourceData.h | 2 +- .../RPI.Edit/Material/MaterialTypeSourceData.cpp | 10 +++++----- .../Material/EditorMaterialComponentInspector.cpp | 8 ++++---- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h index 507652b9fa..ee2a464290 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h @@ -324,7 +324,7 @@ namespace AZ PropertyDefinition* FindProperty(AZStd::span parsedPropertyId, AZStd::span> inPropertyGroupList); // Function overloads for recursion, returns false to indicate that recursion should end. - bool EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, PropertyGroupStack* propertyGroupStack, const AZStd::vector>& inPropertyGroupList) const; + bool EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, PropertyGroupStack& propertyGroupStack, const AZStd::vector>& inPropertyGroupList) const; bool EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const; static void ExtendNameContext(MaterialNameContext& nameContext, const MaterialTypeSourceData::PropertyGroup& propertyGroup); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp index 9153120732..3d40e5551e 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialTypeSourceData.cpp @@ -427,13 +427,13 @@ namespace AZ return parts; } - bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, PropertyGroupStack* propertyGroupStack, const AZStd::vector>& inPropertyGroupList) const + bool MaterialTypeSourceData::EnumeratePropertyGroups(const EnumeratePropertyGroupsCallback& callback, PropertyGroupStack& propertyGroupStack, const AZStd::vector>& inPropertyGroupList) const { for (auto& propertyGroup : inPropertyGroupList) { - propertyGroupStack->push_back(propertyGroup.get()); + propertyGroupStack.push_back(propertyGroup.get()); - if (!callback(*propertyGroupStack)) + if (!callback(propertyGroupStack)) { return false; // Stop processing } @@ -443,7 +443,7 @@ namespace AZ return false; // Stop processing } - propertyGroupStack->pop_back(); + propertyGroupStack.pop_back(); } return true; @@ -457,7 +457,7 @@ namespace AZ } PropertyGroupStack propertyGroupStack; - return EnumeratePropertyGroups(callback, &propertyGroupStack, m_propertyLayout.m_propertyGroups); + return EnumeratePropertyGroups(callback, propertyGroupStack, m_propertyLayout.m_propertyGroups); } bool MaterialTypeSourceData::EnumerateProperties(const EnumeratePropertiesCallback& callback, MaterialNameContext nameContext, const AZStd::vector>& inPropertyGroupList) const diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 1c6410f8c3..37ca44fa43 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -275,7 +275,7 @@ namespace AZ void MaterialPropertyInspector::AddPropertiesGroup() { - // Copy all of the properties from the material asset to the source data that will be exported + // Copy all of the properties from the material asset to the populate the inspector m_editData.m_materialTypeSourceData.EnumeratePropertyGroups( [this](const AZ::RPI::MaterialTypeSourceData::PropertyGroupStack& propertyGroupStack) { @@ -290,10 +290,10 @@ namespace AZ AZStd::vector groupNameVector; AZStd::vector groupDisplayNameVector; - for (auto& group : propertyGroupStack) + for (auto& nextGroup : propertyGroupStack) { - groupNameVector.push_back(group->GetName()); - groupDisplayNameVector.push_back(!group->GetDisplayName().empty() ? group->GetDisplayName() : group->GetName()); + groupNameVector.push_back(nextGroup->GetName()); + groupDisplayNameVector.push_back(!nextGroup->GetDisplayName().empty() ? nextGroup->GetDisplayName() : nextGroup->GetName()); } AZStd::string groupId; From 1c3a61983acf001cf0380c8dcd92eb5244475d17 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Wed, 9 Feb 2022 20:50:32 -0800 Subject: [PATCH 047/133] Refactor EditorEntityUiHandlerBaseto be explicitly Outliner-focused. This lays the groundwork for multiple widget-based handlers in the future. (#7443) Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../EditorEntityUiHandlerBase.cpp | 10 +++++++++- .../EditorEntityUiHandlerBase.h | 20 +++++++++++-------- .../UI/Outliner/EntityOutlinerWidget.cpp | 2 +- .../UI/Prefab/LevelRootUiHandler.cpp | 13 +++++++----- .../UI/Prefab/LevelRootUiHandler.h | 2 +- .../UI/Prefab/PrefabUiHandler.cpp | 14 +++++++------ .../UI/Prefab/PrefabUiHandler.h | 2 +- 7 files changed, 40 insertions(+), 23 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.cpp index 866080a83f..4896a5af49 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.cpp @@ -7,6 +7,7 @@ */ #include +#include #include @@ -117,9 +118,16 @@ namespace AzToolsFramework { } - bool EditorEntityUiHandlerBase::OnEntityDoubleClick([[maybe_unused]] AZ::EntityId entityId) const + bool EditorEntityUiHandlerBase::OnOutlinerItemDoubleClick([[maybe_unused]] const QModelIndex& index) const { return false; } + AZ::EntityId EditorEntityUiHandlerBase::GetEntityIdFromIndex(const QModelIndex& index) + { + QModelIndex firstColumnIndex = index.siblingAtColumn(EntityOutlinerListModel::ColumnName); + + return AZ::EntityId(firstColumnIndex.data(EntityOutlinerListModel::EntityIdRole).value()); + } + } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.h index 96d393efa1..948c26d710 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.h @@ -21,7 +21,6 @@ class QTreeView; namespace AzToolsFramework { //! Defines a handler that can customize entity UI appearance and behavior in the Entity Outliner. - //! This class is meant to be abstract, entities do not have a handler by default. class EditorEntityUiHandlerBase { protected: @@ -33,7 +32,7 @@ namespace AzToolsFramework public: EditorEntityUiHandlerId GetHandlerId(); - // # Entity Outliner + // # Entity Outliner Item //! Returns the item info string that is appended to the item name in the Outliner. virtual QString GenerateItemInfoString(AZ::EntityId entityId) const; @@ -41,10 +40,12 @@ namespace AzToolsFramework virtual QString GenerateItemTooltip(AZ::EntityId entityId) const; //! Returns the item icon pixmap to display in the Outliner. virtual QIcon GenerateItemIcon(AZ::EntityId entityId) const; - //! Returns whether the element's lock and visibility state should be accessible in the Outliner - virtual bool CanToggleLockVisibility(AZ::EntityId entityId) const; //! Returns whether the element's name should be editable virtual bool CanRename(AZ::EntityId entityId) const; + //! Returns whether the element's lock and visibility state should be accessible in the Outliner + virtual bool CanToggleLockVisibility(AZ::EntityId entityId) const; + + // Qt-specific painting functions //! Paints the background of the item in the Outliner. virtual void PaintItemBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; @@ -54,24 +55,27 @@ namespace AzToolsFramework //! Paints the background of the descendant branches of the item in the Outliner. virtual void PaintDescendantBranchBackground(QPainter* painter, const QTreeView* view, const QRect& rect, const QModelIndex& index, const QModelIndex& descendantIndex) const; - //! Paints visual elements on the foreground of the item in the Outliner. virtual void PaintItemForeground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; //! Paints visual elements on the foreground of the descendants of the item in the Outliner. virtual void PaintDescendantForeground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index, const QModelIndex& descendantIndex) const; + // Outliner-specific interactions + //! Triggered when the entity is clicked in the Outliner. //! @return True if the click has been handled and should not be propagated, false otherwise. virtual bool OnOutlinerItemClick(const QPoint& position, const QStyleOptionViewItem& option, const QModelIndex& index) const; + //! Triggered when the entity is double-clicked in the Outliner. + //! @return True if the double-click has been handled and should not be propagated, false otherwise. + virtual bool OnOutlinerItemDoubleClick(const QModelIndex& index) const; //! Triggered when an entity's children are expanded in the Outliner. virtual void OnOutlinerItemExpand(const QModelIndex& index) const; //! Triggered when an entity's children are collapsed in the Outliner. virtual void OnOutlinerItemCollapse(const QModelIndex& index) const; - //! Triggered when the entity is double clicked in the Outliner or in the Viewport. - //! @return True if the double click has been handled and should not be propagated, false otherwise. - virtual bool OnEntityDoubleClick(AZ::EntityId entityId) const; + protected: + static AZ::EntityId GetEntityIdFromIndex(const QModelIndex& index); private: EditorEntityUiHandlerId m_handlerId = 0; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp index 52b688543a..f4855cb715 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerWidget.cpp @@ -945,7 +945,7 @@ namespace AzToolsFramework { if (AZ::EntityId entityId = GetEntityIdFromIndex(index); auto entityUiHandler = m_editorEntityUiInterface->GetHandler(entityId)) { - entityUiHandler->OnEntityDoubleClick(entityId); + entityUiHandler->OnOutlinerItemDoubleClick(index); } } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.cpp index b34bbff298..9c5c478a2f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.cpp @@ -33,7 +33,7 @@ namespace AzToolsFramework } } - QIcon LevelRootUiHandler::GenerateItemIcon(AZ::EntityId /*entityId*/) const + QIcon LevelRootUiHandler::GenerateItemIcon([[maybe_unused]] AZ::EntityId entityId) const { return QIcon(m_levelRootIconPath); } @@ -62,17 +62,18 @@ namespace AzToolsFramework return infoString; } - bool LevelRootUiHandler::CanToggleLockVisibility(AZ::EntityId /*entityId*/) const + bool LevelRootUiHandler::CanToggleLockVisibility([[maybe_unused]] AZ::EntityId entityId) const { return false; } - bool LevelRootUiHandler::CanRename(AZ::EntityId /*entityId*/) const + bool LevelRootUiHandler::CanRename([[maybe_unused]] AZ::EntityId entityId) const { return false; } - void LevelRootUiHandler::PaintItemBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& /*index*/) const + void LevelRootUiHandler::PaintItemBackground( + QPainter* painter, const QStyleOptionViewItem& option, [[maybe_unused]] const QModelIndex& index) const { if (!painter) { @@ -94,8 +95,10 @@ namespace AzToolsFramework painter->restore(); } - bool LevelRootUiHandler::OnEntityDoubleClick(AZ::EntityId entityId) const + bool LevelRootUiHandler::OnOutlinerItemDoubleClick(const QModelIndex& index) const { + AZ::EntityId entityId = GetEntityIdFromIndex(index); + if (auto prefabFocusPublicInterface = AZ::Interface::Get(); !prefabFocusPublicInterface->IsOwningPrefabBeingFocused(entityId)) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.h index 3f7f56670e..a43aa0606a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.h @@ -33,7 +33,7 @@ namespace AzToolsFramework bool CanToggleLockVisibility(AZ::EntityId entityId) const override; bool CanRename(AZ::EntityId entityId) const override; void PaintItemBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; - bool OnEntityDoubleClick(AZ::EntityId entityId) const override; + bool OnOutlinerItemDoubleClick(const QModelIndex& index) const override; private: Prefab::PrefabPublicInterface* m_prefabPublicInterface = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp index 69d6ae82ca..f3579c223c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp @@ -99,7 +99,7 @@ namespace AzToolsFramework return; } - AZ::EntityId entityId(index.data(EntityOutlinerListModel::EntityIdRole).value()); + AZ::EntityId entityId = GetEntityIdFromIndex(index); const bool isFirstColumn = index.column() == EntityOutlinerListModel::ColumnName; const bool isLastColumn = index.column() == EntityOutlinerListModel::ColumnLockToggle; QModelIndex firstColumnIndex = index.siblingAtColumn(EntityOutlinerListModel::ColumnName); @@ -183,7 +183,7 @@ namespace AzToolsFramework return; } - AZ::EntityId entityId(index.data(EntityOutlinerListModel::EntityIdRole).value()); + AZ::EntityId entityId = GetEntityIdFromIndex(index); const QTreeView* outlinerTreeView(qobject_cast(option.widget)); const int ancestorLeft = outlinerTreeView->visualRect(index).left() + (m_prefabBorderThickness / 2) - 1; @@ -283,7 +283,7 @@ namespace AzToolsFramework void PrefabUiHandler::PaintItemForeground(QPainter* painter, const QStyleOptionViewItem& option, [[maybe_unused]] const QModelIndex& index) const { - AZ::EntityId entityId(index.data(EntityOutlinerListModel::EntityIdRole).value()); + AZ::EntityId entityId = GetEntityIdFromIndex(index); const QPoint offset = QPoint(-18, 3); QModelIndex firstColumnIndex = index.siblingAtColumn(EntityOutlinerListModel::ColumnName); const int iconSize = 16; @@ -385,7 +385,7 @@ namespace AzToolsFramework bool PrefabUiHandler::OnOutlinerItemClick(const QPoint& position, const QStyleOptionViewItem& option, const QModelIndex& index) const { - AZ::EntityId entityId(index.data(EntityOutlinerListModel::EntityIdRole).value()); + AZ::EntityId entityId = GetEntityIdFromIndex(index); const QPoint offset = QPoint(-18, 3); if (m_prefabFocusPublicInterface->IsOwningPrefabInFocusHierarchy(entityId)) @@ -411,7 +411,7 @@ namespace AzToolsFramework void PrefabUiHandler::OnOutlinerItemCollapse(const QModelIndex& index) const { - AZ::EntityId entityId(index.data(EntityOutlinerListModel::EntityIdRole).value()); + AZ::EntityId entityId = GetEntityIdFromIndex(index); if (m_prefabFocusPublicInterface->IsOwningPrefabBeingFocused(entityId)) { @@ -420,8 +420,10 @@ namespace AzToolsFramework } } - bool PrefabUiHandler::OnEntityDoubleClick(AZ::EntityId entityId) const + bool PrefabUiHandler::OnOutlinerItemDoubleClick(const QModelIndex& index) const { + AZ::EntityId entityId = GetEntityIdFromIndex(index); + if (!m_prefabFocusPublicInterface->IsOwningPrefabBeingFocused(entityId)) { // Focus on this prefab diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.h index a1c624f85a..7166629cf3 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.h @@ -43,8 +43,8 @@ namespace AzToolsFramework const QModelIndex& index, const QModelIndex& descendantIndex) const override; bool OnOutlinerItemClick(const QPoint& position, const QStyleOptionViewItem& option, const QModelIndex& index) const override; + bool OnOutlinerItemDoubleClick(const QModelIndex& index) const override; void OnOutlinerItemCollapse(const QModelIndex& index) const override; - bool OnEntityDoubleClick(AZ::EntityId entityId) const override; protected: Prefab::PrefabFocusPublicInterface* m_prefabFocusPublicInterface = nullptr; From 3ad78881076240204bc8adb9bf0baeafba330cd7 Mon Sep 17 00:00:00 2001 From: dmcdiarmid-ly <63674186+dmcdiarmid-ly@users.noreply.github.com> Date: Wed, 9 Feb 2022 22:11:43 -0700 Subject: [PATCH 048/133] Checked the device raytracing feature flag before initializing the visualization raytracing objects Signed-off-by: dmcdiarmid-ly <63674186+dmcdiarmid-ly@users.noreply.github.com> --- .../DiffuseProbeGridFeatureProcessor.cpp | 29 ++++++++++--------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp index 84c066604a..5e85c3b247 100644 --- a/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/DiffuseGlobalIllumination/DiffuseProbeGridFeatureProcessor.cpp @@ -92,21 +92,24 @@ namespace AZ AZ_Error("DiffuseProbeGridFeatureProcessor", m_probeGridRenderData.m_srgLayout != nullptr, "Failed to find ObjectSrg layout"); } - // initialize the buffer pools for the DiffuseProbeGrid visualization - m_visualizationBufferPools = RHI::RayTracingBufferPools::CreateRHIRayTracingBufferPools(); - m_visualizationBufferPools->Init(device); - - // load probe visualization model, the BLAS will be created in OnAssetReady() - m_visualizationModelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath( - "Models/DiffuseProbeSphere.azmodel", - AZ::RPI::AssetUtils::TraceLevel::Assert); - - if (!m_visualizationModelAsset.IsReady()) + if (device->GetFeatures().m_rayTracing) { - m_visualizationModelAsset.QueueLoad(); - } + // initialize the buffer pools for the DiffuseProbeGrid visualization + m_visualizationBufferPools = RHI::RayTracingBufferPools::CreateRHIRayTracingBufferPools(); + m_visualizationBufferPools->Init(device); - Data::AssetBus::MultiHandler::BusConnect(m_visualizationModelAsset.GetId()); + // load probe visualization model, the BLAS will be created in OnAssetReady() + m_visualizationModelAsset = AZ::RPI::AssetUtils::GetAssetByProductPath( + "Models/DiffuseProbeSphere.azmodel", + AZ::RPI::AssetUtils::TraceLevel::Assert); + + if (!m_visualizationModelAsset.IsReady()) + { + m_visualizationModelAsset.QueueLoad(); + } + + Data::AssetBus::MultiHandler::BusConnect(m_visualizationModelAsset.GetId()); + } EnableSceneNotification(); } From aec7b58c39d369ccce23e28742989c1ef16575f5 Mon Sep 17 00:00:00 2001 From: Jeremy Ong Date: Thu, 10 Feb 2022 02:27:49 -0700 Subject: [PATCH 049/133] Introduce Atom/GraphicsDevMode settings registry key When `"Atom": {"GraphicsDevMode": true}` is found in a `.setreg` file, PDBs for all shaders will be emitted to their corresponding output locations. This allows global PDB generation without needing to explicitly modify each `.shader` file to include the `GenerateDebugInfo` compilation option. Signed-off-by: Jeremy Ong --- .../Editor/AzslShaderBuilderSystemComponent.cpp | 2 +- Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h | 3 +++ Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp | 14 ++++++++++++++ .../RHI.Builders/ShaderPlatformInterface.cpp | 10 ++++++---- .../RHI.Builders/ShaderPlatformInterface.cpp | 7 +++++-- 5 files changed, 29 insertions(+), 7 deletions(-) diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslShaderBuilderSystemComponent.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslShaderBuilderSystemComponent.cpp index 7e510e2e3a..43d67cc95c 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslShaderBuilderSystemComponent.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslShaderBuilderSystemComponent.cpp @@ -82,7 +82,7 @@ namespace AZ // Register Shader Asset Builder AssetBuilderSDK::AssetBuilderDesc shaderAssetBuilderDescriptor; shaderAssetBuilderDescriptor.m_name = "Shader Asset Builder"; - shaderAssetBuilderDescriptor.m_version = 110; // Add "Definitions" field to shader asset to support convenient addition of preprocessor definitions + shaderAssetBuilderDescriptor.m_version = 111; // Enable shader PDB generation globally if Atom/GraphicsDevMode settings registry key is set shaderAssetBuilderDescriptor.m_patterns.push_back(AssetBuilderSDK::AssetBuilderPattern( AZStd::string::format("*.%s", RPI::ShaderSourceData::Extension), AssetBuilderSDK::AssetBuilderPattern::PatternType::Wildcard)); shaderAssetBuilderDescriptor.m_busId = azrtti_typeid(); shaderAssetBuilderDescriptor.m_createJobFunction = AZStd::bind(&ShaderAssetBuilder::CreateJobs, &m_shaderAssetBuilder, AZStd::placeholders::_1, AZStd::placeholders::_2); diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h index 73e8e1ad56..48a041ad7d 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h @@ -42,6 +42,9 @@ namespace AZ //! Returns if the current bakcend is a null renderer bool IsNullRenderer(); + + //! Returns true if the Atom/GraphicsDevMode settings registry key is set + bool IsGraphicsDevModeEnabled(); } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp b/Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp index bc4cde9406..de27f4ce18 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp @@ -9,9 +9,12 @@ #include #include #include +#include #include #include +static constexpr char GraphicsDevModeSetting[] = "/Atom/GraphicsDevMode"; + namespace AZ { namespace RHI @@ -134,5 +137,16 @@ namespace AZ } return false; } + + bool IsGraphicsDevModeEnabled() + { + AZ::SettingsRegistryInterface* settingsRegistry = AZ::SettingsRegistry::Get(); + bool graphicsDevMode = false; + if (settingsRegistry) + { + settingsRegistry->Get(graphicsDevMode, GraphicsDevModeSetting); + } + return graphicsDevMode; + } } } diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp index ee293292e1..287c8e4fd5 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp @@ -12,10 +12,10 @@ #include #include #include +#include #include #include - #include namespace AZ @@ -253,9 +253,11 @@ namespace AZ return false; } + const bool graphicsDevMode = RHI::IsGraphicsDevModeEnabled(); + // Compilation parameters AZStd::string params = shaderCompilerArguments.MakeAdditionalDxcCommandLineString(); - if (BuildHasDebugInfo(shaderCompilerArguments)) + if (graphicsDevMode || BuildHasDebugInfo(shaderCompilerArguments)) { params += " -Zi"; // Generate debug information params += " -Zss"; // Compute Shader Hash considering source information @@ -284,7 +286,7 @@ namespace AZ // If we use the auto-name (hash), there is no way we can retrieve that name apart from listing the directory. // Instead, let's just generate that hash ourselves. AZStd::string symbolDatabaseFileCliArgument{" "}; // when not debug: still insert a space between 5.dxil and 7.hlsl-in - if (BuildHasDebugInfo(shaderCompilerArguments)) + if (graphicsDevMode || BuildHasDebugInfo(shaderCompilerArguments)) { // prepare .pdb filename: AZStd::string md5hex = RHI::ByteToHexString(md5); @@ -353,7 +355,7 @@ namespace AZ byProducts.m_dynamicBranchCount = ByProducts::UnknownDynamicBranchCount; } - if (BuildHasDebugInfo(shaderCompilerArguments)) + if (graphicsDevMode || BuildHasDebugInfo(shaderCompilerArguments)) { byProducts.m_intermediatePaths.emplace(AZStd::move(objectCodeOutputFile)); } diff --git a/Gems/Atom/RHI/Vulkan/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp b/Gems/Atom/RHI/Vulkan/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp index c5f1060ca3..f5716f384f 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp +++ b/Gems/Atom/RHI/Vulkan/Code/Source/RHI.Builders/ShaderPlatformInterface.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -281,7 +282,9 @@ namespace AZ args.m_destinationFolder = tempFolder.c_str(); const auto dxcInputFile = RHI::PrependFile(args); // Prepend header - if (BuildHasDebugInfo(shaderCompilerArguments)) + const bool graphicsDevMode = RHI::IsGraphicsDevModeEnabled(); + + if (graphicsDevMode || BuildHasDebugInfo(shaderCompilerArguments)) { // dump intermediate "true final HLSL" file (shadername.vulkan.shadersource.prepend) byProducts.m_intermediatePaths.insert(dxcInputFile); @@ -334,7 +337,7 @@ namespace AZ byProducts.m_dynamicBranchCount = ByProducts::UnknownDynamicBranchCount; } - if (BuildHasDebugInfo(shaderCompilerArguments)) + if (graphicsDevMode || BuildHasDebugInfo(shaderCompilerArguments)) { byProducts.m_intermediatePaths.emplace(AZStd::move(objectCodeOutputFile)); } From c964d2085f4d0732d9b23cc5bbedc0181bc551be Mon Sep 17 00:00:00 2001 From: Sergey Pereslavtsev Date: Thu, 10 Feb 2022 10:45:25 +0000 Subject: [PATCH 050/133] Removed pragma once from cpp Signed-off-by: Sergey Pereslavtsev --- Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp b/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp index 12a371fc49..bb4dcb6afe 100644 --- a/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp +++ b/Gems/Terrain/Code/Source/EditorSurfaceTagListProvider.cpp @@ -6,8 +6,6 @@ * */ -#pragma once - #include #include From dac3bc4ba62c34c47ab1513a42f0e415bbcacc49 Mon Sep 17 00:00:00 2001 From: moraaar Date: Thu, 10 Feb 2022 12:23:38 +0000 Subject: [PATCH 051/133] Added option to disable edit button in asset widgets when there are no asset selected. (#7521) Added new attribute "DisableEditButtonWheNoAssetSelected" to PropertyAssetCtrl. By default it's false, keeping the original behavior of leaving the edit button enabled and if it's clicked while there is no asset assigned it'll try to create a new one. PhysX mesh asset property uses now this new feature. Signed-off-by: moraaar moraaar@amazon.com --- .../UI/PropertyEditor/PropertyAssetCtrl.cpp | 42 ++++++++++++++++++- .../UI/PropertyEditor/PropertyAssetCtrl.hxx | 8 ++++ .../Code/Source/EditorColliderComponent.cpp | 1 + 3 files changed, 49 insertions(+), 2 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp index bd0cb3844a..e4a1a35b2c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.cpp @@ -102,7 +102,7 @@ namespace AzToolsFramework m_editButton->setAutoRaise(true); m_editButton->setIcon(QIcon(":/stylesheet/img/UI20/open-in-internal-app.svg")); m_editButton->setToolTip("Edit asset"); - m_editButton->setVisible(false); + SetEditButtonVisible(false); connect(m_editButton, &QToolButton::clicked, this, &PropertyAssetCtrl::OnEditButtonClicked); @@ -961,12 +961,16 @@ namespace AzToolsFramework AzFramework::StringFunc::Path::GetFileName(assetPath.c_str(), m_defaultAssetHint); } m_browseEdit->setPlaceholderText((m_defaultAssetHint + m_DefaultSuffix).c_str()); + + UpdateEditButton(); } void PropertyAssetCtrl::UpdateAssetDisplay() { UpdateThumbnail(); + UpdateEditButton(); + if (m_currentAssetType == AZ::Data::s_invalidAssetType) { return; @@ -1109,7 +1113,9 @@ namespace AzToolsFramework void PropertyAssetCtrl::SetEditButtonVisible(bool visible) { - m_editButton->setVisible(visible); + m_showEditButton = visible; + m_editButton->setVisible(m_showEditButton); + UpdateEditButton(); } void PropertyAssetCtrl::SetEditButtonIcon(const QIcon& icon) @@ -1205,6 +1211,15 @@ namespace AzToolsFramework m_thumbnail->ClearThumbnail(); } + void PropertyAssetCtrl::UpdateEditButton() + { + // if Edit button is in use (shown), enable/disable it depending on the current asset id. + if (m_showEditButton && m_disableEditButtonWhenNoAssetSelected) + { + m_editButton->setEnabled(GetCurrentAssetID().IsValid()); + } + } + void PropertyAssetCtrl::SetClearButtonEnabled(bool enable) { m_browseEdit->setClearButtonEnabled(enable); @@ -1236,6 +1251,17 @@ namespace AzToolsFramework return m_hideProductFilesInAssetPicker; } + void PropertyAssetCtrl::SetDisableEditButtonWhenNoAssetSelected(bool disableEditButtonWhenNoAssetSelected) + { + m_disableEditButtonWhenNoAssetSelected = disableEditButtonWhenNoAssetSelected; + UpdateEditButton(); + } + + bool PropertyAssetCtrl::GetDisableEditButtonWhenNoAssetSelected() const + { + return m_disableEditButtonWhenNoAssetSelected; + } + void PropertyAssetCtrl::SetShowThumbnail(bool enable) { m_showThumbnail = enable; @@ -1349,6 +1375,12 @@ namespace AzToolsFramework GUI->SetEditButtonTooltip(tr(buttonTooltip.c_str())); } } + else if (attrib == AZ_CRC_CE("DisableEditButtonWhenNoAssetSelected")) + { + bool disableEditButtonWhenNoAssetSelected = false; + attrValue->Read(disableEditButtonWhenNoAssetSelected); + GUI->SetDisableEditButtonWhenNoAssetSelected(disableEditButtonWhenNoAssetSelected); + } else if (attrib == AZ::Edit::Attributes::DefaultAsset) { AZ::Data::AssetId assetId; @@ -1597,6 +1629,12 @@ namespace AzToolsFramework GUI->SetEditButtonTooltip(tr(buttonTooltip.c_str())); } } + else if (attrib == AZ_CRC_CE("DisableEditButtonWhenNoAssetSelected")) + { + bool disableEditButtonWhenNoAssetSelected = false; + attrValue->Read(disableEditButtonWhenNoAssetSelected); + GUI->SetDisableEditButtonWhenNoAssetSelected(disableEditButtonWhenNoAssetSelected); + } } void SimpleAssetPropertyHandlerDefault::WriteGUIValuesIntoProperty(size_t index, PropertyAssetCtrl* GUI, property_t& instance, InstanceDataNode* node) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx index d6ff1b8de6..87fd691b20 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyAssetCtrl.hxx @@ -159,6 +159,10 @@ namespace AzToolsFramework //! By default the asset picker shows both on an AZ::Asset<> property. You can hide product assets with this flag. bool m_hideProductFilesInAssetPicker = false; + //! True to disable the edit button when there is no asset currently selected. + bool m_disableEditButtonWhenNoAssetSelected = false; + + bool m_showEditButton = false; bool m_showThumbnail = false; bool m_showThumbnailDropDownButton = false; EditCallbackType* m_thumbnailCallback = nullptr; @@ -220,6 +224,9 @@ namespace AzToolsFramework void SetHideProductFilesInAssetPicker(bool hide); bool GetHideProductFilesInAssetPicker() const; + void SetDisableEditButtonWhenNoAssetSelected(bool disableEditButtonWhenNoAssetSelected); + bool GetDisableEditButtonWhenNoAssetSelected() const; + // Enable and configure a thumbnail widget that displays an asset preview and dropdown arrow for a dropdown menu void SetShowThumbnail(bool enable); bool GetShowThumbnail() const; @@ -250,6 +257,7 @@ namespace AzToolsFramework private: void UpdateThumbnail(); + void UpdateEditButton(); }; class AssetPropertyHandlerDefault diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index 7e1d1c341f..69ae037e07 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -60,6 +60,7 @@ namespace PhysX "Specifies the PhysX mesh collider asset for this PhysX collider component.") ->Attribute(AZ_CRC_CE("EditButton"), "") ->Attribute(AZ_CRC_CE("EditDescription"), "Open in Scene Settings") + ->Attribute(AZ_CRC_CE("DisableEditButtonWhenNoAssetSelected"), true) ->DataElement(AZ::Edit::UIHandlers::Default, &EditorProxyAssetShapeConfig::m_configuration, "Configuration", "PhysX mesh asset collider configuration.") ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly); From 396ec8a247526754eb434f890b47d02c2a13f62f Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Thu, 10 Feb 2022 05:53:21 -0800 Subject: [PATCH 052/133] [Terrain] Optimize bulk queries to the Terrain System to retrieve height, surface weights, and normals (#7357) --- .../AzFramework/SurfaceData/SurfaceData.cpp | 2 + .../AzFramework/SurfaceData/SurfaceData.h | 10 +- .../Include/SurfaceData/SurfaceDataTypes.h | 12 +- .../Code/Source/SurfaceDataTypes.cpp | 2 +- .../Code/Tests/SurfaceDataBenchmarks.cpp | 4 +- .../Source/TerrainSystem/TerrainSystem.cpp | 410 +++++++++++++++--- .../Code/Source/TerrainSystem/TerrainSystem.h | 32 ++ Gems/Terrain/Code/Tests/TerrainSystemTest.cpp | 28 +- 8 files changed, 427 insertions(+), 73 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/SurfaceData/SurfaceData.cpp b/Code/Framework/AzFramework/AzFramework/SurfaceData/SurfaceData.cpp index 55fec57bb6..e287c8d948 100644 --- a/Code/Framework/AzFramework/AzFramework/SurfaceData/SurfaceData.cpp +++ b/Code/Framework/AzFramework/AzFramework/SurfaceData/SurfaceData.cpp @@ -37,6 +37,7 @@ namespace AzFramework::SurfaceData { if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) { + serializeContext->Class>(); serializeContext->Class() ->Field("m_position", &SurfacePoint::m_position) ->Field("m_normal", &SurfacePoint::m_normal) @@ -46,6 +47,7 @@ namespace AzFramework::SurfaceData if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { + behaviorContext->Class>(); behaviorContext->Class("AzFramework::SurfaceData::SurfacePoint") ->Attribute(AZ::Script::Attributes::Category, "SurfaceData") ->Constructor() diff --git a/Code/Framework/AzFramework/AzFramework/SurfaceData/SurfaceData.h b/Code/Framework/AzFramework/AzFramework/SurfaceData/SurfaceData.h index 9faa03f921..45e2ad3abb 100644 --- a/Code/Framework/AzFramework/AzFramework/SurfaceData/SurfaceData.h +++ b/Code/Framework/AzFramework/AzFramework/SurfaceData/SurfaceData.h @@ -10,13 +10,19 @@ #include #include #include -#include +#include namespace AzFramework::SurfaceData { namespace Constants { static constexpr const char* s_unassignedTagName = "(unassigned)"; + + //! The maximum number of surface weights that we can store. + //! For performance reasons, we want to limit this so that we can preallocate the max size in advance. + //! The current number is chosen to be higher than expected needs, but small enough to avoid being excessively wasteful. + //! (Dynamic structures would end up taking more memory than what we're preallocating) + static constexpr size_t MaxSurfaceWeights = 16; } struct SurfaceTagWeight @@ -70,7 +76,7 @@ namespace AzFramework::SurfaceData } }; - using SurfaceTagWeightList = AZStd::vector; + using SurfaceTagWeightList = AZStd::fixed_vector; struct SurfacePoint final { diff --git a/Gems/SurfaceData/Code/Include/SurfaceData/SurfaceDataTypes.h b/Gems/SurfaceData/Code/Include/SurfaceData/SurfaceDataTypes.h index 943c45bb6a..1d49fff3dc 100644 --- a/Gems/SurfaceData/Code/Include/SurfaceData/SurfaceDataTypes.h +++ b/Gems/SurfaceData/Code/Include/SurfaceData/SurfaceDataTypes.h @@ -29,12 +29,6 @@ namespace SurfaceData class SurfaceTagWeights { public: - //! The maximum number of surface weights that we can store. - //! For performance reasons, we want to limit this so that we can preallocate the max size in advance. - //! The current number is chosen to be higher than expected needs, but small enough to avoid being excessively wasteful. - //! (Dynamic structures would end up taking more memory than what we're preallocating) - static inline constexpr size_t MaxSurfaceWeights = 16; - SurfaceTagWeights() = default; //! Construct a collection of SurfaceTagWeights from the given SurfaceTagWeightList. @@ -65,7 +59,7 @@ namespace SurfaceData // early-out once we pass the location for the entry instead of always searching every entry. if (weightItr->m_surfaceType > tag) { - if (m_weights.size() != MaxSurfaceWeights) + if (m_weights.size() != AzFramework::SurfaceData::Constants::MaxSurfaceWeights) { // We didn't find the surface type, so add the new entry in sorted order. m_weights.insert(weightItr, { tag, weight }); @@ -85,7 +79,7 @@ namespace SurfaceData } // We didn't find the surface weight, and the sort order for it is at the end, so add it to the back of the list. - if (m_weights.size() != MaxSurfaceWeights) + if (m_weights.size() != AzFramework::SurfaceData::Constants::MaxSurfaceWeights) { m_weights.emplace_back(tag, weight); } @@ -188,7 +182,7 @@ namespace SurfaceData //! @return The pointer to the tag that's found, or end() if it wasn't found. const AzFramework::SurfaceData::SurfaceTagWeight* FindTag(AZ::Crc32 tag) const; - AZStd::fixed_vector m_weights; + AZStd::fixed_vector m_weights; }; //! SurfacePointList stores a collection of surface point data, which consists of positions, normals, and surface tag weights. diff --git a/Gems/SurfaceData/Code/Source/SurfaceDataTypes.cpp b/Gems/SurfaceData/Code/Source/SurfaceDataTypes.cpp index a25273896e..3d6378aa7c 100644 --- a/Gems/SurfaceData/Code/Source/SurfaceDataTypes.cpp +++ b/Gems/SurfaceData/Code/Source/SurfaceDataTypes.cpp @@ -42,7 +42,7 @@ namespace SurfaceData AzFramework::SurfaceData::SurfaceTagWeightList SurfaceTagWeights::GetSurfaceTagWeightList() const { AzFramework::SurfaceData::SurfaceTagWeightList weights; - weights.reserve(m_weights.size()); + for (auto& weight : m_weights) { weights.emplace_back(weight); diff --git a/Gems/SurfaceData/Code/Tests/SurfaceDataBenchmarks.cpp b/Gems/SurfaceData/Code/Tests/SurfaceDataBenchmarks.cpp index df011113da..becb91f0ce 100644 --- a/Gems/SurfaceData/Code/Tests/SurfaceDataBenchmarks.cpp +++ b/Gems/SurfaceData/Code/Tests/SurfaceDataBenchmarks.cpp @@ -275,7 +275,7 @@ namespace UnitTest { AZ_PROFILE_FUNCTION(Entity); - AZ::Crc32 tags[SurfaceData::SurfaceTagWeights::MaxSurfaceWeights]; + AZ::Crc32 tags[AzFramework::SurfaceData::Constants::MaxSurfaceWeights]; AZ::SimpleLcgRandom randomGenerator(1234567); // Declare this outside the loop so that we aren't benchmarking creation and destruction. @@ -316,7 +316,7 @@ namespace UnitTest { AZ_PROFILE_FUNCTION(Entity); - AZ::Crc32 tags[SurfaceData::SurfaceTagWeights::MaxSurfaceWeights]; + AZ::Crc32 tags[AzFramework::SurfaceData::Constants::MaxSurfaceWeights]; AZ::SimpleLcgRandom randomGenerator(1234567); // Declare this outside the loop so that we aren't benchmarking creation and destruction. diff --git a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp index 8976faadac..6ce83094e4 100644 --- a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp +++ b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp @@ -177,6 +177,193 @@ bool TerrainSystem::InWorldBounds(float x, float y) const return false; } +// Generate positions to be queried based on the sampler type. +void TerrainSystem::GenerateQueryPositions(const AZStd::span& inPositions, + AZStd::vector& outPositions, + Sampler sampler) const +{ + const float minHeight = m_currentSettings.m_worldBounds.GetMin().GetZ(); + for (auto& position : inPositions) + { + switch(sampler) + { + case AzFramework::Terrain::TerrainDataRequests::Sampler::BILINEAR: + { + AZ::Vector2 normalizedDelta; + AZ::Vector2 pos0; + ClampPosition(position.GetX(), position.GetY(), pos0, normalizedDelta); + const AZ::Vector2 pos1(pos0.GetX() + m_currentSettings.m_heightQueryResolution, + pos0.GetY() + m_currentSettings.m_heightQueryResolution); + outPositions.emplace_back(AZ::Vector3(pos0.GetX(), pos0.GetY(), minHeight)); + outPositions.emplace_back(AZ::Vector3(pos1.GetX(), pos0.GetY(), minHeight)); + outPositions.emplace_back(AZ::Vector3(pos0.GetX(), pos1.GetY(), minHeight)); + outPositions.emplace_back(AZ::Vector3(pos1.GetX(), pos1.GetY(), minHeight)); + } + break; + case AzFramework::Terrain::TerrainDataRequests::Sampler::CLAMP: + { + AZ::Vector2 normalizedDelta; + AZ::Vector2 clampedPosition; + ClampPosition(position.GetX(), position.GetY(), clampedPosition, normalizedDelta); + outPositions.emplace_back(AZ::Vector3(clampedPosition.GetX(), clampedPosition.GetY(), minHeight)); + } + break; + case AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT: + [[fallthrough]]; + default: + outPositions.emplace_back(AZ::Vector3(position.GetX(), position.GetY(), minHeight)); + break; + } + } +} + +AZStd::vector TerrainSystem::GenerateInputPositionsFromRegion( + const AZ::Aabb& inRegion, + const AZ::Vector2& stepSize) const +{ + AZStd::vector inPositions; + const auto [numSamplesX, numSamplesY] = GetNumSamplesFromRegion(inRegion, stepSize); + inPositions.reserve(numSamplesX * numSamplesY); + + for (size_t y = 0; y < numSamplesY; y++) + { + float fy = aznumeric_cast(inRegion.GetMin().GetY() + (y * stepSize.GetY())); + for (size_t x = 0; x < numSamplesX; x++) + { + float fx = aznumeric_cast(inRegion.GetMin().GetX() + (x * stepSize.GetX())); + inPositions.emplace_back(AZ::Vector3(fx, fy, 0.0f)); + } + } + + return inPositions; +} + +void TerrainSystem::MakeBulkQueries( + const AZStd::span inPositions, + AZStd::span outPositions, + AZStd::span outTerrainExists, + AZStd::span outSurfaceWeights, + BulkQueriesCallback queryCallback) const +{ + AZ::Aabb bounds; + AZ::EntityId prevAreaId = FindBestAreaEntityAtPosition(inPositions[0].GetX(), inPositions[0].GetY(), bounds); + + // We use a sliding window here and update the window end for each + // position that falls in the same area as the previous positions. This consumes lesser memory + // than sorting the points into separate lists and handling putting them back together. + // This may be sub optimal if the points are randomly distributed in the list as opposed + // to points in the same area id being close to each other. + size_t windowStart = 0; + size_t windowEnd = 0; + const size_t numPositions = inPositions.size(); + for(int i = 1; i < numPositions; i++) + { + AZ::EntityId areaId = FindBestAreaEntityAtPosition(inPositions[i].GetX(), inPositions[i].GetY(), bounds); + bool queryHeights = false; + if (areaId == prevAreaId) + { + // Update window end to current position. + // If it's the last position, submit the query. + windowEnd = i; + if (windowEnd == numPositions - 1) + { + queryHeights = true; + } + } + else + { + queryHeights = true; + } + + if (queryHeights) + { + // If the area id is a default entity id, it usually means the + // position is outside world bounds. + if (prevAreaId != AZ::EntityId()) + { + size_t spanLength = (windowEnd - windowStart) + 1; + queryCallback(AZStd::span(inPositions.begin() + windowStart, spanLength), + AZStd::span(outPositions.begin() + windowStart, spanLength), + AZStd::span(outTerrainExists.begin() + windowStart, spanLength), + AZStd::span(outSurfaceWeights.begin() + windowStart, spanLength), + prevAreaId); + } + + // Reset the window to start at the current position. Set the new area + // id on which to run the next query. + windowStart = windowEnd = i; + prevAreaId = areaId; + } + } +} + +void TerrainSystem::GetHeightsSynchronous(const AZStd::span& inPositions, Sampler sampler, + AZStd::span heights, AZStd::span terrainExists) const +{ + AZStd::shared_lock lock(m_areaMutex); + + AZStd::vector outPositions; + AZStd::vector outTerrainExists; + + // outPositions holds the iterators to results of the bulk queries. + // In the case of the bilinear sampler, we'll be making 4 queries per + // input position. + size_t indexStepSize = (sampler == AzFramework::Terrain::TerrainDataRequests::Sampler::BILINEAR) ? 4 : 1; + outPositions.reserve(inPositions.size() * indexStepSize); + outTerrainExists.resize(inPositions.size() * indexStepSize); + + GenerateQueryPositions(inPositions, outPositions, sampler); + + auto callback = []([[maybe_unused]] const AZStd::span inPositions, + AZStd::span outPositions, + AZStd::span outTerrainExists, + [[maybe_unused]] AZStd::span outSurfaceWeights, + AZ::EntityId areaId) + { + AZ_Assert((inPositions.size() == outPositions.size() && inPositions.size() == outTerrainExists.size()), + "The sizes of the terrain exists list and in/out positions list should match."); + Terrain::TerrainAreaHeightRequestBus::Event(areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetHeights, + outPositions, outTerrainExists); + }; + + // This will be unused for heights. It's fine if it's empty. + AZStd::vector outSurfaceWeights; + MakeBulkQueries(outPositions, outPositions, outTerrainExists, outSurfaceWeights, callback); + + // Compute/store the final result + for (size_t i = 0, iteratorIndex = 0; i < inPositions.size(); i++, iteratorIndex += indexStepSize) + { + switch(sampler) + { + case AzFramework::Terrain::TerrainDataRequests::Sampler::BILINEAR: + { + // We now need to compute the final height after all the bulk queries are done. + AZ::Vector2 normalizedDelta; + AZ::Vector2 clampedPosition; + ClampPosition(inPositions[i].GetX(), inPositions[i].GetY(), clampedPosition, normalizedDelta); + const float heightX0Y0 = outPositions[iteratorIndex].GetZ(); + const float heightX1Y0 = outPositions[iteratorIndex + 1].GetZ(); + const float heightX0Y1 = outPositions[iteratorIndex + 2].GetZ(); + const float heightX1Y1 = outPositions[iteratorIndex + 3].GetZ(); + const float heightXY0 = AZ::Lerp(heightX0Y0, heightX1Y0, normalizedDelta.GetX()); + const float heightXY1 = AZ::Lerp(heightX0Y1, heightX1Y1, normalizedDelta.GetX()); + heights[i] = AZ::Lerp(heightXY0, heightXY1, normalizedDelta.GetY()); + terrainExists[i] = outTerrainExists[iteratorIndex]; + } + break; + case AzFramework::Terrain::TerrainDataRequests::Sampler::CLAMP: + [[fallthrough]]; + case AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT: + [[fallthrough]]; + default: + // For clamp and exact, we just need to store the results of the bulk query. + heights[i] = outPositions[iteratorIndex].GetZ(); + terrainExists[i] = outTerrainExists[iteratorIndex]; + break; + } + } +} + float TerrainSystem::GetHeightSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const { bool terrainExists = false; @@ -315,6 +502,39 @@ bool TerrainSystem::GetIsHoleFromFloats(float x, float y, Sampler sampler) const return !terrainExists; } +void TerrainSystem::GetNormalsSynchronous(const AZStd::span& inPositions, Sampler sampler, + AZStd::span normals, AZStd::span terrainExists) const +{ + AZStd::vector directionVectors; + directionVectors.reserve(inPositions.size() * 4); + const AZ::Vector2 range(m_currentSettings.m_heightQueryResolution / 2.0f, m_currentSettings.m_heightQueryResolution / 2.0f); + size_t indexStepSize = 4; + for (auto& position : inPositions) + { + directionVectors.emplace_back(position.GetX(), position.GetY() - range.GetY(), 0.0f); + directionVectors.emplace_back(position.GetX() - range.GetX(), position.GetY(), 0.0f); + directionVectors.emplace_back(position.GetX() + range.GetX(), position.GetY(), 0.0f); + directionVectors.emplace_back(position.GetX(), position.GetY() + range.GetY(), 0.0f); + } + + AZStd::vector heights(directionVectors.size()); + AZStd::vector exists(directionVectors.size()); + GetHeightsSynchronous(directionVectors, sampler, heights, exists); + + for (size_t i = 0, iteratorIndex = 0; i < inPositions.size(); i++, iteratorIndex += indexStepSize) + { + directionVectors[iteratorIndex].SetZ(heights[iteratorIndex]); + directionVectors[iteratorIndex + 1].SetZ(heights[iteratorIndex + 1]); + directionVectors[iteratorIndex + 2].SetZ(heights[iteratorIndex + 2]); + directionVectors[iteratorIndex + 3].SetZ(heights[iteratorIndex + 3]); + + normals[i] = (directionVectors[iteratorIndex + 2] - directionVectors[iteratorIndex + 1]). + Cross(directionVectors[iteratorIndex + 3] - directionVectors[iteratorIndex]).GetNormalized(); + + terrainExists[i] = exists[iteratorIndex]; + } +} + AZ::Vector3 TerrainSystem::GetNormalSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const { AZStd::shared_lock lock(m_areaMutex); @@ -471,6 +691,35 @@ AZ::EntityId TerrainSystem::FindBestAreaEntityAtPosition(float x, float y, AZ::A return AZ::EntityId(); } +void TerrainSystem::GetOrderedSurfaceWeightsFromList( + const AZStd::span& inPositions, + [[maybe_unused]] Sampler sampler, + AZStd::span outSurfaceWeightsList, + AZStd::span terrainExists) const +{ + if (terrainExists.size() == outSurfaceWeightsList.size()) + { + AZStd::vector heights(inPositions.size()); + GetHeightsSynchronous(inPositions, AzFramework::Terrain::TerrainDataRequests::Sampler::EXACT, heights, terrainExists); + } + + auto callback = [](const AZStd::span inPositions, + [[maybe_unused]] AZStd::span outPositions, + [[maybe_unused]] AZStd::span outTerrainExists, + AZStd::span outSurfaceWeights, + AZ::EntityId areaId) + { + AZ_Assert(inPositions.size() == outSurfaceWeights.size(), + "The sizes of the surface weights list and in/out positions list should match."); + Terrain::TerrainAreaSurfaceRequestBus::Event(areaId, &Terrain::TerrainAreaSurfaceRequestBus::Events::GetSurfaceWeightsFromList, + inPositions, outSurfaceWeights); + }; + + // This will be unused for surface weights. It's fine if it's empty. + AZStd::vector outPositions; + MakeBulkQueries(inPositions, outPositions, terrainExists, outSurfaceWeightsList, callback); +} + void TerrainSystem::GetOrderedSurfaceWeights( const float x, const float y, @@ -551,13 +800,17 @@ void TerrainSystem::ProcessHeightsFromList( return; } + AZStd::vector terrainExists(inPositions.size()); + AZStd::vector heights(inPositions.size()); + + GetHeightsSynchronous(inPositions, sampleFilter, heights, terrainExists); + AzFramework::SurfaceData::SurfacePoint surfacePoint; - for (const auto& position : inPositions) + for (size_t i = 0; i < inPositions.size(); i++) { - bool terrainExists = false; - surfacePoint.m_position = position; - surfacePoint.m_position.SetZ(GetHeight(position, sampleFilter, &terrainExists)); - perPositionCallback(surfacePoint, terrainExists); + surfacePoint.m_position = inPositions[i]; + surfacePoint.m_position.SetZ(heights[i]); + perPositionCallback(surfacePoint, terrainExists[i]); } } @@ -571,13 +824,17 @@ void TerrainSystem::ProcessNormalsFromList( return; } + AZStd::vector terrainExists(inPositions.size()); + AZStd::vector normals(inPositions.size()); + + GetNormalsSynchronous(inPositions, sampleFilter, normals, terrainExists); + AzFramework::SurfaceData::SurfacePoint surfacePoint; - for (const auto& position : inPositions) + for (size_t i = 0; i < inPositions.size(); i++) { - bool terrainExists = false; - surfacePoint.m_position = position; - surfacePoint.m_normal = GetNormal(position, sampleFilter, &terrainExists); - perPositionCallback(surfacePoint, terrainExists); + surfacePoint.m_position = inPositions[i]; + surfacePoint.m_normal = AZStd::move(normals[i]); + perPositionCallback(surfacePoint, terrainExists[i]); } } @@ -591,13 +848,17 @@ void TerrainSystem::ProcessSurfaceWeightsFromList( return; } + AZStd::vector outSurfaceWeightsList(inPositions.size()); + AZStd::vector terrainExists(inPositions.size()); + + GetOrderedSurfaceWeightsFromList(inPositions, sampleFilter, outSurfaceWeightsList, terrainExists); + AzFramework::SurfaceData::SurfacePoint surfacePoint; - for (const auto& position : inPositions) + for (size_t i = 0; i < inPositions.size(); i++) { - bool terrainExists = false; - surfacePoint.m_position = position; - GetSurfaceWeights(position, surfacePoint.m_surfaceTags, sampleFilter, &terrainExists); - perPositionCallback(surfacePoint, terrainExists); + surfacePoint.m_position = inPositions[i]; + surfacePoint.m_surfaceTags = AZStd::move(outSurfaceWeightsList[i]); + perPositionCallback(surfacePoint, terrainExists[i]); } } @@ -611,13 +872,26 @@ void TerrainSystem::ProcessSurfacePointsFromList( return; } + AZStd::vector heights(inPositions.size()); + AZStd::vector normals(inPositions.size()); + AZStd::vector outSurfaceWeightsList(inPositions.size()); + AZStd::vector terrainExists(inPositions.size()); + + GetHeightsSynchronous(inPositions, sampleFilter, heights, terrainExists); + GetNormalsSynchronous(inPositions, sampleFilter, normals, terrainExists); + + // We can skip the unnecessary call to GetHeights since we already + // got the terrain exists flags in the earlier call to GetHeights + AZStd::vector terrainExistsEmpty; + GetOrderedSurfaceWeightsFromList(inPositions, sampleFilter, outSurfaceWeightsList, terrainExistsEmpty); + AzFramework::SurfaceData::SurfacePoint surfacePoint; - for (const auto& position : inPositions) + for (size_t i = 0; i < inPositions.size(); i++) { - bool terrainExists = false; - surfacePoint.m_position = position; - GetSurfacePoint(position, surfacePoint, sampleFilter, &terrainExists); - perPositionCallback(surfacePoint, terrainExists); + surfacePoint.m_position.Set(inPositions[i].GetX(), inPositions[i].GetY(), heights[i]); + surfacePoint.m_normal = AZStd::move(normals[i]); + surfacePoint.m_surfaceTags = AZStd::move(outSurfaceWeightsList[i]); + perPositionCallback(surfacePoint, terrainExists[i]); } } @@ -723,20 +997,23 @@ void TerrainSystem::ProcessHeightsFromRegion( return; } - const size_t numSamplesX = aznumeric_cast(ceil(inRegion.GetExtents().GetX() / stepSize.GetX())); - const size_t numSamplesY = aznumeric_cast(ceil(inRegion.GetExtents().GetY() / stepSize.GetY())); + const auto [numSamplesX, numSamplesY] = GetNumSamplesFromRegion(inRegion, stepSize); + + AZStd::vector inPositions = GenerateInputPositionsFromRegion(inRegion, stepSize); + + AZStd::vector terrainExists(inPositions.size()); + AZStd::vector heights(inPositions.size()); + + GetHeightsSynchronous(inPositions, sampleFilter, heights, terrainExists); AzFramework::SurfaceData::SurfacePoint surfacePoint; - for (size_t y = 0; y < numSamplesY; y++) + for (size_t y = 0, i = 0; y < numSamplesY; y++) { - float fy = aznumeric_cast(inRegion.GetMin().GetY() + (y * stepSize.GetY())); for (size_t x = 0; x < numSamplesX; x++) { - bool terrainExists = false; - float fx = aznumeric_cast(inRegion.GetMin().GetX() + (x * stepSize.GetX())); - surfacePoint.m_position.Set(fx, fy, 0.0f); - surfacePoint.m_position.SetZ(GetHeight(surfacePoint.m_position, sampleFilter, &terrainExists)); - perPositionCallback(x, y, surfacePoint, terrainExists); + surfacePoint.m_position.Set(inPositions[i].GetX(), inPositions[i].GetY(), heights[i]); + perPositionCallback(x, y, surfacePoint, terrainExists[i]); + i++; } } } @@ -753,20 +1030,24 @@ void TerrainSystem::ProcessNormalsFromRegion( return; } - const size_t numSamplesX = aznumeric_cast(ceil(inRegion.GetExtents().GetX() / stepSize.GetX())); - const size_t numSamplesY = aznumeric_cast(ceil(inRegion.GetExtents().GetY() / stepSize.GetY())); + const auto [numSamplesX, numSamplesY] = GetNumSamplesFromRegion(inRegion, stepSize); + + AZStd::vector inPositions = GenerateInputPositionsFromRegion(inRegion, stepSize); + + AZStd::vector terrainExists(inPositions.size()); + AZStd::vector normals(inPositions.size()); + + GetNormalsSynchronous(inPositions, sampleFilter, normals, terrainExists); AzFramework::SurfaceData::SurfacePoint surfacePoint; - for (size_t y = 0; y < numSamplesY; y++) + for (size_t y = 0, i = 0; y < numSamplesY; y++) { - float fy = aznumeric_cast(inRegion.GetMin().GetY() + (y * stepSize.GetY())); for (size_t x = 0; x < numSamplesX; x++) { - bool terrainExists = false; - float fx = aznumeric_cast(inRegion.GetMin().GetX() + (x * stepSize.GetX())); - surfacePoint.m_position.Set(fx, fy, 0.0f); - surfacePoint.m_normal = GetNormal(surfacePoint.m_position, sampleFilter, &terrainExists); - perPositionCallback(x, y, surfacePoint, terrainExists); + surfacePoint.m_position.Set(inPositions[i].GetX(), inPositions[i].GetY(), 0.0f); + surfacePoint.m_normal = AZStd::move(normals[i]); + perPositionCallback(x, y, surfacePoint, terrainExists[i]); + i++; } } } @@ -783,20 +1064,24 @@ void TerrainSystem::ProcessSurfaceWeightsFromRegion( return; } - const size_t numSamplesX = aznumeric_cast(ceil(inRegion.GetExtents().GetX() / stepSize.GetX())); - const size_t numSamplesY = aznumeric_cast(ceil(inRegion.GetExtents().GetY() / stepSize.GetY())); + const auto [numSamplesX, numSamplesY] = GetNumSamplesFromRegion(inRegion, stepSize); + + AZStd::vector inPositions = GenerateInputPositionsFromRegion(inRegion, stepSize); + + AZStd::vector outSurfaceWeightsList(inPositions.size()); + AZStd::vector terrainExists(inPositions.size()); + + GetOrderedSurfaceWeightsFromList(inPositions, sampleFilter, outSurfaceWeightsList, terrainExists); AzFramework::SurfaceData::SurfacePoint surfacePoint; - for (size_t y = 0; y < numSamplesY; y++) + for (size_t y = 0, i = 0; y < numSamplesY; y++) { - float fy = aznumeric_cast(inRegion.GetMin().GetY() + (y * stepSize.GetY())); for (size_t x = 0; x < numSamplesX; x++) { - bool terrainExists = false; - float fx = aznumeric_cast(inRegion.GetMin().GetX() + (x * stepSize.GetX())); - surfacePoint.m_position.Set(fx, fy, 0.0f); - GetSurfaceWeights(surfacePoint.m_position, surfacePoint.m_surfaceTags, sampleFilter, &terrainExists); - perPositionCallback(x, y, surfacePoint, terrainExists); + surfacePoint.m_position.Set(inPositions[i].GetX(), inPositions[i].GetY(), 0.0f); + surfacePoint.m_surfaceTags = AZStd::move(outSurfaceWeightsList[i]); + perPositionCallback(x, y, surfacePoint, terrainExists[i]); + i++; } } } @@ -813,20 +1098,33 @@ void TerrainSystem::ProcessSurfacePointsFromRegion( return; } - const size_t numSamplesX = aznumeric_cast(ceil(inRegion.GetExtents().GetX() / stepSize.GetX())); - const size_t numSamplesY = aznumeric_cast(ceil(inRegion.GetExtents().GetY() / stepSize.GetY())); + const auto [numSamplesX, numSamplesY] = GetNumSamplesFromRegion(inRegion, stepSize); + + AZStd::vector inPositions = GenerateInputPositionsFromRegion(inRegion, stepSize); + + AZStd::vector heights(inPositions.size()); + AZStd::vector normals(inPositions.size()); + AZStd::vector outSurfaceWeightsList(inPositions.size()); + AZStd::vector terrainExists(inPositions.size()); + + GetHeightsSynchronous(inPositions, sampleFilter, heights, terrainExists); + GetNormalsSynchronous(inPositions, sampleFilter, normals, terrainExists); + + // We can skip the unnecessary call to GetHeights since we already + // got the terrain exists flags in the earlier call to GetHeights + AZStd::vector terrainExistsEmpty; + GetOrderedSurfaceWeightsFromList(inPositions, sampleFilter, outSurfaceWeightsList, terrainExistsEmpty); AzFramework::SurfaceData::SurfacePoint surfacePoint; - for (size_t y = 0; y < numSamplesY; y++) + for (size_t y = 0, i = 0; y < numSamplesY; y++) { - float fy = aznumeric_cast(inRegion.GetMin().GetY() + (y * stepSize.GetY())); for (size_t x = 0; x < numSamplesX; x++) { - bool terrainExists = false; - float fx = aznumeric_cast(inRegion.GetMin().GetX() + (x * stepSize.GetX())); - surfacePoint.m_position.Set(fx, fy, 0.0f); - GetSurfacePoint(surfacePoint.m_position, surfacePoint, sampleFilter, &terrainExists); - perPositionCallback(x, y, surfacePoint, terrainExists); + surfacePoint.m_position.Set(inPositions[i].GetX(), inPositions[i].GetY(), heights[i]); + surfacePoint.m_normal = AZStd::move(normals[i]); + surfacePoint.m_surfaceTags = AZStd::move(outSurfaceWeightsList[i]); + perPositionCallback(x, y, surfacePoint, terrainExists[i]); + i++; } } } diff --git a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h index e0457b80af..7895ab96cc 100644 --- a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h +++ b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h @@ -207,6 +207,38 @@ namespace Terrain float GetTerrainAreaHeight(float x, float y, bool& terrainExists) const; AZ::Vector3 GetNormalSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const; + typedef AZStd::function inPositions, + AZStd::span outPositions, + AZStd::span outTerrainExists, + AZStd::span outSurfaceWeights, + AZ::EntityId areaId)> BulkQueriesCallback; + + void GetHeightsSynchronous( + const AZStd::span& inPositions, + Sampler sampler, AZStd::span heights, + AZStd::span terrainExists) const; + void GetNormalsSynchronous( + const AZStd::span& inPositions, + Sampler sampler, AZStd::span normals, + AZStd::span terrainExists) const; + void GetOrderedSurfaceWeightsFromList( + const AZStd::span& inPositions, Sampler sampler, + AZStd::span outSurfaceWeightsList, + AZStd::span terrainExists) const; + void MakeBulkQueries( + const AZStd::span inPositions, + AZStd::span outPositions, + AZStd::span outTerrainExists, + AZStd::span outSurfaceWieghts, + BulkQueriesCallback queryCallback) const; + void GenerateQueryPositions(const AZStd::span& inPositions, + AZStd::vector& outPositions, + Sampler sampler) const; + AZStd::vector GenerateInputPositionsFromRegion( + const AZ::Aabb& inRegion, + const AZ::Vector2& stepSize) const; + // AZ::TickBus::Handler overrides ... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; diff --git a/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp b/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp index 2c01a3d455..1277e9ed20 100644 --- a/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp +++ b/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp @@ -158,6 +158,15 @@ namespace UnitTest // Let the test function modify these values based on the needs of the specific test. mockHeights(outPosition, terrainExists); }); + ON_CALL(*m_terrainAreaHeightRequests, GetHeights) + .WillByDefault( + [mockHeights](AZStd::span inOutPositionList, AZStd::span terrainExistsList) + { + for (int i = 0; i < inOutPositionList.size(); i++) + { + mockHeights(inOutPositionList[i], terrainExistsList[i]); + } + }); ActivateEntity(entity.get()); return entity; @@ -184,9 +193,9 @@ namespace UnitTest tagWeight3.m_weight = 0.3f; expectedTags.push_back(tagWeight3); - m_terrainAreaSurfaceRequests = AZStd::make_unique>(entity->GetId()); - ON_CALL(*m_terrainAreaSurfaceRequests, GetSurfaceWeights).WillByDefault( - [tagWeight1, tagWeight2, tagWeight3](const AZ::Vector3& position, AzFramework::SurfaceData::SurfaceTagWeightList& surfaceWeights) + auto mockGetSurfaceWeights = [tagWeight1, tagWeight2, tagWeight3]( + const AZ::Vector3& position, + AzFramework::SurfaceData::SurfaceTagWeightList& surfaceWeights) { surfaceWeights.clear(); float absYPos = fabsf(position.GetY()); @@ -202,6 +211,19 @@ namespace UnitTest { surfaceWeights.push_back(tagWeight3); } + }; + + m_terrainAreaSurfaceRequests = AZStd::make_unique>(entity->GetId()); + ON_CALL(*m_terrainAreaSurfaceRequests, GetSurfaceWeights).WillByDefault(mockGetSurfaceWeights); + ON_CALL(*m_terrainAreaSurfaceRequests, GetSurfaceWeightsFromList).WillByDefault( + [mockGetSurfaceWeights]( + AZStd::span inPositionList, + AZStd::span outSurfaceWeightsList) + { + for (size_t i = 0; i < inPositionList.size(); i++) + { + mockGetSurfaceWeights(inPositionList[i], outSurfaceWeightsList[i]); + } } ); } From 6791b652cc3a544ad3650ec69b99a594a4b39caf Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Thu, 10 Feb 2022 10:17:01 -0600 Subject: [PATCH 053/133] Fix memory allocation that caused benchmark runs to crash. (#7535) Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> --- Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h b/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h index c45af43ad9..4d2233528b 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h +++ b/Gems/GradientSignal/Code/Tests/GradientSignalTestFixtures.h @@ -90,7 +90,7 @@ namespace UnitTest AZStd::unique_ptr BuildTestSurfaceMaskGradient(float shapeHalfBounds); AZStd::unique_ptr BuildTestSurfaceSlopeGradient(float shapeHalfBounds); - AZ::RPI::AssetHandlerPtrList m_assetHandlers; + AZStd::fixed_vector, 2> m_assetHandlers; }; struct GradientSignalTest From c7e1a6d0b65e2448416cd268f87bc349fbcf1ca4 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 10 Feb 2022 16:43:49 +0000 Subject: [PATCH 054/133] add more collider manipulator tests Signed-off-by: greerdv --- .../Tests/PhysXColliderComponentModeTests.cpp | 101 ++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderComponentModeTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderComponentModeTests.cpp index e323110d6f..a9797d3d53 100644 --- a/Gems/PhysX/Code/Tests/PhysXColliderComponentModeTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXColliderComponentModeTests.cpp @@ -712,4 +712,105 @@ namespace UnitTest EXPECT_NEAR(newSphereRadius, 0.9f, ManipulatorTolerance); } + + TEST_F(PhysXEditorColliderComponentManipulatorFixture, CapsuleColliderScaleManipulatorsCorrectlyLocatedRelativeToColliderWithNonUniformScale) + { + const float capsuleRadius = 0.2f; + const float capsuleHeight = 1.0f; + const AZ::Quaternion capsuleRotation(-0.2f, -0.8f, -0.4f, 0.4f); + const AZ::Vector3 capsuleOffset(1.0f, -2.0f, 1.0f); + SetupCollider(Physics::CapsuleShapeConfiguration(capsuleHeight, capsuleRadius), capsuleRotation, capsuleOffset); + const AZ::Quaternion entityRotation(0.7f, -0.1f, -0.1f, 0.7f); + const AZ::Vector3 entityTranslation(-2.0f, 1.0f, -3.0f); + const float uniformScale = 2.0f; + SetupTransform(entityRotation, entityTranslation, uniformScale); + const AZ::Vector3 nonUniformScale(1.0f, 0.5f, 1.5f); + SetupNonUniformScale(nonUniformScale); + EnterColliderSubMode(PhysX::ColliderComponentModeRequests::SubMode::Dimensions); + + // the expected position of the collider centre based on the combination of entity transform, collider offset and non-uniform scale + const AZ::Vector3 expectedColliderPosition(-0.92f, -2.44f, -5.0f); + + // the expected position of the height manipulator relative to the centre of the collider, based on collider + // rotation, entity scale and non-uniform scale + const AZ::Vector3 heightManipulatorDelta(-0.3096f, 0.6528f, 0.4f); + + // position the camera to look at the collider along the y-z diagonal + AzFramework::SetCameraTransform( + m_cameraState, + AZ::Transform::CreateFromQuaternionAndTranslation( + AZ::Quaternion::CreateRotationX(-AZ::Constants::QuarterPi), expectedColliderPosition + AZ::Vector3(0.0f, -1.0f, 1.0f))); + + const AZ::Vector3 worldStart = expectedColliderPosition + heightManipulatorDelta; + const AZ::Vector3 worldEnd = worldStart + 0.2f * heightManipulatorDelta; + + const auto screenStart = AzFramework::WorldToScreen(worldStart, m_cameraState); + const auto screenEnd = AzFramework::WorldToScreen(worldEnd, m_cameraState); + + m_actionDispatcher + ->CameraState(m_cameraState) + // move the mouse to the position of the height manipulator + ->MousePosition(screenStart) + // drag to move the manipulator + ->MouseLButtonDown() + ->MousePosition(screenEnd) + ->MouseLButtonUp(); + + float newCapsuleHeight = 0.0f; + PhysX::EditorColliderComponentRequestBus::EventResult( + newCapsuleHeight, m_idPair, &PhysX::EditorColliderComponentRequests::GetCapsuleHeight); + + EXPECT_NEAR(newCapsuleHeight, 1.2f, ManipulatorTolerance); + } + + TEST_F(PhysXEditorColliderComponentManipulatorFixture, ColliderRotationManipulatorsCorrectlyLocatedRelativeToColliderWithNonUniformScale) + { + const float capsuleRadius = 1.2f; + const float capsuleHeight = 4.0f; + const AZ::Quaternion capsuleRotation(0.7f, 0.7f, -0.1f, 0.1f); + const AZ::Vector3 capsuleOffset(-2.0f, -2.0f, 1.0f); + SetupCollider(Physics::CapsuleShapeConfiguration(capsuleHeight, capsuleRadius), capsuleRotation, capsuleOffset); + const AZ::Quaternion entityRotation(0.8f, -0.4f, -0.4f, 0.2f); + const AZ::Vector3 entityTranslation(1.0f, -1.5f, 2.0f); + const float uniformScale = 1.5f; + SetupTransform(entityRotation, entityTranslation, uniformScale); + const AZ::Vector3 nonUniformScale(1.5f, 1.5f, 2.0f); + SetupNonUniformScale(nonUniformScale); + EnterColliderSubMode(PhysX::ColliderComponentModeRequests::SubMode::Rotation); + + // the expected position of the collider centre based on the combination of entity transform, collider offset and non-uniform scale + const AZ::Vector3 expectedColliderPosition(-0.86f, 4.8f, -0.52f); + + // the y and z axes of the collider's frame in world space, used to locate points on the x rotation manipulator arc to interact with + const AZ::Vector3 yDirection(0.36f, -0.8f, -0.48f); + const AZ::Vector3 zDirection(0.9024f, 0.168f, 0.3968f); + + // position the camera to look at the collider along the world y axis + AzFramework::SetCameraTransform( + m_cameraState, + AZ::Transform::CreateTranslation(expectedColliderPosition - AZ::Vector3(0.0f, 10.0f, 0.0f))); + + const float screenToWorldMultiplier = AzToolsFramework::CalculateScreenToWorldMultiplier(expectedColliderPosition, m_cameraState); + const float manipulatorViewRadius = 2.0f; + const AZ::Vector3 worldStart = expectedColliderPosition + screenToWorldMultiplier * manipulatorViewRadius * yDirection; + const AZ::Vector3 worldEnd = expectedColliderPosition + screenToWorldMultiplier * manipulatorViewRadius * zDirection; + + const auto screenStart = AzFramework::WorldToScreen(worldStart, m_cameraState); + const auto screenEnd = AzFramework::WorldToScreen(worldEnd, m_cameraState); + + m_actionDispatcher + ->CameraState(m_cameraState) + // move the mouse to a position on the angular manipulator + ->MousePosition(screenStart) + // drag to move the manipulator + ->MouseLButtonDown() + ->MousePosition(screenEnd) + ->MouseLButtonUp(); + + AZ::Quaternion newColliderRotation = AZ::Quaternion::CreateIdentity(); + PhysX::EditorColliderComponentRequestBus::EventResult( + newColliderRotation, m_idPair, &PhysX::EditorColliderComponentRequests::GetColliderRotation); + + EXPECT_THAT(newColliderRotation, testing::Not(IsCloseTolerance(capsuleRotation, ManipulatorTolerance))); + } } // namespace UnitTest From 36285aa834feef9365d5a1a5bb3dda2cbe7165a4 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 10 Feb 2022 17:22:41 +0000 Subject: [PATCH 055/133] apply minor feedback from PR Signed-off-by: greerdv --- .../ComponentModes/BoxViewportEdit.cpp | 12 +++++++----- .../Code/Tests/EditorBoxShapeComponentTests.cpp | 3 +-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp index 8c47bfc797..cf3d8aa693 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp @@ -59,8 +59,8 @@ namespace AzToolsFramework if (auto& linearManipulator = m_linearManipulators[manipulatorIndex]) { linearManipulator->SetSpace(boxWorldFromLocal); - linearManipulator->SetLocalTransform(boxLocalTransform * AZ::Transform::CreateTranslation( - s_boxAxes[manipulatorIndex] * 0.5f * boxDimensions)); + linearManipulator->SetLocalTransform( + boxLocalTransform * AZ::Transform::CreateTranslation(s_boxAxes[manipulatorIndex] * 0.5f * boxDimensions)); linearManipulator->SetNonUniformScale(nonUniformScale); linearManipulator->SetBoundsDirty(); } @@ -88,7 +88,8 @@ namespace AzToolsFramework ManipulatorViews views; views.emplace_back(CreateManipulatorViewQuadBillboard( - AzFramework::ViewportColors::DefaultManipulatorHandleColor, AzFramework::ViewportConstants::DefaultManipulatorHandleSize)); + AzFramework::ViewportColors::DefaultManipulatorHandleColor, + AzFramework::ViewportConstants::DefaultManipulatorHandleSize)); linearManipulator->SetViews(AZStd::move(views)); linearManipulator->InstallMouseMoveCallback( @@ -105,7 +106,8 @@ namespace AzToolsFramework float boxScale = AZ::GetMax(AZ::MinTransformScale, boxWorldTransform.GetUniformScale()); // calculate the position of the manipulator in the reference frame of the box - // the local position offset of the manipulator does not take the transform scale into account, so need to apply it here + // the local position offset of the manipulator does not take the transform scale into account + // so need to apply it here const AZ::Vector3 localPosition = boxLocalTransform.GetInverse().TransformPoint( action.m_start.m_localPosition + action.m_current.m_localPositionOffset / boxScale); @@ -113,7 +115,7 @@ namespace AzToolsFramework // clamp movement so it cannot go negative based on axis direction const AZ::Vector3 axisDisplacement = localPosition.GetAbs() * 2.0f - * AZ::GetMax(0.0f, localPosition.GetNormalized().Dot(action.m_fixed.m_axis)); + * AZ::GetMax(0.0f, localPosition.GetNormalized().Dot(action.m_fixed.m_axis)); AZ::Vector3 boxDimensions = AZ::Vector3::CreateZero(); BoxManipulatorRequestBus::EventResult( diff --git a/Gems/LmbrCentral/Code/Tests/EditorBoxShapeComponentTests.cpp b/Gems/LmbrCentral/Code/Tests/EditorBoxShapeComponentTests.cpp index 713799640b..82a7f57937 100644 --- a/Gems/LmbrCentral/Code/Tests/EditorBoxShapeComponentTests.cpp +++ b/Gems/LmbrCentral/Code/Tests/EditorBoxShapeComponentTests.cpp @@ -118,7 +118,7 @@ namespace LmbrCentral TEST_F(EditorBoxShapeComponentManipulatorFixture, BoxShapeNonUniformScaleManipulatorsScaleCorrectly) { - // a rotation which should map (1, 0, 0) to (0.8, 0.6, 0) + // a rotation which rotates the x-axis to (0.8, 0.6, 0) const AZ::Quaternion boxRotation(0.0f, 0.0f, 0.316228f, 0.948683f); AZ::Transform boxTransform = AZ::Transform::CreateFromQuaternionAndTranslation(boxRotation, AZ::Vector3(2.0f, 3.0f, 4.0f)); boxTransform.SetUniformScale(1.5f); @@ -132,7 +132,6 @@ namespace LmbrCentral // enter the box shape component's component mode AzToolsFramework::SelectEntity(m_entity->GetId()); - AzToolsFramework::ComponentModeFramework::ComponentModeSystemRequestBus::Broadcast( &AzToolsFramework::ComponentModeFramework::ComponentModeSystemRequestBus::Events::AddSelectedComponentModesOfType, EditorBoxShapeComponentTypeId); From 27abad7564ca607900d6d7d6ca42b5dbf6832699 Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Thu, 10 Feb 2022 13:32:22 -0800 Subject: [PATCH 056/133] Fix Mac SQL Package (#7538) * Update mac SQLite3 package to fix bad version Signed-off-by: spham <82231385+spham-amzn@users.noreply.github.com> --- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index ae51076857..c0bc9060d4 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -42,5 +42,5 @@ ly_associate_package(PACKAGE_NAME astc-encoder-3.2-rev5-mac ly_associate_package(PACKAGE_NAME ISPCTexComp-36b80aa-rev1-mac TARGETS ISPCTexComp PACKAGE_HASH 8a4e93277b8face6ea2fd57c6d017bdb55643ed3d6387110bc5f6b3b884dd169) ly_associate_package(PACKAGE_NAME lz4-1.9.3-vcpkg-rev4-mac TARGETS lz4 PACKAGE_HASH 891ff630bf34f7ab1d8eaee2ea0a8f1fca89dbdc63fca41ee592703dd488a73b) ly_associate_package(PACKAGE_NAME azslc-1.7.35-rev1-mac TARGETS azslc PACKAGE_HASH 03cb1ea8c47d4c80c893e2e88767272d5d377838f5ba94b777a45902dd85052e) -ly_associate_package(PACKAGE_NAME SQLite-3.37.2-rev1-mac TARGETS SQLite PACKAGE_HASH f9101023f99cf32fc5867284ceb28c0761c23d2c5a4b1748349c69f976a2fbea) +ly_associate_package(PACKAGE_NAME SQLite-3.37.2-rev2-mac TARGETS SQLite PACKAGE_HASH b7d9abdb68045003e030e1a9a805db1aefa5e8fde6dccfbb4fab3a06249a41fc) ly_associate_package(PACKAGE_NAME AwsIotDeviceSdkCpp-1.15.2-rev2-mac TARGETS AwsIotDeviceSdkCpp PACKAGE_HASH 4854edb7b88fa6437b4e69e87d0ee111a25313ac2a2db5bb2f8b674ba0974f95) From 1865e3085e31443a10bce97d1e11b81957ab2dcc Mon Sep 17 00:00:00 2001 From: puvvadar Date: Thu, 10 Feb 2022 14:17:39 -0800 Subject: [PATCH 057/133] Fix improper early out skipping valid entities Signed-off-by: puvvadar --- .../Code/Source/NetworkTime/NetworkTime.cpp | 63 +++--- .../Source/NetworkTime/NetworkTime.cpp.orig | 187 ++++++++++++++++++ 2 files changed, 217 insertions(+), 33 deletions(-) create mode 100644 Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp.orig diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index 899640895d..c6b6385845 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -113,7 +113,7 @@ namespace Multiplayer NetworkEntityTracker* networkEntityTracker = GetNetworkEntityTracker(); AzFramework::IEntityBoundsUnion* entityBoundsUnion = AZ::Interface::Get(); AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(expandedVolume, - [this, debugDisplay, networkEntityTracker, entityBoundsUnion, expandedVolume](const AzFramework::IVisibilityScene::NodeData& nodeData) + [this, debugDisplay, networkEntityTracker, entityBoundsUnion, rewindVolume](const AzFramework::IVisibilityScene::NodeData& nodeData) { m_rewoundEntities.reserve(m_rewoundEntities.size() + nodeData.m_entries.size()); for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) @@ -122,44 +122,41 @@ namespace Multiplayer { AZ::Entity* entity = static_cast(visEntry->m_userData); NetworkEntityHandle entityHandle(entity, networkEntityTracker); - if (entityHandle.GetNetBindComponent() == nullptr) + if (entityHandle.GetNetBindComponent() != nullptr) { - // Not a net-bound entity, terminate processing of this entity - return; - } - - const AZ::Aabb currentBounds = entityBoundsUnion->GetEntityWorldBoundsUnion(entity->GetId()); - const AZ::Vector3 currentCenter = currentBounds.GetCenter(); - NetworkTransformComponent* networkTransform = entity->template FindComponent(); - if (debugDisplay) - { - debugDisplay->SetColor(AZ::Colors::White); - debugDisplay->DrawWireBox(currentBounds.GetMin(), currentBounds.GetMax()); - } - - if (networkTransform != nullptr) - { - // Get the rewound position for target host frame ID plus the one preceding it for potential lerp - AZ::Vector3 rewindCenter = networkTransform->GetTranslation(); - const AZ::Vector3 rewindCenterPrevious = networkTransform->GetTranslationPrevious(); - const float blendFactor = GetNetworkTime()->GetHostBlendFactor(); - if (!AZ::IsClose(blendFactor, 1.0f) && !rewindCenter.IsClose(rewindCenterPrevious)) - { - // If we have a blend factor, lerp the translation for accuracy - rewindCenter = rewindCenterPrevious.Lerp(rewindCenter, blendFactor); - } - const AZ::Vector3 rewindOffset = rewindCenter - currentCenter; // Compute offset between rewound and current positions - const AZ::Aabb rewoundAabb = currentBounds.GetTranslated(rewindOffset); // Apply offset to the entity aabb + const AZ::Aabb currentBounds = entityBoundsUnion->GetEntityWorldBoundsUnion(entity->GetId()); + const AZ::Vector3 currentCenter = currentBounds.GetCenter(); + NetworkTransformComponent* networkTransform = entity->template FindComponent(); if (debugDisplay) { - debugDisplay->SetColor(AZ::Colors::Grey); - debugDisplay->DrawWireBox(rewoundAabb.GetMin(), rewoundAabb.GetMax()); + debugDisplay->SetColor(AZ::Colors::White); + debugDisplay->DrawWireBox(currentBounds.GetMin(), currentBounds.GetMax()); } - if (AZ::ShapeIntersection::Overlaps(rewoundAabb, expandedVolume)) // Validate the rewound aabb intersects our rewind volume + if (networkTransform != nullptr) { - m_rewoundEntities.push_back(entityHandle); - entityHandle.GetNetBindComponent()->NotifySyncRewindState(); + // Get the rewound position for target host frame ID plus the one preceding it for potential lerp + AZ::Vector3 rewindCenter = networkTransform->GetTranslation(); + const AZ::Vector3 rewindCenterPrevious = networkTransform->GetTranslationPrevious(); + const float blendFactor = GetNetworkTime()->GetHostBlendFactor(); + if (!AZ::IsClose(blendFactor, 1.0f) && !rewindCenter.IsClose(rewindCenterPrevious)) + { + // If we have a blend factor, lerp the translation for accuracy + rewindCenter = rewindCenterPrevious.Lerp(rewindCenter, blendFactor); + } + const AZ::Vector3 rewindOffset = rewindCenter - currentCenter; // Compute offset between rewound and current positions + const AZ::Aabb rewoundAabb = currentBounds.GetTranslated(rewindOffset); // Apply offset to the entity aabb + if (debugDisplay) + { + debugDisplay->SetColor(AZ::Colors::Grey); + debugDisplay->DrawWireBox(rewoundAabb.GetMin(), rewoundAabb.GetMax()); + } + + if (AZ::ShapeIntersection::Overlaps(rewoundAabb, rewindVolume)) // Validate the rewound aabb intersects our rewind volume + { + m_rewoundEntities.push_back(entityHandle); + entityHandle.GetNetBindComponent()->NotifySyncRewindState(); + } } } } diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp.orig b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp.orig new file mode 100644 index 0000000000..26d53a50e1 --- /dev/null +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp.orig @@ -0,0 +1,187 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Multiplayer +{ + AZ_CVAR(float, sv_RewindVolumeExtrudeDistance, 50.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "The amount to increase rewind volume checks to account for fast moving entities"); + AZ_CVAR(bool, bg_RewindDebugDraw, false, nullptr, AZ::ConsoleFunctorFlags::Null, "If true enables debug draw of rewind operations"); + + NetworkTime::NetworkTime() + { + AZ::Interface::Register(this); + } + + NetworkTime::~NetworkTime() + { + AZ::Interface::Unregister(this); + } + + bool NetworkTime::IsTimeRewound() const + { + return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; + } + + HostFrameId NetworkTime::GetHostFrameId() const + { + return m_hostFrameId; + } + + HostFrameId NetworkTime::GetUnalteredHostFrameId() const + { + return m_unalteredFrameId; + } + + void NetworkTime::IncrementHostFrameId() + { + AZ_Assert(!IsTimeRewound(), "Incrementing the global application frameId is unsupported under a rewound time scope"); + ++m_unalteredFrameId; + m_hostFrameId = m_unalteredFrameId; + } + + AZ::TimeMs NetworkTime::GetHostTimeMs() const + { + return m_hostTimeMs; + } + + float NetworkTime::GetHostBlendFactor() const + { + return m_hostBlendFactor; + } + + AzNetworking::ConnectionId NetworkTime::GetRewindingConnectionId() const + { + return m_rewindingConnectionId; + } + + void NetworkTime::ForceSetTime(HostFrameId frameId, AZ::TimeMs timeMs) + { + AZ_Assert(!IsTimeRewound(), "Forcibly setting network time is unsupported under a rewound time scope"); + m_unalteredFrameId = frameId; + m_hostFrameId = frameId; + m_hostTimeMs = timeMs; + m_rewindingConnectionId = AzNetworking::InvalidConnectionId; + } + + void NetworkTime::AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, float blendFactor, AzNetworking::ConnectionId rewindConnectionId) + { + m_hostFrameId = frameId; + m_hostTimeMs = timeMs; + m_hostBlendFactor = blendFactor; + m_rewindingConnectionId = rewindConnectionId; + } + + void NetworkTime::SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) + { + if (!IsTimeRewound()) + { + // If we're not inside a rewind scope then reset any rewound state and exit + ClearRewoundEntities(); + return; + } + + // Since the vis system doesn't support rewound queries, first query with an expanded volume to catch any fast moving entities + const AZ::Aabb expandedVolume = rewindVolume.GetExpanded(AZ::Vector3(sv_RewindVolumeExtrudeDistance)); + + AzFramework::DebugDisplayRequests* debugDisplay = nullptr; + if (bg_RewindDebugDraw) + { + AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; + AzFramework::DebugDisplayRequestBus::Bind(debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); + debugDisplay = AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus); + } + + if (debugDisplay) + { + debugDisplay->SetColor(AZ::Colors::Red); + debugDisplay->DrawWireBox(expandedVolume.GetMin(), expandedVolume.GetMax()); + } + + NetworkEntityTracker* networkEntityTracker = GetNetworkEntityTracker(); + AzFramework::IEntityBoundsUnion* entityBoundsUnion = AZ::Interface::Get(); + AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(expandedVolume, + [this, debugDisplay, networkEntityTracker, entityBoundsUnion, expandedVolume](const AzFramework::IVisibilityScene::NodeData& nodeData) + { + m_rewoundEntities.reserve(m_rewoundEntities.size() + nodeData.m_entries.size()); + for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) + { + if (visEntry->m_typeFlags & AzFramework::VisibilityEntry::TypeFlags::TYPE_Entity) + { + AZ::Entity* entity = static_cast(visEntry->m_userData); + NetworkEntityHandle entityHandle(entity, networkEntityTracker); + if (entityHandle.GetNetBindComponent() != nullptr) + { + const AZ::Aabb currentBounds = entityBoundsUnion->GetEntityWorldBoundsUnion(entity->GetId()); + const AZ::Vector3 currentCenter = currentBounds.GetCenter(); + NetworkTransformComponent* networkTransform = entity->template FindComponent(); + if (debugDisplay) + { + debugDisplay->SetColor(AZ::Colors::White); + debugDisplay->DrawWireBox(currentBounds.GetMin(), currentBounds.GetMax()); + } + +<<<<<<< Updated upstream + if (AZ::ShapeIntersection::Overlaps(rewoundAabb, expandedVolume)) // Validate the rewound aabb intersects our rewind volume + { + m_rewoundEntities.push_back(entityHandle); + entityHandle.GetNetBindComponent()->NotifySyncRewindState(); +======= + if (networkTransform != nullptr) + { + // Get the rewound position for target host frame ID plus the one preceding it for potential lerp + AZ::Vector3 rewindCenter = networkTransform->GetTranslation(); + const AZ::Vector3 rewindCenterPrevious = networkTransform->GetTranslationPrevious(); + const float blendFactor = GetNetworkTime()->GetHostBlendFactor(); + if (!AZ::IsClose(blendFactor, 1.0f) && !rewindCenter.IsClose(rewindCenterPrevious)) + { + // If we have a blend factor, lerp the translation for accuracy + rewindCenter = rewindCenterPrevious.Lerp(rewindCenter, blendFactor); + } + const AZ::Vector3 rewindOffset = rewindCenter - currentCenter; // Compute offset between rewound and current positions + const AZ::Aabb rewoundAabb = currentBounds.GetTranslated(rewindOffset); // Apply offset to the entity aabb + if (debugDisplay) + { + debugDisplay->SetColor(AZ::Colors::Grey); + debugDisplay->DrawWireBox(rewoundAabb.GetMin(), rewoundAabb.GetMax()); + } + + if (AZ::ShapeIntersection::Overlaps(rewoundAabb, rewindVolume)) // Validate the rewound aabb intersects our rewind volume + { + m_rewoundEntities.push_back(entityHandle); + entityHandle.GetNetBindComponent()->NotifySyncRewindState(); + } +>>>>>>> Stashed changes + } + } + } + } + }); + } + + void NetworkTime::ClearRewoundEntities() + { + AZ_Assert(!IsTimeRewound(), "Cannot clear rewound entity state while still within scoped rewind"); + + for (NetworkEntityHandle entityHandle : m_rewoundEntities) + { + if (NetBindComponent* netBindComponent = entityHandle.GetNetBindComponent()) + { + netBindComponent->NotifySyncRewindState(); + } + } + m_rewoundEntities.clear(); + } +} From 1adfd4e3f9b8a3062c424dbe354572af427fc8c5 Mon Sep 17 00:00:00 2001 From: puvvadar Date: Thu, 10 Feb 2022 14:24:00 -0800 Subject: [PATCH 058/133] Delete merge artifact that snuck in Signed-off-by: puvvadar --- .../Source/NetworkTime/NetworkTime.cpp.orig | 187 ------------------ 1 file changed, 187 deletions(-) delete mode 100644 Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp.orig diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp.orig b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp.orig deleted file mode 100644 index 26d53a50e1..0000000000 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp.orig +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Multiplayer -{ - AZ_CVAR(float, sv_RewindVolumeExtrudeDistance, 50.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "The amount to increase rewind volume checks to account for fast moving entities"); - AZ_CVAR(bool, bg_RewindDebugDraw, false, nullptr, AZ::ConsoleFunctorFlags::Null, "If true enables debug draw of rewind operations"); - - NetworkTime::NetworkTime() - { - AZ::Interface::Register(this); - } - - NetworkTime::~NetworkTime() - { - AZ::Interface::Unregister(this); - } - - bool NetworkTime::IsTimeRewound() const - { - return m_rewindingConnectionId != AzNetworking::InvalidConnectionId; - } - - HostFrameId NetworkTime::GetHostFrameId() const - { - return m_hostFrameId; - } - - HostFrameId NetworkTime::GetUnalteredHostFrameId() const - { - return m_unalteredFrameId; - } - - void NetworkTime::IncrementHostFrameId() - { - AZ_Assert(!IsTimeRewound(), "Incrementing the global application frameId is unsupported under a rewound time scope"); - ++m_unalteredFrameId; - m_hostFrameId = m_unalteredFrameId; - } - - AZ::TimeMs NetworkTime::GetHostTimeMs() const - { - return m_hostTimeMs; - } - - float NetworkTime::GetHostBlendFactor() const - { - return m_hostBlendFactor; - } - - AzNetworking::ConnectionId NetworkTime::GetRewindingConnectionId() const - { - return m_rewindingConnectionId; - } - - void NetworkTime::ForceSetTime(HostFrameId frameId, AZ::TimeMs timeMs) - { - AZ_Assert(!IsTimeRewound(), "Forcibly setting network time is unsupported under a rewound time scope"); - m_unalteredFrameId = frameId; - m_hostFrameId = frameId; - m_hostTimeMs = timeMs; - m_rewindingConnectionId = AzNetworking::InvalidConnectionId; - } - - void NetworkTime::AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, float blendFactor, AzNetworking::ConnectionId rewindConnectionId) - { - m_hostFrameId = frameId; - m_hostTimeMs = timeMs; - m_hostBlendFactor = blendFactor; - m_rewindingConnectionId = rewindConnectionId; - } - - void NetworkTime::SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) - { - if (!IsTimeRewound()) - { - // If we're not inside a rewind scope then reset any rewound state and exit - ClearRewoundEntities(); - return; - } - - // Since the vis system doesn't support rewound queries, first query with an expanded volume to catch any fast moving entities - const AZ::Aabb expandedVolume = rewindVolume.GetExpanded(AZ::Vector3(sv_RewindVolumeExtrudeDistance)); - - AzFramework::DebugDisplayRequests* debugDisplay = nullptr; - if (bg_RewindDebugDraw) - { - AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; - AzFramework::DebugDisplayRequestBus::Bind(debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); - debugDisplay = AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus); - } - - if (debugDisplay) - { - debugDisplay->SetColor(AZ::Colors::Red); - debugDisplay->DrawWireBox(expandedVolume.GetMin(), expandedVolume.GetMax()); - } - - NetworkEntityTracker* networkEntityTracker = GetNetworkEntityTracker(); - AzFramework::IEntityBoundsUnion* entityBoundsUnion = AZ::Interface::Get(); - AZ::Interface::Get()->GetDefaultVisibilityScene()->Enumerate(expandedVolume, - [this, debugDisplay, networkEntityTracker, entityBoundsUnion, expandedVolume](const AzFramework::IVisibilityScene::NodeData& nodeData) - { - m_rewoundEntities.reserve(m_rewoundEntities.size() + nodeData.m_entries.size()); - for (AzFramework::VisibilityEntry* visEntry : nodeData.m_entries) - { - if (visEntry->m_typeFlags & AzFramework::VisibilityEntry::TypeFlags::TYPE_Entity) - { - AZ::Entity* entity = static_cast(visEntry->m_userData); - NetworkEntityHandle entityHandle(entity, networkEntityTracker); - if (entityHandle.GetNetBindComponent() != nullptr) - { - const AZ::Aabb currentBounds = entityBoundsUnion->GetEntityWorldBoundsUnion(entity->GetId()); - const AZ::Vector3 currentCenter = currentBounds.GetCenter(); - NetworkTransformComponent* networkTransform = entity->template FindComponent(); - if (debugDisplay) - { - debugDisplay->SetColor(AZ::Colors::White); - debugDisplay->DrawWireBox(currentBounds.GetMin(), currentBounds.GetMax()); - } - -<<<<<<< Updated upstream - if (AZ::ShapeIntersection::Overlaps(rewoundAabb, expandedVolume)) // Validate the rewound aabb intersects our rewind volume - { - m_rewoundEntities.push_back(entityHandle); - entityHandle.GetNetBindComponent()->NotifySyncRewindState(); -======= - if (networkTransform != nullptr) - { - // Get the rewound position for target host frame ID plus the one preceding it for potential lerp - AZ::Vector3 rewindCenter = networkTransform->GetTranslation(); - const AZ::Vector3 rewindCenterPrevious = networkTransform->GetTranslationPrevious(); - const float blendFactor = GetNetworkTime()->GetHostBlendFactor(); - if (!AZ::IsClose(blendFactor, 1.0f) && !rewindCenter.IsClose(rewindCenterPrevious)) - { - // If we have a blend factor, lerp the translation for accuracy - rewindCenter = rewindCenterPrevious.Lerp(rewindCenter, blendFactor); - } - const AZ::Vector3 rewindOffset = rewindCenter - currentCenter; // Compute offset between rewound and current positions - const AZ::Aabb rewoundAabb = currentBounds.GetTranslated(rewindOffset); // Apply offset to the entity aabb - if (debugDisplay) - { - debugDisplay->SetColor(AZ::Colors::Grey); - debugDisplay->DrawWireBox(rewoundAabb.GetMin(), rewoundAabb.GetMax()); - } - - if (AZ::ShapeIntersection::Overlaps(rewoundAabb, rewindVolume)) // Validate the rewound aabb intersects our rewind volume - { - m_rewoundEntities.push_back(entityHandle); - entityHandle.GetNetBindComponent()->NotifySyncRewindState(); - } ->>>>>>> Stashed changes - } - } - } - } - }); - } - - void NetworkTime::ClearRewoundEntities() - { - AZ_Assert(!IsTimeRewound(), "Cannot clear rewound entity state while still within scoped rewind"); - - for (NetworkEntityHandle entityHandle : m_rewoundEntities) - { - if (NetBindComponent* netBindComponent = entityHandle.GetNetBindComponent()) - { - netBindComponent->NotifySyncRewindState(); - } - } - m_rewoundEntities.clear(); - } -} From cff6fb97afe497647749ae6e9d82e010b0138089 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 12:49:41 -0800 Subject: [PATCH 059/133] Fix "expression result unused" warning This macro was expecting that parenthesis used in the macro would be removed during macro expansion, when they are not removed. The result was a function call like this: ```cpp AZ_Assert(g_SymGetSearchPath != 0, ("Can not load %s function!","SymGetSearchPath")); ``` The parenthesis cause the contents of the parenthsis to be evaluated first, and the result is an expression using the comma operator. The comma operator evaluates the left expression, discards the result, then evaluates the right expression, and returns that. So the above dropping the message, and just leaving: ```cpp AZ_Assert(g_SymGetSearchPath != 0, "SymGetSearchPath"); ``` Signed-off-by: Chris Burel --- .../Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index 90362a3ce8..688db347da 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -140,7 +140,7 @@ namespace AZ { SymRegisterCallback64_t g_SymRegisterCallback64; HMODULE g_dbgHelpDll; -#define LOAD_FUNCTION(A) { g_##A = (A##_t)GetProcAddress(g_dbgHelpDll, #A); AZ_Assert(g_##A != 0, ("Can not load %s function!",#A)); } +#define LOAD_FUNCTION(A) { g_##A = (A##_t)GetProcAddress(g_dbgHelpDll, #A); AZ_Assert(g_##A != 0, "Can not load %s function!",#A); } using namespace AZ::Debug; From b44c362af00ed2640be199658b94040572eb585e Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 12:50:56 -0800 Subject: [PATCH 060/133] Fix comparing an array in a conditional, which is always true Instead, check the intent of the original code, if the `szImg` string is not empty. Signed-off-by: Chris Burel --- .../Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index 688db347da..3969a1bf13 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -596,7 +596,7 @@ namespace AZ { result = GetLastError(); } ULONGLONG fileVersion = 0; - if (szImg != NULL) + if (szImg[0]) // !szImg.empty() { // try to retrieve the file-version: VS_FIXEDFILEINFO* fInfo = NULL; From 024cbdd2cd50a6ef3df5f5ce4726f0d58532fa5f Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 12:51:46 -0800 Subject: [PATCH 061/133] Remove unused `azSmyType` variable There's a lot of work done to set the value of this variable, but nothing read from it. Signed-off-by: Chris Burel --- .../AzCore/Debug/StackTracer_Windows.cpp | 37 ------------------- 1 file changed, 37 deletions(-) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index 3969a1bf13..a3f8b1e349 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -624,43 +624,6 @@ namespace AZ { } } - // Retrive some additional-infos about the module - IMAGEHLP_MODULE64 Module; - const char* szSymType = "-unknown-"; - if (GetModuleInfo(hProcess, baseAddr, &Module) != FALSE) - { - switch (Module.SymType) - { - case SymNone: - szSymType = "-nosymbols-"; - break; - case SymCoff: - szSymType = "COFF"; - break; - case SymCv: - szSymType = "CV"; - break; - case SymPdb: - szSymType = "PDB"; - break; - case SymExport: - szSymType = "-exported-"; - break; - case SymDeferred: - szSymType = "-deferred-"; - break; - case SymSym: - szSymType = "SYM"; - break; - case 8: //SymVirtual: - szSymType = "Virtual"; - break; - case 9: // SymDia: - szSymType = "DIA"; - break; - } - } - // find insert position if (g_moduleInfo.size() < g_moduleInfo.capacity()) { From 36487c15886dba229c295a9cb2fff6bea98ec1c5 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 12:57:09 -0800 Subject: [PATCH 062/133] Fix alignment of `CONTEXT` variable The previous code had the `alignas()` in the wrong place, it needs to be left of the typename. Furthermore, `CONTEXT` has a default alignment of 16, so using `alignas(8)` underaligns. Signed-off-by: Chris Burel --- .../Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp index a3f8b1e349..0d3cc7e032 100644 --- a/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp +++ b/Code/Framework/AzCore/Platform/Windows/AzCore/Debug/StackTracer_Windows.cpp @@ -1036,7 +1036,7 @@ cleanup: } HANDLE hThread = nativeThread; - CONTEXT alignas(8) context; // Without this alignment the function randomly crashes in release. + alignas(alignof(CONTEXT)) CONTEXT context; // Without this alignment the function randomly crashes in release. context.ContextFlags = CONTEXT_ALL; GetThreadContext(hThread, &context); From 664403c5de6e995ab1de4d23e4041b36be8c2ae7 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:00:49 -0800 Subject: [PATCH 063/133] Mark benchmark state variables in for loops as unused in benchmarks Signed-off-by: Chris Burel --- Code/Framework/AzCore/Tests/AZStd/String.cpp | 36 ++-- .../AzCore/Tests/DOM/DomJsonBenchmarks.cpp | 18 +- .../AzCore/Tests/DOM/DomPathBenchmarks.cpp | 10 +- .../AzCore/Tests/DOM/DomValueBenchmarks.cpp | 18 +- .../AzCore/Tests/IO/Path/PathTests.cpp | 8 +- Code/Framework/AzCore/Tests/Jobs.cpp | 48 +++--- Code/Framework/AzCore/Tests/Math/CrcTests.cpp | 2 +- .../Tests/Math/FrustumPerformanceTests.cpp | 4 +- .../Tests/Math/Matrix3x3PerformanceTests.cpp | 96 +++++------ .../Tests/Math/Matrix3x4PerformanceTests.cpp | 158 +++++++++--------- .../Tests/Math/Matrix4x4PerformanceTests.cpp | 82 ++++----- .../AzCore/Tests/Math/ObbPerformanceTests.cpp | 38 ++--- .../Tests/Math/PlanePerformanceTests.cpp | 40 ++--- .../Tests/Math/QuaternionPerformanceTests.cpp | 108 ++++++------ .../ShapeIntersectionPerformanceTests.cpp | 10 +- .../Tests/Math/TransformPerformanceTests.cpp | 86 +++++----- .../Tests/Math/Vector2PerformanceTests.cpp | 86 +++++----- .../Tests/Math/Vector3PerformanceTests.cpp | 90 +++++----- .../Tests/Math/Vector4PerformanceTests.cpp | 86 +++++----- .../Tests/Memory/AllocatorBenchmarks.cpp | 6 +- .../IO/Streamer/StorageDriveTests_Windows.cpp | 2 +- Code/Framework/AzCore/Tests/TaskTests.cpp | 6 +- .../Tests/OctreePerformanceTests.cpp | 32 ++-- .../Benchmark/PrefabCreateBenchmarks.cpp | 8 +- .../Benchmark/PrefabInstantiateBenchmarks.cpp | 2 +- .../Prefab/Benchmark/PrefabLoadBenchmarks.cpp | 2 +- .../PrefabUpdateInstancesBenchmarks.cpp | 8 +- .../Spawnable/SpawnAllEntitiesBenchmarks.cpp | 6 +- .../Benchmark/SpawnableCreateBenchmarks.cpp | 2 +- .../Code/Tests/GradientSignalTestHelpers.cpp | 8 +- .../Benchmarks/PhysXCharactersBenchmarks.cpp | 6 +- .../PhysXCharactersRagdollBenchmarks.cpp | 4 +- .../Benchmarks/PhysXGenericBenchmarks.cpp | 2 +- .../Tests/Benchmarks/PhysXJointBenchmarks.cpp | 6 +- .../Benchmarks/PhysXRigidBodyBenchmarks.cpp | 6 +- .../Benchmarks/PhysXSceneQueryBenchmarks.cpp | 6 +- .../Code/Tests/SurfaceDataBenchmarks.cpp | 6 +- .../Code/Tests/TerrainSystemBenchmarks.cpp | 2 +- 38 files changed, 572 insertions(+), 572 deletions(-) diff --git a/Code/Framework/AzCore/Tests/AZStd/String.cpp b/Code/Framework/AzCore/Tests/AZStd/String.cpp index 50450a898c..f53a90047f 100644 --- a/Code/Framework/AzCore/Tests/AZStd/String.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/String.cpp @@ -2537,7 +2537,7 @@ namespace Benchmark { AZStd::string test1{ "foo bar"}; AZStd::string test2{ "bar foo" }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { SwapStringViaPointerSizedSwaps(test1, test2); } @@ -2547,7 +2547,7 @@ namespace Benchmark { AZStd::string test1{ "The brown quick wolf jumped over the hyperactive cat" }; AZStd::string test2{ "The quick brown fox jumped over the lazy dog" }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { SwapStringViaPointerSizedSwaps(test1, test2); } @@ -2557,7 +2557,7 @@ namespace Benchmark { AZStd::string test1{ "foo bar" }; AZStd::string test2{ "bar foo" }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { SwapStringViaMemcpy(test1, test2); } @@ -2567,7 +2567,7 @@ namespace Benchmark { AZStd::string test1{ "The brown quick wolf jumped over the hyperactive cat" }; AZStd::string test2{ "The quick brown fox jumped over the lazy dog" }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { SwapStringViaMemcpy(test1, test2); } @@ -2584,7 +2584,7 @@ namespace Benchmark AZStd::string sourceString(state.range(0), 'a'); const char* sourceAddress = sourceString.c_str(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::string assignString; assignString.assign(sourceAddress); @@ -2600,7 +2600,7 @@ namespace Benchmark const char* sourceAddress = sourceString.c_str(); const size_t sourceSize = sourceString.size(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::string assignString; assignString.assign(sourceAddress, sourceSize); @@ -2616,7 +2616,7 @@ namespace Benchmark auto sourceBegin = sourceString.begin(); auto sourceEnd = sourceString.end(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::string assignString; assignString.assign(sourceBegin, sourceEnd); @@ -2631,7 +2631,7 @@ namespace Benchmark AZStd::string sourceString(state.range(0), 'a'); AZStd::string_view sourceView(sourceString); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::string assignString; assignString.assign(sourceView); @@ -2645,7 +2645,7 @@ namespace Benchmark { AZStd::string sourceString(state.range(0), 'a'); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::string assignString; assignString.assign(sourceString); @@ -2659,7 +2659,7 @@ namespace Benchmark { AZStd::string sourceString(state.range(0), 'a'); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::string assignString; assignString.assign(AZStd::move(sourceString)); @@ -2671,7 +2671,7 @@ namespace Benchmark BENCHMARK_TEMPLATE_DEFINE_F(StringTemplateBenchmarkFixture, BM_StringAssignFromSingleCharacter, AZStd::string)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::string assignString; assignString.assign(state.range(0), 'a'); @@ -2689,7 +2689,7 @@ namespace Benchmark AZStd::fixed_string<1024> sourceString(state.range(0), 'a'); const char* sourceAddress = sourceString.c_str(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::fixed_string<1024> assignString; assignString.assign(sourceAddress); @@ -2705,7 +2705,7 @@ namespace Benchmark const char* sourceAddress = sourceString.c_str(); const size_t sourceSize = sourceString.size(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::fixed_string<1024> assignString; assignString.assign(sourceAddress, sourceSize); @@ -2721,7 +2721,7 @@ namespace Benchmark auto sourceBegin = sourceString.begin(); auto sourceEnd = sourceString.end(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::fixed_string<1024> assignString; assignString.assign(sourceBegin, sourceEnd); @@ -2736,7 +2736,7 @@ namespace Benchmark AZStd::fixed_string<1024> sourceString(state.range(0), 'a'); AZStd::string_view sourceView(sourceString); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::fixed_string<1024> assignString; assignString.assign(sourceView); @@ -2750,7 +2750,7 @@ namespace Benchmark { AZStd::fixed_string<1024> sourceString(state.range(0), 'a'); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::fixed_string<1024> assignString; assignString.assign(sourceString); @@ -2764,7 +2764,7 @@ namespace Benchmark { AZStd::fixed_string<1024> sourceString(state.range(0), 'a'); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::fixed_string<1024> assignString; assignString.assign(AZStd::move(sourceString)); @@ -2776,7 +2776,7 @@ namespace Benchmark BENCHMARK_TEMPLATE_DEFINE_F(StringTemplateBenchmarkFixture, BM_FixedStringAssignFromSingleCharacter, AZStd::fixed_string<1024>)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::fixed_string<1024> assignString; assignString.assign(state.range(0), 'a'); diff --git a/Code/Framework/AzCore/Tests/DOM/DomJsonBenchmarks.cpp b/Code/Framework/AzCore/Tests/DOM/DomJsonBenchmarks.cpp index f84b60af07..65bd609e37 100644 --- a/Code/Framework/AzCore/Tests/DOM/DomJsonBenchmarks.cpp +++ b/Code/Framework/AzCore/Tests/DOM/DomJsonBenchmarks.cpp @@ -29,7 +29,7 @@ namespace AZ::Dom::Benchmark AZ::Dom::JsonBackend backend; AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); AZStd::string payloadCopy = serializedPayload; @@ -53,7 +53,7 @@ namespace AZ::Dom::Benchmark AZ::Dom::JsonBackend backend; AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); AZStd::string payloadCopy = serializedPayload; @@ -77,7 +77,7 @@ namespace AZ::Dom::Benchmark AZ::Dom::JsonBackend backend; AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { auto result = AZ::Dom::Json::WriteToRapidJsonDocument( [&](AZ::Dom::Visitor& visitor) @@ -97,7 +97,7 @@ namespace AZ::Dom::Benchmark AZ::Dom::JsonBackend backend; AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { auto result = AZ::Dom::Utils::WriteToValue( [&](AZ::Dom::Visitor& visitor) @@ -117,7 +117,7 @@ namespace AZ::Dom::Benchmark AZ::Dom::JsonBackend backend; AZStd::string serializedPayload = GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { auto result = AZ::JsonSerializationUtils::ReadJsonString(serializedPayload); @@ -130,7 +130,7 @@ namespace AZ::Dom::Benchmark BENCHMARK_DEFINE_F(DomJsonBenchmark, RapidjsonMakeComplexObject)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { TakeAndDiscardWithoutTimingDtor(GenerateDomJsonBenchmarkPayload(state.range(0), state.range(1)), state); } @@ -152,7 +152,7 @@ namespace AZ::Dom::Benchmark document.GetAllocator()); } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (const AZStd::string& key : keys) { @@ -168,7 +168,7 @@ namespace AZ::Dom::Benchmark { rapidjson::Document original = GenerateDomJsonBenchmarkDocument(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { rapidjson::Document copy; copy.CopyFrom(original, copy.GetAllocator(), true); @@ -184,7 +184,7 @@ namespace AZ::Dom::Benchmark { rapidjson::Document original = GenerateDomJsonBenchmarkDocument(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { rapidjson::Document copy; copy.CopyFrom(original, copy.GetAllocator(), true); diff --git a/Code/Framework/AzCore/Tests/DOM/DomPathBenchmarks.cpp b/Code/Framework/AzCore/Tests/DOM/DomPathBenchmarks.cpp index 4741900aa1..10c5fa1394 100644 --- a/Code/Framework/AzCore/Tests/DOM/DomPathBenchmarks.cpp +++ b/Code/Framework/AzCore/Tests/DOM/DomPathBenchmarks.cpp @@ -20,7 +20,7 @@ namespace AZ::Dom::Benchmark PathEntry end; end.SetEndOfArray(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { Path p; p /= entry1; @@ -40,7 +40,7 @@ namespace AZ::Dom::Benchmark PathEntry end; end.SetEndOfArray(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { Path p = Path() / entry1 / entry2 / 0 / end; } @@ -55,7 +55,7 @@ namespace AZ::Dom::Benchmark AZStd::string s; s.resize_no_construct(p.GetStringLength()); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { p.GetStringLength(); p.FormatString(s.data(), s.size()); @@ -69,7 +69,7 @@ namespace AZ::Dom::Benchmark { AZStd::string pathString = "/path/with/multiple/0/different/components/including-long-strings-like-this/65536/999/-"; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { Path p(pathString); benchmark::DoNotOptimize(p); @@ -86,7 +86,7 @@ namespace AZ::Dom::Benchmark PathEntry endOfArray; endOfArray.SetEndOfArray(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { name.IsEndOfArray(); index.IsEndOfArray(); diff --git a/Code/Framework/AzCore/Tests/DOM/DomValueBenchmarks.cpp b/Code/Framework/AzCore/Tests/DOM/DomValueBenchmarks.cpp index 69d99eb12b..b73306f516 100644 --- a/Code/Framework/AzCore/Tests/DOM/DomValueBenchmarks.cpp +++ b/Code/Framework/AzCore/Tests/DOM/DomValueBenchmarks.cpp @@ -29,7 +29,7 @@ namespace AZ::Dom::Benchmark Value doubleValue(4.0); Value stringValue("foo", true); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { (intValue.GetType()); (boolValue.GetType()); @@ -118,7 +118,7 @@ namespace AZ::Dom::Benchmark value.GetInternalValue()); }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { (getTypeViaVisit(intValue)); (getTypeViaVisit(boolValue)); @@ -136,7 +136,7 @@ namespace AZ::Dom::Benchmark BENCHMARK_DEFINE_F(DomValueBenchmark, AzDomValueMakeComplexObject)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { TakeAndDiscardWithoutTimingDtor(GenerateDomBenchmarkPayload(state.range(0), state.range(1)), state); } @@ -149,7 +149,7 @@ namespace AZ::Dom::Benchmark { Value original = GenerateDomBenchmarkPayload(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { Value copy = original; benchmark::DoNotOptimize(copy); @@ -163,7 +163,7 @@ namespace AZ::Dom::Benchmark { Value original = GenerateDomBenchmarkPayload(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { Value copy = original; copy["entries"]["Key0"].ArrayPushBack(Value(42)); @@ -178,7 +178,7 @@ namespace AZ::Dom::Benchmark { Value original = GenerateDomBenchmarkPayload(state.range(0), state.range(1)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { Value copy = Utils::DeepCopy(original); TakeAndDiscardWithoutTimingDtor(AZStd::move(copy), state); @@ -199,7 +199,7 @@ namespace AZ::Dom::Benchmark value[key] = i; } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (const AZ::Name& key : keys) { @@ -222,7 +222,7 @@ namespace AZ::Dom::Benchmark value[key] = i; } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (const AZStd::string& key : keys) { @@ -245,7 +245,7 @@ namespace AZ::Dom::Benchmark value[key] = i; } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (const AZStd::string& key : keys) { diff --git a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp index cf239a0821..91620ae918 100644 --- a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp +++ b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp @@ -966,7 +966,7 @@ namespace Benchmark BENCHMARK_F(PathBenchmarkFixture, BM_PathAppendFixedPath)(benchmark::State& state) { AZ::IO::FixedMaxPath m_testPath{ "." }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (const auto& appendPath : m_appendPaths) { @@ -977,7 +977,7 @@ namespace Benchmark BENCHMARK_F(PathBenchmarkFixture, BM_PathAppendAllocatingPath)(benchmark::State& state) { AZ::IO::Path m_testPath{ "." }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (const auto& appendPath : m_appendPaths) { @@ -989,7 +989,7 @@ namespace Benchmark BENCHMARK_F(PathBenchmarkFixture, BM_StringFuncPathJoinFixedString)(benchmark::State& state) { AZStd::string m_testPath{ "." }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (const auto& appendPath : m_appendPaths) { @@ -1000,7 +1000,7 @@ namespace Benchmark BENCHMARK_F(PathBenchmarkFixture, BM_StringFuncPathJoinAZStdString)(benchmark::State& state) { AZStd::string m_testPath{ "." }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (const auto& appendPath : m_appendPaths) { diff --git a/Code/Framework/AzCore/Tests/Jobs.cpp b/Code/Framework/AzCore/Tests/Jobs.cpp index 20c960535d..afe2d72acf 100644 --- a/Code/Framework/AzCore/Tests/Jobs.cpp +++ b/Code/Framework/AzCore/Tests/Jobs.cpp @@ -1741,7 +1741,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunSmallNumberOfLightWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(SMALL_NUMBER_OF_JOBS, LIGHT_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1749,7 +1749,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunMediumNumberOfLightWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(MEDIUM_NUMBER_OF_JOBS, LIGHT_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1757,7 +1757,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunLargeNumberOfLightWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(LARGE_NUMBER_OF_JOBS, LIGHT_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1765,7 +1765,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunSmallNumberOfMediumWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(SMALL_NUMBER_OF_JOBS, MEDIUM_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1773,7 +1773,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunMediumNumberOfMediumWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(MEDIUM_NUMBER_OF_JOBS, MEDIUM_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1781,7 +1781,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunLargeNumberOfMediumWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(LARGE_NUMBER_OF_JOBS, MEDIUM_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1789,7 +1789,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunSmallNumberOfHeavyWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(SMALL_NUMBER_OF_JOBS, HEAVY_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1797,7 +1797,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunMediumNumberOfHeavyWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(MEDIUM_NUMBER_OF_JOBS, HEAVY_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1805,7 +1805,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunLargeNumberOfHeavyWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithDefaultPriority(LARGE_NUMBER_OF_JOBS, HEAVY_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1813,7 +1813,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunSmallNumberOfRandomWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomDepthAndDefaultPriority(SMALL_NUMBER_OF_JOBS); } @@ -1821,7 +1821,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunMediumNumberOfRandomWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomDepthAndDefaultPriority(MEDIUM_NUMBER_OF_JOBS); } @@ -1829,7 +1829,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunLargeNumberOfRandomWeightJobsWithDefaultPriority)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomDepthAndDefaultPriority(LARGE_NUMBER_OF_JOBS); } @@ -1837,7 +1837,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunSmallNumberOfLightWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(SMALL_NUMBER_OF_JOBS, LIGHT_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1845,7 +1845,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunMediumNumberOfLightWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(MEDIUM_NUMBER_OF_JOBS, LIGHT_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1853,7 +1853,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunLargeNumberOfLightWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(LARGE_NUMBER_OF_JOBS, LIGHT_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1861,7 +1861,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunSmallNumberOfMediumWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(SMALL_NUMBER_OF_JOBS, MEDIUM_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1869,7 +1869,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunMediumNumberOfMediumWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(MEDIUM_NUMBER_OF_JOBS, MEDIUM_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1877,7 +1877,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunLargeNumberOfMediumWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(LARGE_NUMBER_OF_JOBS, MEDIUM_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1885,7 +1885,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunSmallNumberOfHeavyWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(SMALL_NUMBER_OF_JOBS, HEAVY_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1893,7 +1893,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunMediumNumberOfHeavyWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(MEDIUM_NUMBER_OF_JOBS, HEAVY_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1901,7 +1901,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunLargeNumberOfHeavyWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomPriority(LARGE_NUMBER_OF_JOBS, HEAVY_WEIGHT_JOB_CALCULATE_PI_DEPTH); } @@ -1909,7 +1909,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunSmallNumberOfRandomWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomDepthAndRandomPriority(SMALL_NUMBER_OF_JOBS); } @@ -1917,7 +1917,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunMediumNumberOfRandomWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomDepthAndRandomPriority(MEDIUM_NUMBER_OF_JOBS); } @@ -1925,7 +1925,7 @@ namespace Benchmark BENCHMARK_F(JobBenchmarkFixture, RunLargeNumberOfRandomWeightJobsWithRandomPriorities)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { RunMultipleCalculatePiJobsWithRandomDepthAndRandomPriority(LARGE_NUMBER_OF_JOBS); } diff --git a/Code/Framework/AzCore/Tests/Math/CrcTests.cpp b/Code/Framework/AzCore/Tests/Math/CrcTests.cpp index 0255c1ad6d..f152744486 100644 --- a/Code/Framework/AzCore/Tests/Math/CrcTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/CrcTests.cpp @@ -54,7 +54,7 @@ namespace Benchmark { // Runtime performance is not actually being measured by this test. // This function only exist to calculate AZ::Crc32 values at compile time - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { [[maybe_unused]] constexpr auto resultArray = Crc32Internal::GenerateTestCrc32Values(); } diff --git a/Code/Framework/AzCore/Tests/Math/FrustumPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/FrustumPerformanceTests.cpp index e26d896e5a..7e753fffb9 100644 --- a/Code/Framework/AzCore/Tests/Math/FrustumPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/FrustumPerformanceTests.cpp @@ -63,7 +63,7 @@ namespace Benchmark BENCHMARK_F(BM_MathFrustum, SphereIntersect)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& data : m_dataArray) { @@ -75,7 +75,7 @@ namespace Benchmark BENCHMARK_F(BM_MathFrustum, AabbIntersect)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& data : m_dataArray) { diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x3PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x3PerformanceTests.cpp index 918673d475..c6fe9c8178 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x3PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x3PerformanceTests.cpp @@ -68,7 +68,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateIdentity)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -80,7 +80,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateZero)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -92,7 +92,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetRowX3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -108,7 +108,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetColumnX3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -124,7 +124,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateFromValue)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -136,7 +136,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateFromRowMajorFloat9)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -148,7 +148,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateFromColumnMajorFloat9)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -162,7 +162,7 @@ namespace Benchmark { float storeValues[9]; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -176,7 +176,7 @@ namespace Benchmark { float storeValues[9]; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -188,7 +188,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateRotationX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -200,7 +200,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateRotationY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -212,7 +212,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateRotationZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -224,7 +224,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateFromTransform)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -236,7 +236,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateFromMatrix4x4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -248,7 +248,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateFromQuaternion)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -260,7 +260,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -272,7 +272,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateDiagonal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -284,7 +284,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, CreateCrossProduct)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -296,7 +296,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetElement)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -308,7 +308,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, SetElement)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -321,7 +321,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, SetRowX3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -336,7 +336,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, SetColumnX3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -351,7 +351,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetBasisX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -363,7 +363,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetBasisY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -375,7 +375,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetBasisZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -387,7 +387,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, OperatorAssign)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -399,7 +399,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, OperatorMultiply)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -411,7 +411,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, TransposedMultiply)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -423,7 +423,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, MultiplyVector)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -435,7 +435,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, OperatorSum)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -447,7 +447,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, OperatorDifference)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -459,7 +459,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, OperatorMultiplyScalar)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -471,7 +471,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, OperatorDivideScalar)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -483,7 +483,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, Transpose)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -494,7 +494,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetTranspose)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -506,7 +506,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, RetrieveScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -518,7 +518,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, ExtractScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -530,7 +530,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, MultiplyByScaleX2)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -542,7 +542,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetPolarDecomposition)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -557,7 +557,7 @@ namespace Benchmark AZ::Matrix3x3 orthogonalOut; AZ::Matrix3x3 symmetricOut; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -568,7 +568,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetInverseFast)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -580,7 +580,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetInverseFull)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -592,7 +592,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, Orthogonalize)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -603,7 +603,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetOrthogonalized)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -615,7 +615,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, IsOrthogonal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -627,7 +627,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetDiagonal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -639,7 +639,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetDeterminant)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -651,7 +651,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x3, GetAdjugate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x4PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x4PerformanceTests.cpp index 63ddefdd2c..fd942056a2 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x4PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x4PerformanceTests.cpp @@ -86,7 +86,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateIdentity)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -98,7 +98,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateZero)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -110,7 +110,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromValue)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -122,7 +122,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromRowMajorFloat12)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -134,7 +134,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromRows)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -146,7 +146,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromColumnMajorFloat12)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -158,7 +158,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromColumns)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -170,7 +170,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromColumnMajorFloat16)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -182,7 +182,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateRotationX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -194,7 +194,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateRotationY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -206,7 +206,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateRotationZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -218,7 +218,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromQuaternion)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -230,7 +230,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromQuaternionAndTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -242,7 +242,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromMatrix3x3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -254,7 +254,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromMatrix3x3AndTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -266,7 +266,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromTransform)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -278,7 +278,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -290,7 +290,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateFromTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -302,7 +302,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, CreateLookAt)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -316,7 +316,7 @@ namespace Benchmark { float testFloats[12]; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -330,7 +330,7 @@ namespace Benchmark { float testFloats[12]; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -344,7 +344,7 @@ namespace Benchmark { float testFloats[16]; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -356,7 +356,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetElement)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -368,7 +368,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetElement)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -381,7 +381,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetRow)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -393,7 +393,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetRowAsVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -405,7 +405,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetRowWithFloats)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -418,7 +418,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetRowWithVector3AndFloat)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -431,7 +431,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetRowWithVector4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -444,7 +444,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetRows)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -459,7 +459,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetRows)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -472,7 +472,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetColumn)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -484,7 +484,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetColumnWithFloats)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -497,7 +497,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetColumnWithVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -510,7 +510,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetColumns)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -526,7 +526,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetColumns)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -539,7 +539,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetBasisX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -551,7 +551,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetBasisXWithFloats)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -564,7 +564,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetBasisXWithVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -577,7 +577,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetBasisY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -589,7 +589,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetBasisYWithFloats)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -602,7 +602,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetBasisYWithVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -615,7 +615,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetBasisZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -627,7 +627,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetBasisZWithFloats)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -640,7 +640,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetBasisZWithVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -653,7 +653,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -665,7 +665,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetTranslationWithFloats)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -678,7 +678,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetTranslationWithVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -691,7 +691,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetBasisAndTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -707,7 +707,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetBasisAndTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -720,7 +720,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, OperatorMultiplyMatrix3x4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -732,7 +732,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, OperatorMultiplyEqualsMatrix3x4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -745,7 +745,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, TransformPointVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -757,7 +757,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, TransformVectorVector4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -769,7 +769,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, Multiply3x3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -781,7 +781,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetTranspose)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -793,7 +793,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, Transpose)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -806,7 +806,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetTranspose3x3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -818,7 +818,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, Transpose3x3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -831,7 +831,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetInverseFull)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -843,7 +843,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, InvertFull)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -856,7 +856,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetInverseFast)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -868,7 +868,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, InvertFast)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -881,7 +881,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, RetrieveScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -893,7 +893,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, ExtractScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -906,7 +906,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, MultiplyByScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -919,7 +919,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, IsOrthogonal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -931,7 +931,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetOrthogonalized)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -943,7 +943,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, Orthogonalize)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -956,7 +956,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, IsCloseExactAndDifferent)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -971,7 +971,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, OperatorEqualEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -983,7 +983,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, OperatorNotEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -995,7 +995,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetEulerDegrees)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -1007,7 +1007,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetEulerRadians)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -1019,7 +1019,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetFromEulerDegrees)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -1032,7 +1032,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetFromEulerRadians)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -1045,7 +1045,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, SetRotationPartFromQuaternion)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -1058,7 +1058,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, GetDeterminant3x3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -1070,7 +1070,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix3x4, IsFinite)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { diff --git a/Code/Framework/AzCore/Tests/Math/Matrix4x4PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix4x4PerformanceTests.cpp index 21f440c3a1..49a433a7fc 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix4x4PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix4x4PerformanceTests.cpp @@ -64,7 +64,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateIdentity)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -76,7 +76,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateZero)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -88,7 +88,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetRowX4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -106,7 +106,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetColumnX3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -124,7 +124,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateFromValue)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -136,7 +136,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateFromRowMajorFloat16)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -148,7 +148,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateFromColumnMajorFloat9)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -160,7 +160,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateProjection)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -172,7 +172,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateProjectionFov)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -184,7 +184,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateInterpolated)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -198,7 +198,7 @@ namespace Benchmark { float storeValues[16]; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -212,7 +212,7 @@ namespace Benchmark { float storeValues[16]; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -224,7 +224,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateRotationX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -236,7 +236,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateRotationY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -248,7 +248,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateRotationZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -260,7 +260,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateFromQuaternion)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -272,7 +272,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -284,7 +284,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateDiagonal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -296,7 +296,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetElement)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -308,7 +308,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, SetElement)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -321,7 +321,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, SetRowX3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -337,7 +337,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, SetColumnX3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -353,7 +353,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetBasisX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -365,7 +365,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetBasisY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -377,7 +377,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetBasisZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -389,7 +389,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, CreateTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -401,7 +401,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, SetTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -414,7 +414,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -426,7 +426,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, OperatorAssign)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -438,7 +438,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, OperatorMultiply)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -450,7 +450,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, OperatorMultiplyAssign)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -463,7 +463,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, OperatorMultiplyVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -475,7 +475,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, OperatorMultiplyVector4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -487,7 +487,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, TransposedMultiply3x3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -499,7 +499,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, Multiply3x3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -511,7 +511,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, Transpose)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -524,7 +524,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetTranspose)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -536,7 +536,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetInverseFast)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -552,7 +552,7 @@ namespace Benchmark AZ::Matrix4x4 mat = AZ::Matrix4x4::CreateRotationX(1.0f); mat.SetElement(0, 1, 23.1234f); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -564,7 +564,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, GetInverseFull)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -576,7 +576,7 @@ namespace Benchmark BENCHMARK_F(BM_MathMatrix4x4, SetRotationPartFromQuaternion)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { diff --git a/Code/Framework/AzCore/Tests/Math/ObbPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/ObbPerformanceTests.cpp index d1e8ac2225..ac95912035 100644 --- a/Code/Framework/AzCore/Tests/Math/ObbPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/ObbPerformanceTests.cpp @@ -47,7 +47,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, CreateFromPositionRotationAndHalfLengths)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -60,7 +60,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, SetPosition)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -72,7 +72,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetPosition)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -84,7 +84,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetAxisX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -96,7 +96,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetAxisY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -108,7 +108,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetAxisZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -120,7 +120,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetAxisIndex3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -136,7 +136,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, SetHalfLengthX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -148,7 +148,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetHalfLengthX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -160,7 +160,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, SetHalfLengthY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -172,7 +172,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetHalfLengthY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -184,7 +184,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, SetHalfLengthZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -196,7 +196,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetHalfLengthZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -208,7 +208,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, SetHalfLengthIndex3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -222,7 +222,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, GetHalfLengthIndex3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -242,7 +242,7 @@ namespace Benchmark AZ::Vector3 max(120.0f, 300.0f, 50.0f); AZ::Aabb aabb = AZ::Aabb::CreateFromMinMax(min, max); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -256,7 +256,7 @@ namespace Benchmark { AZ::Transform transform = AZ::Transform::CreateRotationY(AZ::DegToRad(90.0f)); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -268,7 +268,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, Equal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { @@ -280,7 +280,7 @@ namespace Benchmark BENCHMARK_F(BM_MathObb, IsFinite)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < numIters; ++i) { diff --git a/Code/Framework/AzCore/Tests/Math/PlanePerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/PlanePerformanceTests.cpp index e066207635..919dc72988 100644 --- a/Code/Framework/AzCore/Tests/Math/PlanePerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/PlanePerformanceTests.cpp @@ -73,7 +73,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, CreateFromNormalAndDistance)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -85,7 +85,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, GetDistance)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -97,7 +97,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, GetNormal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -109,7 +109,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, CreateFromNormalAndPoint)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -128,7 +128,7 @@ namespace Benchmark coeff.push_back(unif(rng)); } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -148,7 +148,7 @@ namespace Benchmark coeff.push_back(unif(rng)); } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -160,7 +160,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, SetVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -179,7 +179,7 @@ namespace Benchmark vecs.push_back(AZ::Vector4(unif(rng), unif(rng), unif(rng), unif(rng))); } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -192,7 +192,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, SetNormal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -205,7 +205,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, SetDistance)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -218,7 +218,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, GetPlaneEquationCoefficients)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -236,7 +236,7 @@ namespace Benchmark trans.push_back(AZ::Transform::CreateRotationY(AZ::DegToRad(unif(rng)))); } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -254,7 +254,7 @@ namespace Benchmark trans.push_back(AZ::Transform::CreateRotationY(AZ::DegToRad(unif(rng)))); } - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -265,7 +265,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, GetPointDist)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -277,7 +277,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, GetProjected)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -291,7 +291,7 @@ namespace Benchmark { AZ::Vector3 rayResult; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -305,7 +305,7 @@ namespace Benchmark { float rayResult; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { @@ -319,7 +319,7 @@ namespace Benchmark { AZ::Vector3 rayResult; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters - 1; ++i) { @@ -333,7 +333,7 @@ namespace Benchmark { float rayResult; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters - 1; ++i) { @@ -345,7 +345,7 @@ namespace Benchmark BENCHMARK_F(BM_MathPlane, IsFinite)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (int i = 0; i < m_numIters; ++i) { diff --git a/Code/Framework/AzCore/Tests/Math/QuaternionPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/QuaternionPerformanceTests.cpp index 486a33ba67..4ef42c3016 100644 --- a/Code/Framework/AzCore/Tests/Math/QuaternionPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/QuaternionPerformanceTests.cpp @@ -68,7 +68,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SplatFloatConstruction)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -80,7 +80,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, NonNormalized4FloatsConstruction)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -92,7 +92,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, CreateFromIdentity)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& quatData : m_quatDataArray) { @@ -104,7 +104,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, CreateZero)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& quatData : m_quatDataArray) { @@ -116,7 +116,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, CreateRotationX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -128,7 +128,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, CreateRotationY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -140,7 +140,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, CreateRotationZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -155,7 +155,7 @@ namespace Benchmark const AZ::Vector3 vec1 = AZ::Vector3(1.0f, 2.0f, 3.0f).GetNormalized(); const AZ::Vector3 vec2 = AZ::Vector3(-2.0f, 7.0f, -1.0f).GetNormalized(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& quatData : m_quatDataArray) { @@ -170,7 +170,7 @@ namespace Benchmark const AZ::Vector3 vec1 = AZ::Vector3(1.0f, 2.0f, 3.0f).GetNormalized(); const AZ::Vector3 vec2 = AZ::Vector3(-1.0f, -2.0f, -3.0f).GetNormalized(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& quatData : m_quatDataArray) { @@ -182,7 +182,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -194,7 +194,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -206,7 +206,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -218,7 +218,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetW)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -230,7 +230,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -243,7 +243,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -256,7 +256,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -269,7 +269,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetW)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -282,7 +282,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetSplat)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -295,7 +295,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetAll)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -310,7 +310,7 @@ namespace Benchmark { AZ::Vector3 vec(5.0f, 6.0f, 7.0f); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& quatData : m_quatDataArray) { @@ -324,7 +324,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetArray)(benchmark::State& state) { const float quatArray[4] = { 5.0f, 6.0f, 7.0f, 8.0f }; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& quatData : m_quatDataArray) { @@ -337,7 +337,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetElements)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -353,7 +353,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetElement)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -374,7 +374,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetConjugate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -386,7 +386,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetInverseFast)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -398,7 +398,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetInverseFull)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -410,7 +410,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, Dot)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -422,7 +422,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetLength)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -434,7 +434,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetLengthEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -446,7 +446,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetLengthReciprocal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -458,7 +458,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetLengthReciprocalEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -470,7 +470,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetNormalized)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -482,7 +482,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetNormalizedEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -494,7 +494,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, NormalizeWithLength)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -506,7 +506,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, NormalizeWithLengthEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -518,7 +518,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, Lerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -530,7 +530,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, NLerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -542,7 +542,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, Slerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -554,7 +554,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, OperatorEquality)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -566,7 +566,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, OperatorInequality)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -578,7 +578,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, OperatorNegate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -590,7 +590,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, OperatorSum)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -602,7 +602,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, OperatorSub)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -614,7 +614,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, OperatorMultiply)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -626,7 +626,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, OperatorMultiplyScalar)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -638,7 +638,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, TransformVector)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -653,7 +653,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, IsClose)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -665,7 +665,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, IsIdentity)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -677,7 +677,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetEulerDegrees)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -689,7 +689,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, GetEulerRadians)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -701,7 +701,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetFromEulerRadians)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -715,7 +715,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, SetFromEulerDegrees)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -729,7 +729,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, ConvertToAxisAngle)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& quatData : m_quatDataArray) { @@ -744,7 +744,7 @@ namespace Benchmark BENCHMARK_F(BM_MathQuaternion, AggregateMultiply)(::benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZ::Vector3 position = AZ::Vector3::CreateZero(); for (auto& quatData : m_quatDataArray) diff --git a/Code/Framework/AzCore/Tests/Math/ShapeIntersectionPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/ShapeIntersectionPerformanceTests.cpp index ecab1717b2..7526bdb778 100644 --- a/Code/Framework/AzCore/Tests/Math/ShapeIntersectionPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/ShapeIntersectionPerformanceTests.cpp @@ -80,7 +80,7 @@ namespace Benchmark BENCHMARK_F(BM_MathShapeIntersection, ContainsFrustumPoint)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -103,7 +103,7 @@ namespace Benchmark BENCHMARK_F(BM_MathShapeIntersection, OverlapsFrustumSphere)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -120,7 +120,7 @@ namespace Benchmark BENCHMARK_F(BM_MathShapeIntersection, ContainsFrustumSphere)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -137,7 +137,7 @@ namespace Benchmark BENCHMARK_F(BM_MathShapeIntersection, OverlapsFrustumAabb)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -154,7 +154,7 @@ namespace Benchmark BENCHMARK_F(BM_MathShapeIntersection, ContainsFrustumAabb)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { diff --git a/Code/Framework/AzCore/Tests/Math/TransformPerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/TransformPerformanceTests.cpp index dde0192ef9..37d9a32820 100644 --- a/Code/Framework/AzCore/Tests/Math/TransformPerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/TransformPerformanceTests.cpp @@ -78,7 +78,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateIdentity)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for ([[maybe_unused]] auto& testData : m_testDataArray) { @@ -90,7 +90,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateRotationX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -102,7 +102,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateRotationY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -114,7 +114,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateRotationZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -126,7 +126,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateFromQuaternion)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -138,7 +138,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateFromQuaternionAndTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -150,7 +150,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateFromMatrix3x3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -162,7 +162,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateFromMatrix3x3AndTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -174,7 +174,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateFromMatrix3x4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -186,7 +186,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateUniformScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -198,7 +198,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateFromTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -210,7 +210,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, CreateLookAt)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -223,7 +223,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetBasis)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -235,7 +235,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetBasisX)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -247,7 +247,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetBasisY)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -259,7 +259,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetBasisZ)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -271,7 +271,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetBasisAndTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -287,7 +287,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetTranslation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -299,7 +299,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, SetTranslationWithFloats)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -312,7 +312,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, SetTranslationWithVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -325,7 +325,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetRotation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -337,7 +337,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, SetRotation)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -350,7 +350,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetUniformScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -362,7 +362,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, SetUniformScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -375,7 +375,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, ExtractUniformScale)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -388,7 +388,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, OperatorMultiplyTransform)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -400,7 +400,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, OperatorMultiplyEqualsTransform)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -413,7 +413,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, TransformPointVector3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -425,7 +425,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, TransformPointVector4)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -437,7 +437,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, TransformVector)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -449,7 +449,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetInverse)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -461,7 +461,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, Invert)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -474,7 +474,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, IsOrthogonal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -486,7 +486,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetOrthogonalized)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -498,7 +498,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, Orthogonalize)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -511,7 +511,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, IsCloseExactAndDifferent)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -526,7 +526,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, OperatorEqualEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -538,7 +538,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, OperatorNotEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -550,7 +550,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetEulerDegrees)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -562,7 +562,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, GetEulerRadians)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -574,7 +574,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, SetFromEulerDegrees)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -587,7 +587,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, SetFromEulerRadians)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { @@ -600,7 +600,7 @@ namespace Benchmark BENCHMARK_F(BM_MathTransform, IsFinite)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& testData : m_testDataArray) { diff --git a/Code/Framework/AzCore/Tests/Math/Vector2PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Vector2PerformanceTests.cpp index 3ab306ff66..6c8e575481 100644 --- a/Code/Framework/AzCore/Tests/Math/Vector2PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Vector2PerformanceTests.cpp @@ -58,7 +58,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetSet)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZ::Vector2 v1, v2; float x = 0.0f, y = 0.0f; @@ -84,7 +84,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, ElementAccess)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZ::Vector2 v1, v2; float x = 0.0f, y = 0.0f; @@ -111,7 +111,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, CreateSelectCmpEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -123,7 +123,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, CreateSelectCmpGreaterEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -135,7 +135,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, CreateSelectCmpGreater)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -147,7 +147,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetNormalized)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -159,7 +159,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetNormalizedEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -171,7 +171,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, NormalizeWithLength)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -183,7 +183,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, NormalizeWithLengthEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -195,7 +195,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetNormalizedSafe)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -207,7 +207,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetNormalizedSafeEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -219,7 +219,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetDistance)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -231,7 +231,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetDistanceEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -243,7 +243,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Lerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -267,7 +267,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Slerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -291,7 +291,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Nlerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -315,7 +315,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Dot)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -327,7 +327,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Equality)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -339,7 +339,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Inequality)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -351,7 +351,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, IsLessThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -363,7 +363,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, IsLessEqualThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -375,7 +375,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, IsGreaterThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -387,7 +387,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, IsGreaterEqualThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -399,7 +399,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetMin)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -411,7 +411,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetMax)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -423,7 +423,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetClamp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -435,7 +435,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Sub)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -447,7 +447,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Sum)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -459,7 +459,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Mul)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -471,7 +471,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Div)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -483,7 +483,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetSin)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -495,7 +495,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetCos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -507,7 +507,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetSinCos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -521,7 +521,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetAcos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -533,7 +533,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetAtan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -545,7 +545,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetAtan2)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -557,7 +557,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetAngleMod)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -569,7 +569,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, Angle)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -581,7 +581,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, AngleDeg)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -593,7 +593,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetAbs)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -605,7 +605,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetReciprocal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -617,7 +617,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetReciprocalEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -629,7 +629,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector2, GetProjected)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { diff --git a/Code/Framework/AzCore/Tests/Math/Vector3PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Vector3PerformanceTests.cpp index 5f33730bca..3e54e435d8 100644 --- a/Code/Framework/AzCore/Tests/Math/Vector3PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Vector3PerformanceTests.cpp @@ -58,7 +58,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetSet)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZ::Vector3 v1, v2, v3; float x = 0.0f, y = 0.0f, z = 0.0f; @@ -98,7 +98,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, ElementAccess)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZ::Vector3 v1, v2, v3; float x = 0.0f, y = 0.0f, z = 0.0f; @@ -138,7 +138,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, CreateSelectCmpEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -150,7 +150,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, CreateSelectCmpGreaterEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -162,7 +162,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, CreateSelectCmpGreater)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -174,7 +174,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetNormalized)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -186,7 +186,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetNormalizedEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -198,7 +198,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, NormalizeWithLength)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -210,7 +210,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, NormalizeWithLengthEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -222,7 +222,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetNormalizedSafe)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -234,7 +234,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetNormalizedSafeEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -246,7 +246,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetDistance)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -258,7 +258,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetDistanceEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -270,7 +270,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Lerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -294,7 +294,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Slerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -318,7 +318,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Nlerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -342,7 +342,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Dot)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -354,7 +354,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Cross)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -366,7 +366,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Equality)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -378,7 +378,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Inequality)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -390,7 +390,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, IsLessThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -402,7 +402,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, IsLessEqualThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -414,7 +414,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, IsGreaterThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -426,7 +426,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, IsGreaterEqualThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -438,7 +438,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetMin)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -450,7 +450,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetMax)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -462,7 +462,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetClamp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -474,7 +474,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Sub)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -486,7 +486,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Sum)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -498,7 +498,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Mul)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -510,7 +510,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Div)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -522,7 +522,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetSin)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -534,7 +534,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetCos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -546,7 +546,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetSinCos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -560,7 +560,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetAcos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -572,7 +572,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetAtan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -584,7 +584,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetAngleMod)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -596,7 +596,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, Angle)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -608,7 +608,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, AngleDeg)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -620,7 +620,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetAbs)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -632,7 +632,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetReciprocal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -644,7 +644,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetReciprocalEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -656,7 +656,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, IsPerpendicular)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -668,7 +668,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetOrthogonalVector)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -680,7 +680,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector3, GetProjected)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { diff --git a/Code/Framework/AzCore/Tests/Math/Vector4PerformanceTests.cpp b/Code/Framework/AzCore/Tests/Math/Vector4PerformanceTests.cpp index f12851b1ed..d2a5bbd46b 100644 --- a/Code/Framework/AzCore/Tests/Math/Vector4PerformanceTests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Vector4PerformanceTests.cpp @@ -60,7 +60,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetSet)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZ::Vector4 v1, v2, v3, v4; float x = 0.0f, y = 0.0f, z = 0.0f, w = 0.0f; @@ -117,7 +117,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, ElementAccess)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZ::Vector4 v1, v2, v3, v4; float x = 0.0f, y = 0.0f, z = 0.0f, w = 0.0f; @@ -174,7 +174,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, CreateSelectCmpEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -186,7 +186,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, CreateSelectCmpGreaterEqual)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -198,7 +198,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, CreateSelectCmpGreater)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -210,7 +210,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetNormalized)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -222,7 +222,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetNormalizedEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -234,7 +234,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, NormalizeWithLength)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -246,7 +246,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, NormalizeWithLengthEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -258,7 +258,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetNormalizedSafe)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -270,7 +270,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetNormalizedSafeEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -282,7 +282,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetDistance)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -294,7 +294,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetDistanceEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -306,7 +306,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Lerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -330,7 +330,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Slerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -354,7 +354,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Nlerp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -378,7 +378,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Dot)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -390,7 +390,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Dot3)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -402,7 +402,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetHomogenized)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -414,7 +414,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Equality)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -426,7 +426,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Inequality)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -438,7 +438,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, IsLessThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -450,7 +450,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, IsLessEqualThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -462,7 +462,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, IsGreaterThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -474,7 +474,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, IsGreaterEqualThan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -486,7 +486,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetMin)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -498,7 +498,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetMax)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -510,7 +510,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetClamp)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -522,7 +522,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Sub)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -534,7 +534,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Sum)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -546,7 +546,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Mul)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -558,7 +558,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Div)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -570,7 +570,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetSin)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -582,7 +582,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetCos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -594,7 +594,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetSinCos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -608,7 +608,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetAcos)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -620,7 +620,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetAtan)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -632,7 +632,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetAngleMod)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -644,7 +644,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, Angle)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -656,7 +656,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, AngleDeg)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -668,7 +668,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetAbs)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -680,7 +680,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetReciprocal)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { @@ -692,7 +692,7 @@ namespace Benchmark BENCHMARK_F(BM_MathVector4, GetReciprocalEstimate)(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& vecData : m_vecDataArray) { diff --git a/Code/Framework/AzCore/Tests/Memory/AllocatorBenchmarks.cpp b/Code/Framework/AzCore/Tests/Memory/AllocatorBenchmarks.cpp index e027b03a49..f7ebc2f632 100644 --- a/Code/Framework/AzCore/Tests/Memory/AllocatorBenchmarks.cpp +++ b/Code/Framework/AzCore/Tests/Memory/AllocatorBenchmarks.cpp @@ -288,7 +288,7 @@ namespace Benchmark public: void Benchmark(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); @@ -333,7 +333,7 @@ namespace Benchmark public: void Benchmark(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); AZStd::vector& perThreadAllocations = base::GetPerThreadAllocations(state.thread_index); @@ -420,7 +420,7 @@ namespace Benchmark void Benchmark(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); diff --git a/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp b/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp index 95b0626d7f..3f3386241a 100644 --- a/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp +++ b/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp @@ -1248,7 +1248,7 @@ namespace Benchmark AZStd::unique_ptr buffer(new char[FileSize]); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::binary_semaphore waitForReads; AZStd::atomic end; diff --git a/Code/Framework/AzCore/Tests/TaskTests.cpp b/Code/Framework/AzCore/Tests/TaskTests.cpp index 53fa89900e..7d805ce1f7 100644 --- a/Code/Framework/AzCore/Tests/TaskTests.cpp +++ b/Code/Framework/AzCore/Tests/TaskTests.cpp @@ -677,7 +677,7 @@ namespace Benchmark [] { }); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { TaskGraphEvent ev; graph->SubmitOnExecutor(*executor, &ev); @@ -699,7 +699,7 @@ namespace Benchmark }); a.Precedes(b); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { TaskGraphEvent ev; graph->SubmitOnExecutor(*executor, &ev); @@ -729,7 +729,7 @@ namespace Benchmark e.Follows(a, b, c, d); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { TaskGraphEvent ev; graph->SubmitOnExecutor(*executor, &ev); diff --git a/Code/Framework/AzFramework/Tests/OctreePerformanceTests.cpp b/Code/Framework/AzFramework/Tests/OctreePerformanceTests.cpp index 64fba61e2c..7ab2638af6 100644 --- a/Code/Framework/AzFramework/Tests/OctreePerformanceTests.cpp +++ b/Code/Framework/AzFramework/Tests/OctreePerformanceTests.cpp @@ -142,7 +142,7 @@ namespace Benchmark BENCHMARK_F(BM_Octree, InsertDelete1000)(benchmark::State& state) { constexpr uint32_t EntryCount = 1000; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { InsertEntries(EntryCount); RemoveEntries(EntryCount); @@ -152,7 +152,7 @@ namespace Benchmark BENCHMARK_F(BM_Octree, InsertDelete10000)(benchmark::State& state) { constexpr uint32_t EntryCount = 10000; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { InsertEntries(EntryCount); RemoveEntries(EntryCount); @@ -162,7 +162,7 @@ namespace Benchmark BENCHMARK_F(BM_Octree, InsertDelete100000)(benchmark::State& state) { constexpr uint32_t EntryCount = 100000; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { InsertEntries(EntryCount); RemoveEntries(EntryCount); @@ -172,7 +172,7 @@ namespace Benchmark BENCHMARK_F(BM_Octree, InsertDelete1000000)(benchmark::State& state) { constexpr uint32_t EntryCount = 1000000; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { InsertEntries(EntryCount); RemoveEntries(EntryCount); @@ -183,7 +183,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 1000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -197,7 +197,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 10000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -211,7 +211,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 100000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -225,7 +225,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 1000000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -239,7 +239,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 1000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -253,7 +253,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 10000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -267,7 +267,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 100000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -281,7 +281,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 1000000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -295,7 +295,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 1000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -309,7 +309,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 10000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -323,7 +323,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 100000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { @@ -337,7 +337,7 @@ namespace Benchmark { constexpr uint32_t EntryCount = 1000000; InsertEntries(EntryCount); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (auto& queryData : m_queryDataArray) { diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp index 8cc5e5f4d2..debca753de 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabCreateBenchmarks.cpp @@ -21,7 +21,7 @@ namespace Benchmark CreateFakePaths(numInstances); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); @@ -60,7 +60,7 @@ namespace Benchmark { const unsigned int numEntities = static_cast(state.range()); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); @@ -100,7 +100,7 @@ namespace Benchmark // plus the instance receiving them CreateFakePaths(numInstancesToAdd + 1); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); @@ -150,7 +150,7 @@ namespace Benchmark // plus the root instance CreateFakePaths(numInstances + 1); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp index f2f3cf82b0..cc1caf1a82 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabInstantiateBenchmarks.cpp @@ -24,7 +24,7 @@ namespace Benchmark m_pathString); TemplateId templateToInstantiateId = firstInstance->GetTemplateId(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp index dd29654416..60e87a7a82 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabLoadBenchmarks.cpp @@ -19,7 +19,7 @@ namespace Benchmark const unsigned int numTemplates = static_cast(state.range()); CreateFakePaths(numTemplates); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabUpdateInstancesBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabUpdateInstancesBenchmarks.cpp index 92a30b89f2..4f50da66c8 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabUpdateInstancesBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/PrefabUpdateInstancesBenchmarks.cpp @@ -24,7 +24,7 @@ namespace Benchmark const auto& nestedTemplatePath = m_paths.front(); const auto& enclosingTemplatePath = m_paths.back(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); @@ -85,7 +85,7 @@ namespace Benchmark const unsigned int numInstances = maxDepth; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); @@ -137,7 +137,7 @@ namespace Benchmark const unsigned int numInstances = numRootInstances * maxDepth; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); @@ -197,7 +197,7 @@ namespace Benchmark const unsigned int numInstances = (1 << maxDepth) - 1; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/Spawnable/SpawnAllEntitiesBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/Spawnable/SpawnAllEntitiesBenchmarks.cpp index ba0c3a4838..a44ce6dd28 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/Spawnable/SpawnAllEntitiesBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/Spawnable/SpawnAllEntitiesBenchmarks.cpp @@ -22,7 +22,7 @@ namespace Benchmark SetUpSpawnableAsset(entityCountInSourcePrefab); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); m_spawnTicket = aznew AzFramework::EntitySpawnTicket(m_spawnableAsset); @@ -59,7 +59,7 @@ namespace Benchmark SetUpSpawnableAsset(entityCountInSpawnable); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); m_spawnTicket = aznew AzFramework::EntitySpawnTicket(m_spawnableAsset); @@ -94,7 +94,7 @@ namespace Benchmark SetUpSpawnableAsset(entityCountInSpawnable); auto spawner = AzFramework::SpawnableEntitiesInterface::Get(); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { state.PauseTiming(); m_spawnTicket = aznew AzFramework::EntitySpawnTicket(m_spawnableAsset); diff --git a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp index d9024114a5..e625a1ba0c 100644 --- a/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp +++ b/Code/Framework/AzToolsFramework/Tests/Prefab/Benchmark/SpawnableCreateBenchmarks.cpp @@ -27,7 +27,7 @@ namespace Benchmark auto& prefabDom = m_prefabSystemComponent->FindTemplateDom(instance->GetTemplateId()); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { // Create a vector to store spawnables so that they don't get destroyed immediately after construction. AZStd::vector> spawnables; diff --git a/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.cpp b/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.cpp index d3c537ea1d..c05d34221b 100644 --- a/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.cpp +++ b/Gems/GradientSignal/Code/Tests/GradientSignalTestHelpers.cpp @@ -259,7 +259,7 @@ namespace UnitTest const float width = aznumeric_cast(queryRange); // Call GetValue() on the EBus for every height and width in our ranges. - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (float y = 0.0f; y < height; y += 1.0f) { @@ -285,7 +285,7 @@ namespace UnitTest int64_t totalQueryPoints = queryRange * queryRange; // Call GetValues() for every height and width in our ranges. - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { // Set up our vector of query positions. This is done inside the benchmark timing since we're counting the work to create // each query position in the single GetValue() call benchmarks, and will make the timing more directly comparable. @@ -313,7 +313,7 @@ namespace UnitTest const float width = aznumeric_cast(queryRange); // Call GetValue() through the GradientSampler for every height and width in our ranges. - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (float y = 0.0f; y < height; y += 1.0f) { @@ -343,7 +343,7 @@ namespace UnitTest const int64_t totalQueryPoints = queryRange * queryRange; // Call GetValues() through the GradientSampler for every height and width in our ranges. - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { // Set up our vector of query positions. This is done inside the benchmark timing since we're counting the work to create // each query position in the single GetValue() call benchmarks, and will make the timing more directly comparable. diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXCharactersBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXCharactersBenchmarks.cpp index cd9e3c0395..55d7305a70 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXCharactersBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXCharactersBenchmarks.cpp @@ -235,7 +235,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker AZStd::vector tickTimes; tickTimes.reserve(CharacterConstants::GameFramesToSimulate); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < CharacterConstants::GameFramesToSimulate; i++) { @@ -294,7 +294,7 @@ namespace PhysX::Benchmarks AZStd::vector tickTimes; tickTimes.reserve(CharacterConstants::GameFramesToSimulate); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < CharacterConstants::GameFramesToSimulate; i++) { @@ -361,7 +361,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker AZStd::vector tickTimes; tickTimes.reserve(CharacterConstants::GameFramesToSimulate); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { //run each simulation part, and change direction each time for (AZ::u32 i = 0; i < numDirectionChanges; i++) diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXCharactersRagdollBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXCharactersRagdollBenchmarks.cpp index c82d222e80..e86125c1f5 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXCharactersRagdollBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXCharactersRagdollBenchmarks.cpp @@ -198,7 +198,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker AZStd::vector tickTimes; tickTimes.reserve(RagdollConstants::GameFramesToSimulate); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < RagdollConstants::GameFramesToSimulate; i++) { @@ -264,7 +264,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker AZStd::vector tickTimes; tickTimes.reserve(RagdollConstants::GameFramesToSimulate); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < RagdollConstants::GameFramesToSimulate; i++) { diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXGenericBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXGenericBenchmarks.cpp index c2cf7f1246..1e556c3af7 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXGenericBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXGenericBenchmarks.cpp @@ -31,7 +31,7 @@ namespace PhysX::Benchmarks void BM_PhysXBenchmarkFixture(benchmark::State& state) { - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { auto fixture = std::make_unique(); fixture->SetUp(); diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp index de8a9d2146..8606735174 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXJointBenchmarks.cpp @@ -245,7 +245,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker Types::TimeList tickTimes; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < JointConstants::GameFramesToSimulate; i++) { @@ -300,7 +300,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker Types::TimeList tickTimes; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < JointConstants::GameFramesToSimulate; i++) { @@ -399,7 +399,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker Types::TimeList tickTimes; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < JointConstants::GameFramesToSimulate; i++) { diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp index 58cbd0da23..616c248667 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXRigidBodyBenchmarks.cpp @@ -229,7 +229,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker Types::TimeList tickTimes; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < RigidBodyConstants::GameFramesToSimulate; i++) { @@ -302,7 +302,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker AZStd::vector tickTimes; tickTimes.reserve(RigidBodyConstants::GameFramesToSimulate); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < RigidBodyConstants::GameFramesToSimulate; i++) { @@ -471,7 +471,7 @@ namespace PhysX::Benchmarks //setup the frame timer tracker AZStd::vector tickTimes; tickTimes.reserve(RigidBodyConstants::GameFramesToSimulate); - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { for (AZ::u32 i = 0; i < RigidBodyConstants::GameFramesToSimulate; i++) { diff --git a/Gems/PhysX/Code/Tests/Benchmarks/PhysXSceneQueryBenchmarks.cpp b/Gems/PhysX/Code/Tests/Benchmarks/PhysXSceneQueryBenchmarks.cpp index 9a8a28a85e..ba3f7aad40 100644 --- a/Gems/PhysX/Code/Tests/Benchmarks/PhysXSceneQueryBenchmarks.cpp +++ b/Gems/PhysX/Code/Tests/Benchmarks/PhysXSceneQueryBenchmarks.cpp @@ -141,7 +141,7 @@ namespace PhysX::Benchmarks auto* sceneInterface = AZ::Interface::Get(); auto next = 0; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { request.m_direction = m_boxes[next].GetNormalized(); @@ -175,7 +175,7 @@ namespace PhysX::Benchmarks auto* sceneInterface = AZ::Interface::Get(); auto next = 0; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { request.m_direction = m_boxes[next].GetNormalized(); @@ -206,7 +206,7 @@ namespace PhysX::Benchmarks auto* sceneInterface = AZ::Interface::Get(); auto next = 0; - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { request.m_pose = AZ::Transform::CreateTranslation(m_boxes[next]); diff --git a/Gems/SurfaceData/Code/Tests/SurfaceDataBenchmarks.cpp b/Gems/SurfaceData/Code/Tests/SurfaceDataBenchmarks.cpp index becb91f0ce..a507391ae6 100644 --- a/Gems/SurfaceData/Code/Tests/SurfaceDataBenchmarks.cpp +++ b/Gems/SurfaceData/Code/Tests/SurfaceDataBenchmarks.cpp @@ -181,7 +181,7 @@ namespace UnitTest SurfaceData::SurfaceTagVector filterTags = CreateBenchmarkTagFilterList(); // Query every point in our world at 1 meter intervals. - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { // This is declared outside the loop so that the list of points doesn't fully reallocate on every query. SurfaceData::SurfacePointList points; @@ -211,7 +211,7 @@ namespace UnitTest SurfaceData::SurfaceTagVector filterTags = CreateBenchmarkTagFilterList(); // Query every point in our world at 1 meter intervals. - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { SurfaceData::SurfacePointLists points; @@ -235,7 +235,7 @@ namespace UnitTest SurfaceData::SurfaceTagVector filterTags = CreateBenchmarkTagFilterList(); // Query every point in our world at 1 meter intervals. - for (auto _ : state) + for ([[maybe_unused]] auto _ : state) { AZStd::vector queryPositions; queryPositions.reserve(worldSizeInt * worldSizeInt); diff --git a/Gems/Terrain/Code/Tests/TerrainSystemBenchmarks.cpp b/Gems/Terrain/Code/Tests/TerrainSystemBenchmarks.cpp index 6aad3f9568..c2df02779d 100644 --- a/Gems/Terrain/Code/Tests/TerrainSystemBenchmarks.cpp +++ b/Gems/Terrain/Code/Tests/TerrainSystemBenchmarks.cpp @@ -267,7 +267,7 @@ namespace UnitTest auto terrainSystem = CreateAndActivateTerrainSystem(queryResolution, worldBounds); // Call the terrain API we're testing for every height and width in our ranges. - for (auto stateIterator : state) + for ([[maybe_unused]] auto stateIterator : state) { ApiCaller(queryResolution, worldBounds, sampler); } From ddb66786dc4711d31e2276765c435820c0974b0e Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:01:07 -0800 Subject: [PATCH 064/133] Remove unused variable Signed-off-by: Chris Burel --- Code/Framework/AzCore/Tests/Memory.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Code/Framework/AzCore/Tests/Memory.cpp b/Code/Framework/AzCore/Tests/Memory.cpp index 0e0103d162..2be694c384 100644 --- a/Code/Framework/AzCore/Tests/Memory.cpp +++ b/Code/Framework/AzCore/Tests/Memory.cpp @@ -141,7 +141,6 @@ namespace UnitTest //////////////////////////////////////////////////////////////////////// // Create some threads and simulate concurrent allocation and deallocation - AZStd::chrono::system_clock::time_point startTime = AZStd::chrono::system_clock::now(); { AZStd::thread m_threads[m_maxNumThreads]; for (unsigned int i = 0; i < m_maxNumThreads; ++i) @@ -156,8 +155,6 @@ namespace UnitTest m_threads[i].join(); } } - //AZStd::chrono::microseconds exTime = AZStd::chrono::system_clock::now() - startTime; - //AZ_Printf("UnitTest::SystemAllocatorTest::deafult","Time: %d Ms\n",exTime.count()); ////////////////////////////////////////////////////////////////////////// AllocatorInstance::Destroy(); From b79d5faa1602bdc864f36daf35540a16deba5471 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:02:00 -0800 Subject: [PATCH 065/133] Remove unused captures Signed-off-by: Chris Burel --- .../Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp b/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp index 3f3386241a..4efcd0d86e 100644 --- a/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp +++ b/Code/Framework/AzCore/Tests/Platform/Windows/Tests/IO/Streamer/StorageDriveTests_Windows.cpp @@ -981,7 +981,7 @@ namespace AZ::IO AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the // capture. Newer versions issue unused warning - auto callback = [numChunks, &numCallbacks, &waitForReads](FileRequestHandle request) + auto callback = [&numCallbacks, &waitForReads](FileRequestHandle request) AZ_POP_DISABLE_WARNING { IStreamer* streamer = Interface::Get(); @@ -1052,7 +1052,7 @@ namespace AZ::IO AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the // capture. Newer versions issue unused warning - auto callback = [numChunks, &waitForReads, &waitForSingleRead, &numReadCallbacks]([[maybe_unused]] FileRequestHandle request) + auto callback = [&waitForReads, &waitForSingleRead, &numReadCallbacks]([[maybe_unused]] FileRequestHandle request) AZ_POP_DISABLE_WARNING { numReadCallbacks++; @@ -1076,7 +1076,7 @@ namespace AZ::IO cancels.push_back(m_streamer->Cancel(requests[numChunks - i - 1])); AZ_PUSH_DISABLE_WARNING(5233, "-Wunknown-warning-option") // Older versions of MSVC toolchain require to pass constexpr in the // capture. Newer versions issue unused warning - auto callback = [&numCancelCallbacks, &waitForCancels, numChunks](FileRequestHandle request) + auto callback = [&numCancelCallbacks, &waitForCancels](FileRequestHandle request) AZ_POP_DISABLE_WARNING { auto result = Interface::Get()->GetRequestStatus(request); From 5cc258d509781beb6fccfe67b1f86da8f9f40604 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:02:11 -0800 Subject: [PATCH 066/133] Remove unused variable Signed-off-by: Chris Burel --- .../Platform/Windows/AzFramework/Process/ProcessWatcher_Win.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Process/ProcessWatcher_Win.cpp b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Process/ProcessWatcher_Win.cpp index b0ef2f09a4..387a1abfe7 100644 --- a/Code/Framework/AzFramework/Platform/Windows/AzFramework/Process/ProcessWatcher_Win.cpp +++ b/Code/Framework/AzFramework/Platform/Windows/AzFramework/Process/ProcessWatcher_Win.cpp @@ -374,8 +374,6 @@ namespace AzFramework // is double-quoted, then the double-quotes must be escaped properly otherwise // it will be absorbed by the native argument parser and possibly evaluated as // multiple values for arguments - AZStd::string_view escapedDoubleQuote = R"("\")"; - AZStd::vector preprocessedCommandArray; for (const auto& commandArg : commandLineArray) From f59ac65d2c55e197d81995a58823cfc3c6e0245e Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:02:49 -0800 Subject: [PATCH 067/133] Move platform-specific variable to be inside a platform-specific `#ifdef` Signed-off-by: Chris Burel --- .../AzQtComponents/AzQtComponents/Components/FancyDocking.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp index 7e78f64778..26b9e13e18 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp @@ -276,7 +276,6 @@ namespace AzQtComponents */ void FancyDocking::updateDockingGeometry() { - QRect totalScreenRect; int numScreens = QApplication::screens().count(); #ifdef AZ_PLATFORM_WINDOWS @@ -286,6 +285,9 @@ namespace AzQtComponents m_perScreenFullScreenWidgets.clear(); #endif +#if !defined(AZ_PLATFORM_WINDOWS) + QRect totalScreenRect; +#endif for (int i = 0; i < numScreens; ++i) { #ifdef AZ_PLATFORM_WINDOWS From fc2fc8459bbb7db0f5699cb71fb3f78534e69a6e Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:04:10 -0800 Subject: [PATCH 068/133] Fix missing `return;` statement (this is why we use `-Wunused-value`) Signed-off-by: Chris Burel --- Gems/Atom/RHI/DX12/Code/Source/RHI/AliasedHeap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/AliasedHeap.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/AliasedHeap.cpp index c988c4e14e..dcd4a2574c 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/AliasedHeap.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/AliasedHeap.cpp @@ -113,7 +113,7 @@ namespace AZ if (!memoryView.IsValid()) { - RHI::ResultCode::OutOfMemory; + return RHI::ResultCode::OutOfMemory; } buffer->SetDescriptor(descriptor); From bdac37477521b37ab72d3948b1b2e8b60cd2ad5a Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:07:50 -0800 Subject: [PATCH 069/133] Fix case-insensitive non-portable include paths Signed-off-by: Chris Burel --- .../Code/Include/Platform/Windows/Atom_RHI_Vulkan_Windows.h | 2 +- Gems/Blast/Code/Source/Components/BlastFamilyComponent.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Atom/RHI/Vulkan/Code/Include/Platform/Windows/Atom_RHI_Vulkan_Windows.h b/Gems/Atom/RHI/Vulkan/Code/Include/Platform/Windows/Atom_RHI_Vulkan_Windows.h index 2b2c2b015e..de5931f693 100644 --- a/Gems/Atom/RHI/Vulkan/Code/Include/Platform/Windows/Atom_RHI_Vulkan_Windows.h +++ b/Gems/Atom/RHI/Vulkan/Code/Include/Platform/Windows/Atom_RHI_Vulkan_Windows.h @@ -8,7 +8,7 @@ #pragma once #include -#include +#include #include #include #include diff --git a/Gems/Blast/Code/Source/Components/BlastFamilyComponent.h b/Gems/Blast/Code/Source/Components/BlastFamilyComponent.h index 99957d0fce..1a0e8135d9 100644 --- a/Gems/Blast/Code/Source/Components/BlastFamilyComponent.h +++ b/Gems/Blast/Code/Source/Components/BlastFamilyComponent.h @@ -7,7 +7,7 @@ */ #pragma once -#include +#include #include #include #include From d4eb3109506079ca57a5590185828d570b5acee4 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:08:12 -0800 Subject: [PATCH 070/133] Mark unused variables as unused Signed-off-by: Chris Burel --- Code/Framework/AzCore/Tests/AZStd/Examples.cpp | 2 +- Gems/Blast/Code/Source/Family/DamageManager.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Framework/AzCore/Tests/AZStd/Examples.cpp b/Code/Framework/AzCore/Tests/AZStd/Examples.cpp index 518eb5eed6..89441b711e 100644 --- a/Code/Framework/AzCore/Tests/AZStd/Examples.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/Examples.cpp @@ -443,7 +443,7 @@ namespace UnitTest : m_data(data) { /* expensive operations */ } private: - int m_data; + [[maybe_unused]] int m_data; }; ////////////////////////////////////////////////////////////////////////// diff --git a/Gems/Blast/Code/Source/Family/DamageManager.h b/Gems/Blast/Code/Source/Family/DamageManager.h index ed8d03da18..28892074b0 100644 --- a/Gems/Blast/Code/Source/Family/DamageManager.h +++ b/Gems/Blast/Code/Source/Family/DamageManager.h @@ -83,7 +83,7 @@ namespace Blast static AZ::Vector3 TransformToLocal(BlastActor& actor, const AZ::Vector3& globalPosition); BlastMaterial m_blastMaterial; - ActorTracker& m_actorTracker; + [[maybe_unused]] ActorTracker& m_actorTracker; }; template From 3d0a15f009c233f44224fa81cc899025fa59d362 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 13:24:27 -0800 Subject: [PATCH 071/133] Remove `AZStd::to_string(string&, bool)` overload from MCore's StringConversion header This overload has significant impact on overload resolution. Consider these overloads: ```cpp void to_string(AZStd::string& dest, AZStd::wstring_view src); void to_string(string& str, bool value); ``` And then calling code like this: ``` WCHAR src[260]; AZStd::string dst; AZStd::to_string(dst, src); // Which overload does this call? ``` If the .cpp has not included `MCore/Source/StringConversions.h`, the call to `to_string()` will convert the `WCHAR[260]` type to a `AZStd::wstring_view`, and call the first overload. But if `StringConversions.h` _has_ been included, the implicit conversion of `WCHAR[260]` to `bool` has a higher precedence, and it will be chosen instead. This overload was causing some uses of `to_string` in `AnimGraph/GameController.cpp` to resolve to the wrong overload in unity builds. Signed-off-by: Chris Burel --- Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp | 5 ----- Gems/EMotionFX/Code/MCore/Source/StringConversions.h | 2 -- 2 files changed, 7 deletions(-) diff --git a/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp b/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp index 88a22db245..5f57a036c2 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StringConversions.cpp @@ -76,11 +76,6 @@ namespace MCore namespace AZStd { - void to_string(string& str, bool value) - { - str = value ? "true" : "false"; - } - void to_string(string& str, const AZ::Vector2& value) { str = AZStd::string::format("%.8f,%.8f", diff --git a/Gems/EMotionFX/Code/MCore/Source/StringConversions.h b/Gems/EMotionFX/Code/MCore/Source/StringConversions.h index fd1c59208d..01b41091cf 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StringConversions.h +++ b/Gems/EMotionFX/Code/MCore/Source/StringConversions.h @@ -49,7 +49,6 @@ namespace MCore namespace AZStd { - void to_string(string& str, bool value); void to_string(string& str, const AZ::Vector2& value); void to_string(string& str, const AZ::Vector3& value); void to_string(string& str, const AZ::Vector4& value); @@ -57,7 +56,6 @@ namespace AZStd void to_string(string& str, const AZ::Matrix4x4& value); void to_string(string& str, const AZ::Transform& value); - inline AZStd::string to_string(bool val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Vector2& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Vector3& val) { AZStd::string str; to_string(str, val); return str; } inline AZStd::string to_string(const AZ::Vector4& val) { AZStd::string str; to_string(str, val); return str; } From ae7f370fed796cd130ef0855d6d06afda730c465 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:15:34 -0800 Subject: [PATCH 072/133] Fix lambda returning `false` instead of `nullptr` Signed-off-by: Chris Burel --- .../Windows/Editor/Core/QtEditorApplication_windows.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Editor/Platform/Windows/Editor/Core/QtEditorApplication_windows.cpp b/Code/Editor/Platform/Windows/Editor/Core/QtEditorApplication_windows.cpp index f8065af931..1fd7f29ca3 100644 --- a/Code/Editor/Platform/Windows/Editor/Core/QtEditorApplication_windows.cpp +++ b/Code/Editor/Platform/Windows/Editor/Core/QtEditorApplication_windows.cpp @@ -135,7 +135,7 @@ namespace Editor } widget = widget->parentWidget(); } - return false; + return nullptr; }; if (object == toolBarAt(QCursor::pos())) { From 07ce8c6e785636af5d10cb79b69b599d005f2023 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:16:11 -0800 Subject: [PATCH 073/133] Remove unused functions and variables Signed-off-by: Chris Burel --- Code/Legacy/CrySystem/DebugCallStack.cpp | 4 ---- .../CrySystem/LocalizedStringManager.cpp | 21 +------------------ 2 files changed, 1 insertion(+), 24 deletions(-) diff --git a/Code/Legacy/CrySystem/DebugCallStack.cpp b/Code/Legacy/CrySystem/DebugCallStack.cpp index 201582b949..440525d7c8 100644 --- a/Code/Legacy/CrySystem/DebugCallStack.cpp +++ b/Code/Legacy/CrySystem/DebugCallStack.cpp @@ -47,8 +47,6 @@ extern HMODULE gDLLHandle; static HWND hwndException = 0; static bool g_bUserDialog = true; // true=on crash show dialog box, false=supress user interaction -static int PrintException(EXCEPTION_POINTERS* pex); - static bool IsFloatingPointException(EXCEPTION_POINTERS* pex); extern LONG WINAPI CryEngineExceptionFilterWER(struct _EXCEPTION_POINTERS* pExceptionPointers); @@ -667,8 +665,6 @@ INT_PTR CALLBACK DebugCallStack::ExceptionDialogProc(HWND hwndDlg, UINT message, { static EXCEPTION_POINTERS* pex; - static char errorString[32768] = ""; - switch (message) { case WM_INITDIALOG: diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp index c48baa95a7..b69fc539f9 100644 --- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp +++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp @@ -2620,26 +2620,7 @@ namespace UnixTimeToFileTime(unixtime, &filetime); FileTimeToSystemTime(&filetime, systemtime); } - - time_t UnixTimeFromFileTime(const FILETIME* filetime) - { - LONGLONG longlong = filetime->dwHighDateTime; - longlong <<= 32; - longlong |= filetime->dwLowDateTime; - longlong -= 116444736000000000; - return longlong / 10000000; - } - - time_t UnixTimeFromSystemTime(const SYSTEMTIME* systemtime) - { - // convert systemtime to filetime - FILETIME filetime; - SystemTimeToFileTime(systemtime, &filetime); - // convert filetime to unixtime - time_t unixtime = UnixTimeFromFileTime(&filetime); - return unixtime; - } -}; +} void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool bShowSeconds, AZStd::string& outTimeString) { From 0b133f1154ca2788cd271df9f39f8793b3679d4f Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:16:50 -0800 Subject: [PATCH 074/133] Fix format string used for `size_t` (should be `%zu`), remove unused vararg Signed-off-by: Chris Burel --- .../Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp index a90f2cf4a2..428ab16f13 100644 --- a/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp +++ b/Code/Tools/TestImpactFramework/Frontend/Console/Code/Source/TestImpactConsoleTestSequenceEventHandler.cpp @@ -186,7 +186,7 @@ namespace TestImpact void TestRunCompleteCallback(const Client::TestRunBase& testRun, size_t numTestRunsCompleted, size_t totalNumTestRuns) { const auto progress = - AZStd::string::format("(%03u/%03u)", numTestRunsCompleted, totalNumTestRuns, testRun.GetTargetName().c_str()); + AZStd::string::format("(%03zu/%03zu)", numTestRunsCompleted, totalNumTestRuns); AZStd::string result; switch (testRun.GetResult()) From 66ba970a3bffa75ac0badc931960cb8f3409b0c6 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:17:19 -0800 Subject: [PATCH 075/133] Fix methods that recurse infinitely Signed-off-by: Chris Burel --- .../TestImpactClientSequenceReport.h | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h index b668bda155..5c4ac76031 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactClientSequenceReport.h @@ -391,57 +391,57 @@ namespace TestImpact // SequenceReport overrides ... AZStd::chrono::milliseconds GetDuration() const override { - return GetDuration() + m_draftedTestRunReport.GetDuration(); + return SequenceReportBase::GetDuration() + m_draftedTestRunReport.GetDuration(); } TestSequenceResult GetResult() const override { - return CalculateMultiTestSequenceResult({ GetResult(), m_draftedTestRunReport.GetResult() }); + return CalculateMultiTestSequenceResult({ SequenceReportBase::GetResult(), m_draftedTestRunReport.GetResult() }); } size_t GetTotalNumTestRuns() const override { - return GetTotalNumTestRuns() + m_draftedTestRunReport.GetTotalNumTestRuns(); + return SequenceReportBase::GetTotalNumTestRuns() + m_draftedTestRunReport.GetTotalNumTestRuns(); } size_t GetTotalNumPassingTests() const override { - return GetTotalNumPassingTests() + m_draftedTestRunReport.GetTotalNumPassingTests(); + return SequenceReportBase::GetTotalNumPassingTests() + m_draftedTestRunReport.GetTotalNumPassingTests(); } size_t GetTotalNumFailingTests() const override { - return GetTotalNumFailingTests() + m_draftedTestRunReport.GetTotalNumFailingTests(); + return SequenceReportBase::GetTotalNumFailingTests() + m_draftedTestRunReport.GetTotalNumFailingTests(); } size_t GetTotalNumDisabledTests() const override { - return GetTotalNumDisabledTests() + m_draftedTestRunReport.GetTotalNumDisabledTests(); + return SequenceReportBase::GetTotalNumDisabledTests() + m_draftedTestRunReport.GetTotalNumDisabledTests(); } size_t GetTotalNumPassingTestRuns() const override { - return GetTotalNumPassingTestRuns() + m_draftedTestRunReport.GetNumPassingTestRuns(); + return SequenceReportBase::GetTotalNumPassingTestRuns() + m_draftedTestRunReport.GetNumPassingTestRuns(); } size_t GetTotalNumFailingTestRuns() const override { - return GetTotalNumFailingTestRuns() + m_draftedTestRunReport.GetNumFailingTestRuns(); + return SequenceReportBase::GetTotalNumFailingTestRuns() + m_draftedTestRunReport.GetNumFailingTestRuns(); } size_t GetTotalNumExecutionFailureTestRuns() const override { - return GetTotalNumExecutionFailureTestRuns() + m_draftedTestRunReport.GetNumExecutionFailureTestRuns(); + return SequenceReportBase::GetTotalNumExecutionFailureTestRuns() + m_draftedTestRunReport.GetNumExecutionFailureTestRuns(); } size_t GetTotalNumTimedOutTestRuns() const override { - return GetTotalNumTimedOutTestRuns() + m_draftedTestRunReport.GetNumTimedOutTestRuns(); + return SequenceReportBase::GetTotalNumTimedOutTestRuns() + m_draftedTestRunReport.GetNumTimedOutTestRuns(); } size_t GetTotalNumUnexecutedTestRuns() const override { - return GetTotalNumUnexecutedTestRuns() + m_draftedTestRunReport.GetNumUnexecutedTestRuns(); + return SequenceReportBase::GetTotalNumUnexecutedTestRuns() + m_draftedTestRunReport.GetNumUnexecutedTestRuns(); } private: AZStd::vector m_draftedTestRuns; From 24339e36ab48164cb8a6bb296bba004530efeb9b Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:19:26 -0800 Subject: [PATCH 076/133] Fix non-constexpr `RepoPath` class to not try to be `constexpr` `RepoPath` is implemented with an `AZ::IO::Path`, which is not `constexpr`. Consequently, its constructors also cannot be `constexpr`. This also marks the function definitions in the header as `inline`, to avoid ODR violations. Signed-off-by: Chris Burel --- .../TestImpactFramework/TestImpactRepoPath.h | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRepoPath.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRepoPath.h index e784c43500..eede3e5968 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRepoPath.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRepoPath.h @@ -24,13 +24,13 @@ namespace TestImpact using value_type = AZ::IO::Path::value_type; constexpr RepoPath() = default; - constexpr RepoPath(const RepoPath&) = default; - constexpr RepoPath(RepoPath&&) noexcept = default; - constexpr RepoPath(const string_type& path) noexcept; - constexpr RepoPath(const string_view_type& path) noexcept; - constexpr RepoPath(const value_type* path) noexcept; - constexpr RepoPath(const AZ::IO::PathView& path); - constexpr RepoPath(const AZ::IO::Path& path); + RepoPath(const RepoPath&) = default; + RepoPath(RepoPath&&) noexcept = default; + RepoPath(const string_type& path) noexcept; + RepoPath(const string_view_type& path) noexcept; + RepoPath(const value_type* path) noexcept; + RepoPath(const AZ::IO::PathView& path); + RepoPath(const AZ::IO::Path& path); RepoPath& operator=(const RepoPath&) noexcept = default; RepoPath& operator=(const string_type&) noexcept; @@ -67,27 +67,27 @@ namespace TestImpact AZ::IO::Path m_path; }; - constexpr RepoPath::RepoPath(const string_type& path) noexcept + inline RepoPath::RepoPath(const string_type& path) noexcept : m_path(AZ::IO::Path(path).MakePreferred()) { } - constexpr RepoPath::RepoPath(const string_view_type& path) noexcept + inline RepoPath::RepoPath(const string_view_type& path) noexcept : m_path(AZ::IO::Path(path).MakePreferred()) { } - constexpr RepoPath::RepoPath(const value_type* path) noexcept + inline RepoPath::RepoPath(const value_type* path) noexcept : m_path(AZ::IO::Path(path).MakePreferred()) { } - constexpr RepoPath::RepoPath(const AZ::IO::PathView& path) + inline RepoPath::RepoPath(const AZ::IO::PathView& path) : m_path(AZ::IO::Path(path).MakePreferred()) { } - constexpr RepoPath::RepoPath(const AZ::IO::Path& path) + inline RepoPath::RepoPath(const AZ::IO::Path& path) : m_path(AZ::IO::Path(path).MakePreferred()) { } From 20e268930ca72de7be5c4024792b9aaa20025364 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:21:20 -0800 Subject: [PATCH 077/133] Correct use of the `typename` keyword Signed-off-by: Chris Burel --- .../Include/TestImpactFramework/TestImpactRepoPath.h | 4 ++-- .../Process/JobRunner/TestImpactProcessJobRunner.h | 10 +++++----- .../Code/Source/TestEngine/TestImpactTestEngine.cpp | 4 ++-- .../TestImpactClientSequenceReportSerializer.cpp | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRepoPath.h b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRepoPath.h index eede3e5968..0cd01f73aa 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRepoPath.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Include/TestImpactFramework/TestImpactRepoPath.h @@ -52,11 +52,11 @@ namespace TestImpact // Wrappers around the AZ::IO::Path concatenation operator friend RepoPath operator/(const RepoPath& lhs, const AZ::IO::PathView& rhs); friend RepoPath operator/(const RepoPath& lhs, AZStd::string_view rhs); - friend RepoPath operator/(const RepoPath& lhs, const typename value_type* rhs); + friend RepoPath operator/(const RepoPath& lhs, const value_type* rhs); friend RepoPath operator/(const RepoPath& lhs, const RepoPath& rhs); RepoPath& operator/=(const AZ::IO::PathView& rhs); RepoPath& operator/=(AZStd::string_view rhs); - RepoPath& operator/=(const typename value_type* rhs); + RepoPath& operator/=(const value_type* rhs); RepoPath& operator/=(const RepoPath& rhs); friend bool operator==(const RepoPath& lhs, const RepoPath& rhs) noexcept; diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Process/JobRunner/TestImpactProcessJobRunner.h b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Process/JobRunner/TestImpactProcessJobRunner.h index 8144615aeb..c46edbbfb7 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Process/JobRunner/TestImpactProcessJobRunner.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Process/JobRunner/TestImpactProcessJobRunner.h @@ -58,14 +58,14 @@ namespace TestImpact //! @param payloadMapProducer The client callback to be called when all jobs have finished to transform the work produced by each job into the desired output. //! @param jobCallback The client callback to be called when each job changes state. //! @return The result of the run sequence and the jobs with their associated payloads. - AZStd::pair> Execute( + AZStd::pair> Execute( const AZStd::vector& jobs, PayloadMapProducer payloadMapProducer, StdOutputRouting stdOutRouting, StdErrorRouting stdErrRouting, AZStd::optional jobTimeout, AZStd::optional runnerTimeout, - JobCallback jobCallback); + JobCallback jobCallback); private: ProcessScheduler m_processScheduler; @@ -82,17 +82,17 @@ namespace TestImpact } template - AZStd::pair> JobRunner::Execute( + AZStd::pair> JobRunner::Execute( const AZStd::vector& jobInfos, PayloadMapProducer payloadMapProducer, StdOutputRouting stdOutRouting, StdErrorRouting stdErrRouting, AZStd::optional jobTimeout, AZStd::optional runnerTimeout, - JobCallback jobCallback) + JobCallback jobCallback) { AZStd::vector processes; - AZStd::unordered_map> metas; + AZStd::unordered_map> metas; AZStd::vector jobs; jobs.reserve(jobInfos.size()); processes.reserve(jobInfos.size()); diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp index c84700065f..e5269a5769 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp @@ -162,7 +162,7 @@ namespace TestImpact { } - [[nodiscard]] ProcessCallbackResult operator()(const typename JobInfo& jobInfo, const TestImpact::JobMeta& meta) + [[nodiscard]] ProcessCallbackResult operator()(const JobInfo& jobInfo, const TestImpact::JobMeta& meta) { const auto id = jobInfo.GetId().m_value; const auto& args = jobInfo.GetCommand().m_args; @@ -189,7 +189,7 @@ namespace TestImpact private: const AZStd::vector& m_testTargets; - TestEngineJobMap* m_engineJobs; + TestEngineJobMap* m_engineJobs; Policy::ExecutionFailure m_executionFailurePolicy; Policy::TestFailure m_testFailurePolicy; AZStd::optional* m_callback; diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp index 944fd4ac38..46a2d2dab9 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp @@ -775,7 +775,7 @@ namespace TestImpact serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::MaxConcurrency]].GetUint64(), testTargetTimeout ? AZStd::optional{ testTargetTimeout } : AZStd::nullopt, globalTimeout ? AZStd::optional{ globalTimeout } : AZStd::nullopt, - DeserializePolicyStateType(serialSequenceReportBase), + DeserializePolicyStateType(serialSequenceReportBase), SuiteTypeFromString(serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::Suite]].GetString()), DeserializeTestSelection(serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::SelectedTestRuns]]), DeserializeTestRunReport(serialSequenceReportBase[SequenceReportFields::Keys[SequenceReportFields::SelectedTestRunReport]])); From 86aa5093eca9c72415f81a5c4ac0b09953aef52b Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:23:48 -0800 Subject: [PATCH 078/133] Use `enable_if` to control what types can instantiate a template Using a `static_assert(false, ...)` expression in the `else` block of a `if constexpr` statement doesn't work. The `else` block is not protected by the `constexpr`-ness of the `if`s, so it is always compiled. Consequently it will always fail to compile. Signed-off-by: Chris Burel --- .../TestImpactClientSequenceReportSerializer.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp index 46a2d2dab9..65a5c88883 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestImpactClientSequenceReportSerializer.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include #include @@ -735,7 +736,11 @@ namespace TestImpact }; } - template + template, + AZStd::is_same, + AZStd::is_same + >>> PolicyStateType DeserializePolicyStateType(const rapidjson::Value& serialPolicyStateType) { if constexpr (AZStd::is_same_v) @@ -750,10 +755,6 @@ namespace TestImpact { return DeserializeImpactAnalysisSequencePolicyStateMembers(serialPolicyStateType); } - else - { - static_assert(false, "Template paramater must be a valid policy state type"); - } } template From be785dbae863a8d7b55680beb98f041cff842065 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:30:09 -0800 Subject: [PATCH 079/133] Correct the signature for the copy constructor of `TestImpact::Pipe` Signed-off-by: Chris Burel --- .../Source/Platform/Windows/Process/TestImpactWin32_Pipe.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Pipe.h b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Pipe.h index 19c11dd4da..9f55ad6074 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Pipe.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Platform/Windows/Process/TestImpactWin32_Pipe.h @@ -24,8 +24,8 @@ namespace TestImpact public: Pipe(SECURITY_ATTRIBUTES& sa, HANDLE& stdChannel); Pipe(Pipe&& other) = delete; - Pipe(Pipe& other) = delete; - Pipe& operator=(Pipe& other) = delete; + Pipe(const Pipe& other) = delete; + Pipe& operator=(const Pipe& other) = delete; Pipe& operator=(Pipe&& other) = delete; //! Releases the child end of the pipe (not needed once parent has their end). From 41be03f193c5163b209ba255707b7c804048deeb Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:30:39 -0800 Subject: [PATCH 080/133] Silence warning about unnecessary lambda captures with clang The `unused-lambda-capture` will be triggered by the following code: ```cpp void foo(int); int main() { const int i = 0; auto l = [i](){foo(i);}; } ``` The issue here is that reading from the constant variable `i` does not constitute an ODR-use, and consequently the variable does not have to be captured. See https://github.com/llvm/llvm-project/issues/34213#issuecomment-980987311 for a related discussion. However, MSVC sees it differently. In order to make both compilers happy, mark this variable with `AZ_UNUSED`, since lambda captures can't be marked with attributes like `[[maybe_unused]]`. Signed-off-by: Chris Burel --- .../Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp index f39cfaaf10..dfa8c9c49b 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/Artifact/Factory/TestImpactTestRunSuiteFactory.cpp @@ -69,6 +69,7 @@ namespace TestImpact const auto getDuration = [Keys](const AZ::rapidxml::xml_node<>* node) AZ_POP_DISABLE_WARNING { + AZ_UNUSED(Keys); // Clang reports a warning that capturing Keys is not necessary because it is not odr-used const AZStd::string duration = node->first_attribute(Keys[DurationKey])->value(); return AZStd::chrono::milliseconds(static_cast(AZStd::stof(duration) * 1000.f)); }; @@ -86,6 +87,7 @@ namespace TestImpact const auto getStatus = [Keys](const AZ::rapidxml::xml_node<>* node) AZ_POP_DISABLE_WARNING { + AZ_UNUSED(Keys); // Clang reports a warning that capturing Keys is not necessary because it is not odr-used const AZStd::string status = node->first_attribute(Keys[StatusKey])->value(); if (status == Keys[RunKey]) { From 872f2a0cfad5658f8cdf37c598f3e275fa37cf49 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:30:54 -0800 Subject: [PATCH 081/133] Remove unused private class member Signed-off-by: Chris Burel --- .../Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp | 3 +-- .../Runtime/Code/Source/TestEngine/TestImpactTestEngine.h | 1 - 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp index e5269a5769..75f02982c0 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.cpp @@ -239,8 +239,7 @@ namespace TestImpact const RepoPath& testRunnerBinary, const RepoPath& instrumentBinary, size_t maxConcurrentRuns) - : m_maxConcurrentRuns(maxConcurrentRuns) - , m_testJobInfoGenerator(AZStd::make_unique( + : m_testJobInfoGenerator(AZStd::make_unique( sourceDir, targetBinaryDir, cacheDir, artifactDir, testRunnerBinary, instrumentBinary)) , m_testEnumerator(AZStd::make_unique(maxConcurrentRuns)) , m_instrumentedTestRunner(AZStd::make_unique(maxConcurrentRuns)) diff --git a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.h b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.h index 6b097f241f..bba94e38b3 100644 --- a/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.h +++ b/Code/Tools/TestImpactFramework/Runtime/Code/Source/TestEngine/TestImpactTestEngine.h @@ -117,7 +117,6 @@ namespace TestImpact //! Cleans up the artifacts directory of any artifacts from previous runs. void DeleteArtifactXmls() const; - size_t m_maxConcurrentRuns = 0; AZStd::unique_ptr m_testJobInfoGenerator; AZStd::unique_ptr m_testEnumerator; AZStd::unique_ptr m_instrumentedTestRunner; From ca297fdf38c2c4a0ae3df6c4f8a6ba69e648c9f1 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Thu, 10 Feb 2022 15:31:24 -0800 Subject: [PATCH 082/133] Remove unused variables Signed-off-by: Chris Burel --- Code/Editor/Util/3DConnexionDriver.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/Code/Editor/Util/3DConnexionDriver.cpp b/Code/Editor/Util/3DConnexionDriver.cpp index 9dc1600185..c0d4393b49 100644 --- a/Code/Editor/Util/3DConnexionDriver.cpp +++ b/Code/Editor/Util/3DConnexionDriver.cpp @@ -116,9 +116,6 @@ bool C3DConnexionDriver::GetInputMessageData(LPARAM lParam, S3DConnexionMessage& { if (event->header.dwType == RIM_TYPEHID) { - static bool bGotTranslation = false, - bGotRotation = false; - static int all6DOFs[6] = {0}; LPRAWHID pRawHid = &event->data.hid; // Translation or Rotation packet? They come in two different packets. From c6ba1ef064ba8a92c937ae74b4b25e272ac2d975 Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Fri, 11 Feb 2022 01:10:17 -0600 Subject: [PATCH 083/133] =?UTF-8?q?Atom=20Tools:=20updated=20document=20an?= =?UTF-8?q?d=20windows=20systems=20and=20buses=20to=20support=20multiple?= =?UTF-8?q?=20instances=20=E2=80=A2=20This=20change=20is=20partially=20to?= =?UTF-8?q?=20unblock=20physics=20tool=20prototyping.=20It=20introduces=20?= =?UTF-8?q?a=20tool=20ID=20that=20is=20passed=20down=20into=20systems=20an?= =?UTF-8?q?d=20acts=20as=20a=20context=20for=20document,=20window,=20and?= =?UTF-8?q?=20other=20systems=20and=20buses.=20=E2=80=A2=20The=20document?= =?UTF-8?q?=20system=20component=20is=20no=20longer=20a=20component.=20It?= =?UTF-8?q?=20is=20just=20a=20system=20class=20that=20can=20be=20construct?= =?UTF-8?q?ed=20with=20a=20tool=20ID.=20Internally,=20it=20will=20connect?= =?UTF-8?q?=20to=20its=20buses=20and=20be=20addressable=20by=20tool=20ID.?= =?UTF-8?q?=20More=20than=20one=20can=20be=20instantiated,=20each=20with?= =?UTF-8?q?=20a=20unique=20tool=20ID.=20=E2=80=A2=20These=20changes=20are?= =?UTF-8?q?=20still=20backward=20compatible=20because=20most=20of=20the=20?= =?UTF-8?q?buses=20were=20using=20broadcast=20for=20standalone=20applicati?= =?UTF-8?q?ons.=20All=20of=20those=20calls=20have=20been=20updated=20but?= =?UTF-8?q?=20not=20all=20of=20the=20scripts,=20which=20should=20still=20w?= =?UTF-8?q?ork=20as=20is.=20=E2=80=A2=20Got=20rid=20of=20the=20window=20fa?= =?UTF-8?q?ctory=20request=20bus=20in=20favor=20of=20just=20instantiating?= =?UTF-8?q?=20the=20main=20window=20or=20any=20other=20UI=20in=20the=20app?= =?UTF-8?q?lication=20layer.=20=E2=80=A2=20Fixed=20a=20couple=20of=20bugs?= =?UTF-8?q?=20that=20were=20discovered=20while=20making=20these=20changes.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Guthrie Adams --- .../Atom/atom_utils/material_editor_utils.py | 6 +- .../hydra_AtomMaterialEditor_BasicTests.py | 2 +- .../Application/AtomToolsApplication.h | 29 +- .../Document/AtomToolsDocument.h | 8 +- .../Document/AtomToolsDocumentApplication.h | 12 +- .../Document/AtomToolsDocumentMainWindow.h | 2 +- .../AtomToolsDocumentNotificationBus.h | 3 +- .../Document/AtomToolsDocumentSystem.h} | 68 ++-- .../AtomToolsDocumentSystemRequestBus.h | 11 +- .../Window/AtomToolsMainWindow.h | 5 +- .../AtomToolsMainWindowFactoryRequestBus.h | 30 -- .../AtomToolsMainWindowNotificationBus.h | 3 +- .../Window/AtomToolsMainWindowRequestBus.h | 9 +- .../Application/AtomToolsApplication.cpp | 135 ++++--- .../AssetBrowser/AtomToolsAssetBrowser.cpp | 41 ++- .../Code/Source/AtomToolsFrameworkModule.cpp | 3 - .../Source/Document/AtomToolsDocument.cpp | 49 +-- .../Document/AtomToolsDocumentApplication.cpp | 26 +- .../Document/AtomToolsDocumentMainWindow.cpp | 54 +-- ...ponent.cpp => AtomToolsDocumentSystem.cpp} | 348 +++++++++--------- .../Source/Window/AtomToolsMainWindow.cpp | 47 ++- .../AtomToolsMainWindowSystemComponent.cpp | 9 - .../Code/atomtoolsframework_files.cmake | 5 +- .../Code/Source/Document/MaterialDocument.cpp | 16 +- .../Code/Source/Document/MaterialDocument.h | 4 +- .../Code/Source/MaterialEditorApplication.cpp | 71 ++-- .../Code/Source/MaterialEditorApplication.h | 8 +- .../Viewport/MaterialViewportWidget.cpp | 5 +- .../Source/Viewport/MaterialViewportWidget.h | 4 +- .../Source/Window/MaterialEditorWindow.cpp | 29 +- .../Code/Source/Window/MaterialEditorWindow.h | 2 +- .../MaterialInspector/MaterialInspector.cpp | 5 +- .../MaterialInspector/MaterialInspector.h | 4 +- .../ShaderManagementConsoleDocument.cpp | 8 +- .../ShaderManagementConsoleDocument.h | 6 +- .../ShaderManagementConsoleApplication.cpp | 67 ++-- .../ShaderManagementConsoleApplication.h | 8 +- .../Window/ShaderManagementConsoleWindow.cpp | 12 +- .../Window/ShaderManagementConsoleWindow.h | 2 +- 39 files changed, 554 insertions(+), 602 deletions(-) rename Gems/Atom/Tools/AtomToolsFramework/Code/{Source/Document/AtomToolsDocumentSystemComponent.h => Include/AtomToolsFramework/Document/AtomToolsDocumentSystem.h} (55%) delete mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h rename Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/{AtomToolsDocumentSystemComponent.cpp => AtomToolsDocumentSystem.cpp} (65%) diff --git a/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/material_editor_utils.py b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/material_editor_utils.py index c3c1c76611..90f9399c1c 100644 --- a/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/material_editor_utils.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/atom_utils/material_editor_utils.py @@ -162,11 +162,11 @@ def select_model_config(configname): azlmbr.materialeditor.MaterialViewportRequestBus(azlmbr.bus.Broadcast, "SelectModelPresetByName", configname) -def destroy_main_window(): +def exit(): """ - Closes the Material Editor window + Closes the Material Editor """ - azlmbr.atomtools.AtomToolsMainWindowFactoryRequestBus(azlmbr.bus.Broadcast, "DestroyMainWindow") + azlmbr.atomtools.general.exit() def wait_for_condition(function, timeout_in_seconds=1.0): diff --git a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomMaterialEditor_BasicTests.py b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomMaterialEditor_BasicTests.py index bd00a84919..f881660f33 100644 --- a/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomMaterialEditor_BasicTests.py +++ b/AutomatedTesting/Gem/PythonTests/Atom/tests/hydra_AtomMaterialEditor_BasicTests.py @@ -214,7 +214,7 @@ def run(): (not material_editor.is_open(document1_id)) and (not material_editor.is_open(document2_id)) and (not material_editor.is_open(document3_id)), 2.0) - material_editor.destroy_main_window() + material_editor.exit() if __name__ == "__main__": diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h index 016bc5c5e2..1c2a2edc53 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h @@ -39,16 +39,16 @@ namespace AtomToolsFramework { public: AZ_TYPE_INFO(AtomTools::AtomToolsApplication, "{A0DF25BA-6F74-4F11-9F85-0F99278D5986}"); + AZ_DISABLE_COPY_MOVE(AtomToolsApplication); using Base = AzFramework::Application; - AtomToolsApplication(int* argc, char*** argv); + AtomToolsApplication(const AZStd::string& targetName, int* argc, char*** argv); ~AtomToolsApplication(); virtual bool LaunchLocalServer(); - ////////////////////////////////////////////////////////////////////////// - // AzFramework::Application + // AzFramework::Application overrides... void CreateReflectionManager() override; void Reflect(AZ::ReflectContext* context) override; void RegisterCoreComponents() override; @@ -57,43 +57,25 @@ namespace AtomToolsFramework const char* GetCurrentConfigurationName() const override; void StartCommon(AZ::Entity* systemEntity) override; void Tick() override; - void Stop() override; + void Destroy() override; protected: - ////////////////////////////////////////////////////////////////////////// // AtomsToolMainWindowNotificationBus::Handler overrides... void OnMainWindowClosing() override; - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// // AssetDatabaseRequestsBus::Handler overrides... bool GetAssetDatabaseLocation(AZStd::string& result) override; - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // AzFramework::Application overrides... - void Destroy() override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// // AZ::ComponentApplication overrides... void QueryApplicationType(AZ::ApplicationTypeQuery& appType) const override; - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// // AZ::UserSettingsOwnerRequestBus::Handler overrides... void SaveSettings() override; - ////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////// // EditorPythonConsoleNotificationBus::Handler overrides... void OnTraceMessage(AZStd::string_view message) override; void OnErrorMessage(AZStd::string_view message) override; void OnExceptionMessage(AZStd::string_view message) override; - //////////////////////////////////////////////////////////////////////// - - //! Executable target name generally used as a prefix for logging and other saved files - virtual AZStd::string GetBuildTargetName() const; //! List of filters for assets that need to be pre-built to run the application virtual AZStd::vector GetCriticalAssetFilters() const; @@ -121,5 +103,8 @@ namespace AtomToolsFramework AtomToolsFramework::LocalSocket m_socket; AtomToolsFramework::LocalServer m_server; + + const AZStd::string m_targetName; + const AZ::Crc32 m_toolId = {}; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocument.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocument.h index 2c9497df8e..7f51dc3c57 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocument.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocument.h @@ -23,9 +23,9 @@ namespace AtomToolsFramework public: AZ_RTTI(AtomToolsDocument, "{8992DF74-88EC-438C-B280-6E71D4C0880B}"); AZ_CLASS_ALLOCATOR(AtomToolsDocument, AZ::SystemAllocator, 0); - AZ_DISABLE_COPY(AtomToolsDocument); + AZ_DISABLE_COPY_MOVE(AtomToolsDocument); - AtomToolsDocument(); + AtomToolsDocument(const AZ::Crc32& toolId); virtual ~AtomToolsDocument(); const AZ::Uuid& GetId() const; @@ -66,8 +66,10 @@ namespace AtomToolsFramework //! This can be overridden to restore additional data. virtual bool ReopenRestoreState(); + const AZ::Crc32 m_toolId = {}; + //! The unique id of this document, used for all bus notifications and requests. - AZ::Uuid m_id = AZ::Uuid::CreateRandom(); + const AZ::Uuid m_id = AZ::Uuid::CreateRandom(); //! The absolute path to the document source file. AZStd::string m_absolutePath; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentApplication.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentApplication.h index 7b9327337c..c94cf97508 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentApplication.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentApplication.h @@ -9,6 +9,7 @@ #pragma once #include +#include namespace AtomToolsFramework { @@ -16,13 +17,20 @@ namespace AtomToolsFramework : public AtomToolsApplication { public: - AZ_TYPE_INFO(AtomToolsDocumentApplication, "{F4B43677-EB95-4CBB-8B8E-9EF4247E6F0D}"); + AZ_TYPE_INFO(AtomToolsDocumentApplication, "{AC892170-D353-404A-A3D8-BB039C717295}"); + AZ_DISABLE_COPY_MOVE(AtomToolsDocumentApplication); using Base = AtomToolsApplication; - AtomToolsDocumentApplication(int* argc, char*** argv); + AtomToolsDocumentApplication(const AZStd::string& targetName, int* argc, char*** argv); + protected: // AtomToolsApplication overrides... + void Reflect(AZ::ReflectContext* context) override; + void StartCommon(AZ::Entity* systemEntity) override; + void Destroy() override; void ProcessCommandLine(const AZ::CommandLine& commandLine) override; + + AZStd::unique_ptr m_documentSystem; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentMainWindow.h index 826d2427b1..75c129e10e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentMainWindow.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentMainWindow.h @@ -28,7 +28,7 @@ namespace AtomToolsFramework using Base = AtomToolsMainWindow; - AtomToolsDocumentMainWindow(QWidget* parent = 0); + AtomToolsDocumentMainWindow(const AZ::Crc32& toolId, QWidget* parent = 0); ~AtomToolsDocumentMainWindow(); protected: diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentNotificationBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentNotificationBus.h index b9af219b9e..4fdd1f8aa9 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentNotificationBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentNotificationBus.h @@ -18,8 +18,9 @@ namespace AtomToolsFramework : public AZ::EBusTraits { public: - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + typedef AZ::Crc32 BusIdType; //! Signal that a document was created //! @param documentId unique id of document for which the notification is sent diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystem.h similarity index 55% rename from Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.h rename to Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystem.h index 5eb531ef25..64109ba80a 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystem.h @@ -8,60 +8,34 @@ #pragma once -#include -#include -#include - #include #include #include - -AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT -#include -#include -AZ_POP_DISABLE_WARNING +#include +#include +#include +#include namespace AtomToolsFramework { - //! AtomToolsDocumentSystemComponent is the central component for managing documents - class AtomToolsDocumentSystemComponent - : public AZ::Component - , private AtomToolsDocumentNotificationBus::Handler - , private AtomToolsDocumentSystemRequestBus::Handler + //! AtomToolsDocumentSystem Is responsible for creation, management, and requests related to documents + class AtomToolsDocumentSystem + : public AtomToolsDocumentNotificationBus::Handler + , public AtomToolsDocumentSystemRequestBus::Handler { public: - AZ_COMPONENT(AtomToolsDocumentSystemComponent, "{343A3383-6A59-4343-851B-BF84FC6CB18E}"); - - AtomToolsDocumentSystemComponent(); - ~AtomToolsDocumentSystemComponent() = default; - AtomToolsDocumentSystemComponent(const AtomToolsDocumentSystemComponent&) = delete; - AtomToolsDocumentSystemComponent& operator=(const AtomToolsDocumentSystemComponent&) = delete; + AZ_CLASS_ALLOCATOR(AtomToolsFramework::AtomToolsDocumentSystem, AZ::SystemAllocator, 0); + AZ_RTTI(AtomToolsFramework::AtomToolsDocumentSystem, "{9D31F309-6B20-40C5-813C-F1226180E1F8}"); + AZ_DISABLE_COPY_MOVE(AtomToolsDocumentSystem); static void Reflect(AZ::ReflectContext* context); - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + AtomToolsDocumentSystem() = default; + AtomToolsDocumentSystem(const AZ::Crc32& toolId); + ~AtomToolsDocumentSystem(); - private: - //////////////////////////////////////////////////////////////////////// - // AZ::Component interface implementation - void Init() override; - void Activate() override; - void Deactivate() override; - //////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // AtomToolsDocumentNotificationBus::Handler overrides... - void OnDocumentDependencyModified(const AZ::Uuid& documentId) override; - void OnDocumentExternallyModified(const AZ::Uuid& documentId) override; - ////////////////////////////////////////////////////////////////////////// - - void QueueReopenDocuments(); - void ReopenDocuments(); - - //////////////////////////////////////////////////////////////////////// // AtomToolsDocumentSystemRequestBus::Handler overrides... - void RegisterDocumentType(AZStd::function documentCreator) override; + void RegisterDocumentType(const AtomToolsDocumentFactoryCallback& documentCreator) override; AZ::Uuid CreateDocument() override; bool DestroyDocument(const AZ::Uuid& documentId) override; AZ::Uuid OpenDocument(AZStd::string_view sourcePath) override; @@ -74,11 +48,19 @@ namespace AtomToolsFramework bool SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) override; bool SaveAllDocuments() override; AZ::u32 GetDocumentCount() const override; - //////////////////////////////////////////////////////////////////////// + + private: + // AtomToolsDocumentNotificationBus::Handler overrides... + void OnDocumentDependencyModified(const AZ::Uuid& documentId) override; + void OnDocumentExternallyModified(const AZ::Uuid& documentId) override; + + void QueueReopenDocuments(); + void ReopenDocuments(); AZ::Uuid OpenDocumentImpl(AZStd::string_view sourcePath, bool checkIfAlreadyOpen); - AZStd::function m_documentCreator; + const AZ::Crc32 m_toolId = {}; + AtomToolsDocumentFactoryCallback m_documentCreator; AZStd::unordered_map> m_documentMap; AZStd::unordered_set m_documentIdsWithExternalChanges; AZStd::unordered_set m_documentIdsWithDependencyChanges; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h index 88b5acd3be..d59dc64034 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h @@ -14,16 +14,19 @@ namespace AtomToolsFramework { class AtomToolsDocument; - //! AtomToolsDocumentSystemRequestBus provides high level requests for menus, scripts, etc. + using AtomToolsDocumentFactoryCallback = AZStd::function; + + //! AtomToolsDocumentSystemRequestBus is an interface that provides requests for high level user interactions with a system of documents class AtomToolsDocumentSystemRequests : public AZ::EBusTraits { public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + typedef AZ::Crc32 BusIdType; //! Register a document factory function used to create specific document types - virtual void RegisterDocumentType(AZStd::function documentCreator) = 0; + virtual void RegisterDocumentType(const AtomToolsDocumentFactoryCallback& documentCreator) = 0; //! Create a document //! @return Uuid of new document, or null Uuid if failed diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h index 86e9e2f291..558447998b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindow.h @@ -25,7 +25,7 @@ namespace AtomToolsFramework , protected AtomToolsMainWindowRequestBus::Handler { public: - AtomToolsMainWindow(QWidget* parent = 0); + AtomToolsMainWindow(const AZ::Crc32& toolId, QWidget* parent = 0); ~AtomToolsMainWindow(); protected: @@ -48,6 +48,9 @@ namespace AtomToolsFramework virtual void SetupMetrics(); virtual void UpdateMetrics(); + virtual void UpdateWindowTitle(); + + const AZ::Crc32 m_toolId = {}; AzQtComponents::FancyDocking* m_advancedDockManager = {}; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h deleted file mode 100644 index c93b4ba4b9..0000000000 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include - -namespace AtomToolsFramework -{ - //! AtomToolsMainWindowFactoryRequestBus provides - class AtomToolsMainWindowFactoryRequests : public AZ::EBusTraits - { - public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - - /// Creates and shows main window - virtual void CreateMainWindow() = 0; - - //! Destroys main window and releases all cached assets - virtual void DestroyMainWindow() = 0; - }; - using AtomToolsMainWindowFactoryRequestBus = AZ::EBus; - -} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h index cadd3440d9..996396aaa2 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h @@ -16,7 +16,8 @@ namespace AtomToolsFramework { public: static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + typedef AZ::Crc32 BusIdType; virtual void OnMainWindowClosing(){}; }; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h index cb63ff295c..e744ac92ed 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h @@ -16,12 +16,14 @@ class QWidget; namespace AtomToolsFramework { - //! AtomToolsMainWindowRequestBus provides + //! AtomToolsMainWindowRequestBus provides an interface to common main application window functions like adding docked windows, + //! resizing the viewport, and other operations class AtomToolsMainWindowRequests : public AZ::EBusTraits { public: - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + typedef AZ::Crc32 BusIdType; //! Bring main window to foreground virtual void ActivateWindow() = 0; @@ -58,6 +60,7 @@ namespace AtomToolsFramework //! Releases the viewport's render target resolution lock, allowing it to match the viewport widget again. virtual void UnlockViewportRenderTargetSize() {}; }; + using AtomToolsMainWindowRequestBus = AZ::EBus; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index 4ba1d04b71..72d7cbf100 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -9,7 +9,6 @@ #include #include #include -#include #include #include @@ -46,26 +45,16 @@ AZ_POP_DISABLE_WARNING namespace AtomToolsFramework { - AZStd::string AtomToolsApplication::GetBuildTargetName() const - { - return AZStd::string("AtomTools"); - } - - const char* AtomToolsApplication::GetCurrentConfigurationName() const - { -#if defined(_RELEASE) - return "ReleaseAtomTools"; -#elif defined(_DEBUG) - return "DebugAtomTools"; -#else - return "ProfileAtomTools"; -#endif - } - - AtomToolsApplication::AtomToolsApplication(int* argc, char*** argv) + AtomToolsApplication::AtomToolsApplication(const AZStd::string& targetName, int* argc, char*** argv) : Application(argc, argv) , AzQtApplication(*argc, *argv) + , m_targetName(targetName) + , m_toolId(targetName) { + // The settings registry has been created at this point, so add the CMake target + AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization( + *AZ::SettingsRegistry::Get(), m_targetName); + // Suppress spam from the Source Control system m_traceLogger.AddWindowFilter(AzToolsFramework::SCC_WINDOW); @@ -80,18 +69,26 @@ namespace AtomToolsFramework m_styleManager.reset(new AzQtComponents::StyleManager(this)); m_styleManager->initialize(this, engineRootPath); - m_timer.setInterval(1); + const AZ::u64 updateIntervalWhenActive = + GetSettingOrDefault("/O3DE/AtomToolsFramework/Application/UpdateIntervalWhenActive", 1); + const AZ::u64 updateIntervalWhenNotActive = + GetSettingOrDefault("/O3DE/AtomToolsFramework/Application/UpdateIntervalWhenNotActive", 64); + + m_timer.setInterval(updateIntervalWhenActive); connect(&m_timer, &QTimer::timeout, this, [this]() { this->PumpSystemEventLoopUntilEmpty(); this->Tick(); }); - connect(this, &QGuiApplication::applicationStateChanged, this, [this]() + connect(this, &QGuiApplication::applicationStateChanged, this, [this, updateIntervalWhenActive, updateIntervalWhenNotActive]() { // Limit the update interval when not in focus to reduce power consumption and interference with other applications - this->m_timer.setInterval((applicationState() & Qt::ApplicationActive) ? 1 : 32); + this->m_timer.setInterval( + (applicationState() & Qt::ApplicationActive) ? updateIntervalWhenActive : updateIntervalWhenNotActive); }); + + AtomToolsMainWindowNotificationBus::Handler::BusConnect(m_toolId); } AtomToolsApplication ::~AtomToolsApplication() @@ -108,6 +105,17 @@ namespace AtomToolsFramework GetSerializeContext()->CreateEditContext(); } + const char* AtomToolsApplication::GetCurrentConfigurationName() const + { +#if defined(_RELEASE) + return "ReleaseAtomTools"; +#elif defined(_DEBUG) + return "DebugAtomTools"; +#else + return "ProfileAtomTools"; +#endif + } + void AtomToolsApplication::Reflect(AZ::ReflectContext* context) { Base::Reflect(context); @@ -181,7 +189,7 @@ namespace AtomToolsFramework Base::StartCommon(systemEntity); const bool clearLogFile = GetSettingOrDefault("/O3DE/AtomToolsFramework/Application/ClearLogOnStart", false); - m_traceLogger.OpenLogFile(GetBuildTargetName() + ".log", clearLogFile); + m_traceLogger.OpenLogFile(m_targetName + ".log", clearLogFile); ConnectToAssetProcessor(); @@ -200,9 +208,6 @@ namespace AtomToolsFramework LoadSettings(); - AtomToolsMainWindowNotificationBus::Handler::BusConnect(); - AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::CreateMainWindow); - auto editorPythonEventsInterface = AZ::Interface::Get(); if (editorPythonEventsInterface) { @@ -218,16 +223,22 @@ namespace AtomToolsFramework m_timer.start(); } - void AtomToolsApplication::OnMainWindowClosing() + void AtomToolsApplication::Tick() { - ExitMainLoop(); + TickSystem(); + Base::Tick(); + + if (WasExitMainLoopRequested()) + { + m_timer.disconnect(); + quit(); + } } void AtomToolsApplication::Destroy() { - // before modules are unloaded, destroy UI to free up any assets it cached - AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::DestroyMainWindow); m_styleManager.reset(); + UnloadSettings(); AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); @@ -241,6 +252,11 @@ namespace AtomToolsFramework #endif } + void AtomToolsApplication::OnMainWindowClosing() + { + ExitMainLoop(); + } + AZStd::vector AtomToolsApplication::GetCriticalAssetFilters() const { return AZStd::vector({}); @@ -255,14 +271,12 @@ namespace AtomToolsFramework // and able to negotiate a connection when running a debug build // and to negotiate a connection - const auto targetName = GetBuildTargetName(); - AzFramework::AssetSystem::ConnectionSettings connectionSettings; AzFramework::AssetSystem::ReadConnectionSettingsFromSettingsRegistry(connectionSettings); connectionSettings.m_connectionDirection = AzFramework::AssetSystem::ConnectionSettings::ConnectionDirection::ConnectToAssetProcessor; - connectionSettings.m_connectionIdentifier = targetName; - connectionSettings.m_loggingCallback = [targetName]([[maybe_unused]] AZStd::string_view logData) + connectionSettings.m_connectionIdentifier = m_targetName; + connectionSettings.m_loggingCallback = [targetName = m_targetName]([[maybe_unused]] AZStd::string_view logData) { AZ_UNUSED(targetName); // Prevent unused warning in release builds AZ_TracePrintf(targetName.c_str(), "%.*s", aznumeric_cast(logData.size()), logData.data()); @@ -279,7 +293,7 @@ namespace AtomToolsFramework void AtomToolsApplication::CompileCriticalAssets() { - AZ_TracePrintf(GetBuildTargetName().c_str(), "Compiling critical assets.\n"); + AZ_TracePrintf(m_targetName.c_str(), "Compiling critical assets.\n"); QStringList failedAssets; @@ -288,7 +302,7 @@ namespace AtomToolsFramework // So the asset id won't be found right after CompileAssetSync call. for (const AZStd::string& assetFilters : GetCriticalAssetFilters()) { - AZ_TracePrintf(GetBuildTargetName().c_str(), "Compiling critical asset matching: %s.\n", assetFilters.c_str()); + AZ_TracePrintf(m_targetName.c_str(), "Compiling critical asset matching: %s.\n", assetFilters.c_str()); // Wait for the asset be compiled AzFramework::AssetSystem::AssetStatus status = AzFramework::AssetSystem::AssetStatus_Unknown; @@ -335,7 +349,7 @@ namespace AtomToolsFramework AZ_Assert(context, "No serialize context"); char resolvedPath[AZ_MAX_PATH_LEN] = ""; - AZStd::string fileName = "@user@/" + GetBuildTargetName() + "UserSettings.xml"; + AZStd::string fileName = "@user@/" + m_targetName + "UserSettings.xml"; AZ::IO::FileIOBase::GetInstance()->ResolvePath( fileName.c_str(), resolvedPath, AZ_ARRAY_SIZE(resolvedPath)); @@ -350,7 +364,7 @@ namespace AtomToolsFramework AZ_Assert(context, "No serialize context"); char resolvedPath[AZ_MAX_PATH_LEN] = ""; - AZStd::string fileName = "@user@/" + GetBuildTargetName() + "UserSettings.xml"; + AZStd::string fileName = "@user@/" + m_targetName + "UserSettings.xml"; AZ::IO::FileIOBase::GetInstance()->ResolvePath(fileName.c_str(), resolvedPath, AZ_MAX_PATH_LEN); @@ -376,8 +390,7 @@ namespace AtomToolsFramework const AZStd::string activateWindowSwitchName = "activatewindow"; if (commandLine.HasSwitch(activateWindowSwitchName)) { - AtomToolsFramework::AtomToolsMainWindowRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsMainWindowRequestBus::Handler::ActivateWindow); + AtomToolsMainWindowRequestBus::Event(m_toolId, &AtomToolsMainWindowRequestBus::Handler::ActivateWindow); } const AZStd::string timeoputSwitchName = "timeout"; @@ -385,14 +398,11 @@ namespace AtomToolsFramework { const AZStd::string& timeoutValue = commandLine.GetSwitchValue(timeoputSwitchName, 0); const uint32_t timeoutInMs = atoi(timeoutValue.c_str()); - AZ_Printf(GetBuildTargetName().c_str(), "Timeout scheduled, shutting down in %u ms", timeoutInMs); - QTimer::singleShot( - timeoutInMs, - [this] - { - AZ_Printf(GetBuildTargetName().c_str(), "Timeout reached, shutting down"); - ExitMainLoop(); - }); + AZ_Printf(m_targetName.c_str(), "Timeout scheduled, shutting down in %u ms", timeoutInMs); + QTimer::singleShot(timeoutInMs, [this] { + AZ_Printf(m_targetName.c_str(), "Timeout reached, shutting down"); + ExitMainLoop(); + }); } // Process command line options for running one or more python scripts on startup @@ -403,7 +413,7 @@ namespace AtomToolsFramework const AZStd::string runPythonScriptPath = commandLine.GetSwitchValue(runPythonScriptSwitchName, runPythonScriptIndex); AZStd::vector runPythonArgs; - AZ_Printf(GetBuildTargetName().c_str(), "Launching script: %s", runPythonScriptPath.c_str()); + AZ_Printf(m_targetName.c_str(), "Launching script: %s", runPythonScriptPath.c_str()); AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast( &AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByFilenameWithArgs, runPythonScriptPath, runPythonArgs); } @@ -486,27 +496,6 @@ namespace AtomToolsFramework return false; } - void AtomToolsApplication::Tick() - { - TickSystem(); - Base::Tick(); - - if (WasExitMainLoopRequested()) - { - m_timer.disconnect(); - quit(); - } - } - - void AtomToolsApplication::Stop() - { - AtomToolsMainWindowFactoryRequestBus::Broadcast(&AtomToolsMainWindowFactoryRequestBus::Handler::DestroyMainWindow); - m_styleManager.reset(); - - UnloadSettings(); - Base::Stop(); - } - void AtomToolsApplication::QueryApplicationType(AZ::ApplicationTypeQuery& appType) const { appType.m_maskValue = AZ::ApplicationTypeQuery::Masks::Tool; @@ -524,7 +513,7 @@ namespace AtomToolsFramework for (auto& line : lines) { - AZ_TracePrintf(GetBuildTargetName().c_str(), "Python: %s\n", line.c_str()); + AZ_TracePrintf(m_targetName.c_str(), "Python: %s\n", line.c_str()); } #endif } @@ -537,7 +526,7 @@ namespace AtomToolsFramework void AtomToolsApplication::OnExceptionMessage([[maybe_unused]] AZStd::string_view message) { - AZ_Error(GetBuildTargetName().c_str(), false, "Python: " AZ_STRING_FORMAT, AZ_STRING_ARG(message)); + AZ_Error(m_targetName.c_str(), false, "Python: " AZ_STRING_FORMAT, AZ_STRING_ARG(message)); } // Copied from PyIdleWaitFrames in CryEdit.cpp @@ -577,6 +566,8 @@ namespace AtomToolsFramework void AtomToolsApplication::PyExit() { - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop); + QTimer::singleShot(0, []() { + AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::ExitMainLoop); + }); } } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AssetBrowser/AtomToolsAssetBrowser.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AssetBrowser/AtomToolsAssetBrowser.cpp index 8394efa46f..81bdaf380f 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AssetBrowser/AtomToolsAssetBrowser.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AssetBrowser/AtomToolsAssetBrowser.cpp @@ -89,13 +89,14 @@ namespace AtomToolsFramework void AtomToolsAssetBrowser::SelectEntries(const AZStd::string& absolutePath) { - if (!absolutePath.empty()) + AZ::TickBus::Handler::BusDisconnect(); + + m_pathToSelect = absolutePath; + if (!m_pathToSelect.empty() && AzFramework::StringFunc::Path::Normalize(m_pathToSelect)) { // Selecting a new asset in the browser is not guaranteed to happen immediately. // The asset browser model notifications are sent before the model is updated. // Instead of relying on the notifications, queue the selection and process it on tick until this change occurs. - m_pathToSelect = absolutePath; - AzFramework::StringFunc::Path::Normalize(m_pathToSelect); AZ::TickBus::Handler::BusConnect(); } } @@ -201,25 +202,29 @@ namespace AtomToolsFramework AZ_UNUSED(time); AZ_UNUSED(deltaTime); - if (!m_pathToSelect.empty()) + if (m_pathToSelect.empty()) { - // Attempt to select the new path - AzToolsFramework::AssetBrowser::AssetBrowserViewRequestBus::Broadcast( - &AzToolsFramework::AssetBrowser::AssetBrowserViewRequestBus::Events::SelectFileAtPath, m_pathToSelect); + AZ::TickBus::Handler::BusDisconnect(); + m_pathToSelect.clear(); + return; + } - // Iterate over the selected entries to verify if the selection was made - for (const AssetBrowserEntry* entry : m_ui->m_assetBrowserTreeViewWidget->GetSelectedAssets()) + // Attempt to select the new path + AzToolsFramework::AssetBrowser::AssetBrowserViewRequestBus::Broadcast( + &AzToolsFramework::AssetBrowser::AssetBrowserViewRequestBus::Events::SelectFileAtPath, m_pathToSelect); + + // Iterate over the selected entries to verify if the selection was made + for (const AssetBrowserEntry* entry : m_ui->m_assetBrowserTreeViewWidget->GetSelectedAssets()) + { + if (entry) { - if (entry) + AZStd::string sourcePath = entry->GetFullPath(); + AzFramework::StringFunc::Path::Normalize(sourcePath); + if (m_pathToSelect == sourcePath) { - AZStd::string sourcePath = entry->GetFullPath(); - AzFramework::StringFunc::Path::Normalize(sourcePath); - if (m_pathToSelect == sourcePath) - { - // Once the selection is confirmed, cancel the operation and disconnect - AZ::TickBus::Handler::BusDisconnect(); - m_pathToSelect.clear(); - } + // Once the selection is confirmed, cancel the operation and disconnect + AZ::TickBus::Handler::BusDisconnect(); + m_pathToSelect.clear(); } } } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp index 978ac52cca..a67e00a955 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/AtomToolsFrameworkModule.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -19,7 +18,6 @@ namespace AtomToolsFramework { m_descriptors.insert(m_descriptors.end(), { AtomToolsFrameworkSystemComponent::CreateDescriptor(), - AtomToolsDocumentSystemComponent::CreateDescriptor(), AtomToolsMainWindowSystemComponent::CreateDescriptor(), PerformanceMonitorSystemComponent::CreateDescriptor(), PreviewRendererSystemComponent::CreateDescriptor(), @@ -30,7 +28,6 @@ namespace AtomToolsFramework { return AZ::ComponentTypeList{ azrtti_typeid(), - azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp index 2660a1e8fb..d99369958c 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocument.cpp @@ -13,17 +13,18 @@ namespace AtomToolsFramework { - AtomToolsDocument::AtomToolsDocument() + AtomToolsDocument::AtomToolsDocument(const AZ::Crc32& toolId) + : m_toolId(toolId) { AtomToolsDocumentRequestBus::Handler::BusConnect(m_id); - AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentCreated, m_id); + AtomToolsDocumentNotificationBus::Event(m_toolId, &AtomToolsDocumentNotificationBus::Events::OnDocumentCreated, m_id); } AtomToolsDocument::~AtomToolsDocument() { - AzToolsFramework::AssetSystemBus::Handler::BusDisconnect(); - AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentDestroyed, m_id); + AtomToolsDocumentNotificationBus::Event(m_toolId, &AtomToolsDocumentNotificationBus::Events::OnDocumentDestroyed, m_id); AtomToolsDocumentRequestBus::Handler::BusDisconnect(); + AzToolsFramework::AssetSystemBus::Handler::BusDisconnect(); } const AZ::Uuid& AtomToolsDocument::GetId() const @@ -80,10 +81,10 @@ namespace AtomToolsFramework return false; } - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentModified, m_id); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentModified, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); return true; } @@ -169,8 +170,8 @@ namespace AtomToolsFramework AZ_TracePrintf("AtomToolsDocument", "Document closed: '%s'.\n", m_absolutePath.c_str()); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentClosed, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentClosed, m_id); // Clearing after notification so paths are still available Clear(); @@ -211,8 +212,8 @@ namespace AtomToolsFramework // The history index is one beyond the last executed command. Decrement the index then execute undo. m_undoHistory[--m_undoHistoryIndex].first(); AZ_TracePrintf("AtomToolsDocument", "Document undo: '%s'.\n", m_absolutePath.c_str()); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); return true; } return false; @@ -225,8 +226,8 @@ namespace AtomToolsFramework // Execute the current redo command then move the history index to the next position. m_undoHistory[m_undoHistoryIndex++].second(); AZ_TracePrintf("AtomToolsDocument", "Document redo: '%s'.\n", m_absolutePath.c_str()); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); return true; } return false; @@ -259,8 +260,8 @@ namespace AtomToolsFramework { AZ_TracePrintf("AtomToolsDocument", "Document opened: '%s'.\n", m_absolutePath.c_str()); AzToolsFramework::AssetSystemBus::Handler::BusConnect(); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, m_id); return true; } @@ -282,8 +283,8 @@ namespace AtomToolsFramework &AzToolsFramework::SourceControlCommandBus::Events::RequestEdit, m_savePathNormalized.c_str(), true, [](bool, const AzToolsFramework::SourceControlFileInfo&) {}); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentSaved, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentSaved, m_id); return true; } @@ -319,8 +320,8 @@ namespace AtomToolsFramework // Assign the index to the end of history m_undoHistoryIndex = aznumeric_cast(m_undoHistory.size()); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentUndoStateChanged, m_id); } void AtomToolsDocument::SourceFileChanged(AZStd::string relativePath, AZStd::string scanFolder, [[maybe_unused]] AZ::Uuid sourceUUID) @@ -333,16 +334,16 @@ namespace AtomToolsFramework if (!m_ignoreSourceFileChangeToSelf) { AZ_TracePrintf("AtomToolsDocument", "Document changed externally: '%s'.\n", m_absolutePath.c_str()); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentExternallyModified, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentExternallyModified, m_id); } m_ignoreSourceFileChangeToSelf = false; } else if (m_sourceDependencies.find(sourcePath) != m_sourceDependencies.end()) { AZ_TracePrintf("AtomToolsDocument", "Document dependency changed: '%s'.\n", m_absolutePath.c_str()); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentDependencyModified, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentDependencyModified, m_id); } } diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentApplication.cpp index beb414bb6c..c4eb89e7d1 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentApplication.cpp @@ -11,11 +11,29 @@ namespace AtomToolsFramework { - AtomToolsDocumentApplication::AtomToolsDocumentApplication(int* argc, char*** argv) - : Base(argc, argv) + AtomToolsDocumentApplication::AtomToolsDocumentApplication(const AZStd::string& targetName, int* argc, char*** argv) + : Base(targetName, argc, argv) { } + void AtomToolsDocumentApplication::Reflect(AZ::ReflectContext* context) + { + Base::Reflect(context); + AtomToolsDocumentSystem::Reflect(context); + } + + void AtomToolsDocumentApplication::StartCommon(AZ::Entity* systemEntity) + { + Base::StartCommon(systemEntity); + m_documentSystem.reset(aznew AtomToolsDocumentSystem(m_toolId)); + } + + void AtomToolsDocumentApplication::Destroy() + { + m_documentSystem.reset(); + Base::Destroy(); + } + void AtomToolsDocumentApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) { // Process command line options for opening documents on startup @@ -24,8 +42,8 @@ namespace AtomToolsFramework { const AZStd::string openDocumentPath = commandLine.GetMiscValue(openDocumentIndex); - AZ_Printf(GetBuildTargetName().c_str(), "Opening document: %s", openDocumentPath.c_str()); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); + AZ_Printf(m_targetName.c_str(), "Opening document: %s", openDocumentPath.c_str()); + AtomToolsDocumentSystemRequestBus::Event(m_toolId, &AtomToolsDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); } Base::ProcessCommandLine(commandLine); diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentMainWindow.cpp index e8be20097f..f2db527ea8 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentMainWindow.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentMainWindow.cpp @@ -25,13 +25,13 @@ AZ_POP_DISABLE_WARNING namespace AtomToolsFramework { - AtomToolsDocumentMainWindow::AtomToolsDocumentMainWindow(QWidget* parent /* = 0 */) - : AtomToolsMainWindow(parent) + AtomToolsDocumentMainWindow::AtomToolsDocumentMainWindow(const AZ::Crc32& toolId, QWidget* parent /* = 0 */) + : AtomToolsMainWindow(toolId, parent) { setObjectName("AtomToolsDocumentMainWindow"); AddDocumentMenus(); AddDocumentTabBar(); - AtomToolsDocumentNotificationBus::Handler::BusConnect(); + AtomToolsDocumentNotificationBus::Handler::BusConnect(m_toolId); } AtomToolsDocumentMainWindow::~AtomToolsDocumentMainWindow() @@ -49,8 +49,8 @@ namespace AtomToolsFramework AZStd::string savePath; if (GetCreateDocumentParams(openPath, savePath)) { - AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, openPath, savePath); + AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, openPath, savePath); } }, QKeySequence::New); m_menuFile->insertAction(insertPostion, m_actionNew); @@ -59,7 +59,7 @@ namespace AtomToolsFramework AZStd::string openPath; if (GetOpenDocumentParams(openPath)) { - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::OpenDocument, openPath); + AtomToolsDocumentSystemRequestBus::Event(m_toolId, &AtomToolsDocumentSystemRequestBus::Events::OpenDocument, openPath); } }, QKeySequence::Open); m_menuFile->insertAction(insertPostion, m_actionOpen); @@ -68,7 +68,8 @@ namespace AtomToolsFramework m_actionSave = CreateAction("&Save", [this]() { const AZ::Uuid documentId = GetDocumentTabId(m_tabWidget->currentIndex()); bool result = false; - AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsDocumentSystemRequestBus::Events::SaveDocument, documentId); + AtomToolsDocumentSystemRequestBus::EventResult( + result, m_toolId, &AtomToolsDocumentSystemRequestBus::Events::SaveDocument, documentId); if (!result) { SetStatusError(tr("Document save failed: %1").arg(GetDocumentPath(documentId))); @@ -81,8 +82,9 @@ namespace AtomToolsFramework const QString documentPath = GetDocumentPath(documentId); bool result = false; - AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsCopy, - documentId, GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); + AtomToolsDocumentSystemRequestBus::EventResult( + result, m_toolId, &AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsCopy, documentId, + GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { SetStatusError(tr("Document save failed: %1").arg(GetDocumentPath(documentId))); @@ -95,8 +97,9 @@ namespace AtomToolsFramework const QString documentPath = GetDocumentPath(documentId); bool result = false; - AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsChild, - documentId, GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); + AtomToolsDocumentSystemRequestBus::EventResult( + result, m_toolId, &AtomToolsDocumentSystemRequestBus::Events::SaveDocumentAsChild, documentId, + GetSaveFileInfo(documentPath).absoluteFilePath().toUtf8().constData()); if (!result) { SetStatusError(tr("Document save failed: %1").arg(GetDocumentPath(documentId))); @@ -106,7 +109,8 @@ namespace AtomToolsFramework m_actionSaveAll = CreateAction("Save A&ll", [this]() { bool result = false; - AtomToolsDocumentSystemRequestBus::BroadcastResult(result, &AtomToolsDocumentSystemRequestBus::Events::SaveAllDocuments); + AtomToolsDocumentSystemRequestBus::EventResult( + result, m_toolId, &AtomToolsDocumentSystemRequestBus::Events::SaveAllDocuments); if (!result) { SetStatusError(tr("Document save all failed")); @@ -117,18 +121,19 @@ namespace AtomToolsFramework m_actionClose = CreateAction("&Close", [this]() { const AZ::Uuid documentId = GetDocumentTabId(m_tabWidget->currentIndex()); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); + AtomToolsDocumentSystemRequestBus::Event(m_toolId, &AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); }, QKeySequence::Close); m_menuFile->insertAction(insertPostion, m_actionClose); - m_actionCloseAll = CreateAction("Close All", []() { - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments); + m_actionCloseAll = CreateAction("Close All", [this]() { + AtomToolsDocumentSystemRequestBus::Event(m_toolId, &AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments); }); m_menuFile->insertAction(insertPostion, m_actionCloseAll); m_actionCloseOthers = CreateAction("Close Others", [this]() { const AZ::Uuid documentId = GetDocumentTabId(m_tabWidget->currentIndex()); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); + AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); }); m_menuFile->insertAction(insertPostion, m_actionCloseOthers); m_menuFile->insertSeparator(insertPostion); @@ -194,12 +199,12 @@ namespace AtomToolsFramework // This should automatically clear the active document connect(m_tabWidget, &QTabWidget::currentChanged, this, [this](int tabIndex) { const AZ::Uuid documentId = GetDocumentTabId(tabIndex); - AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); + AtomToolsDocumentNotificationBus::Event(m_toolId,&AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); }); connect(m_tabWidget, &QTabWidget::tabCloseRequested, this, [this](int tabIndex) { const AZ::Uuid documentId = GetDocumentTabId(tabIndex); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); + AtomToolsDocumentSystemRequestBus::Event(m_toolId, &AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); }); // Add context menu for right-clicking on tabs @@ -341,15 +346,18 @@ namespace AtomToolsFramework const QString selectActionName = (currentTabIndex == clickedTabIndex) ? "Select in Browser" : "Select"; tabMenu.addAction(selectActionName, [this, clickedTabIndex]() { const AZ::Uuid documentId = GetDocumentTabId(clickedTabIndex); - AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); + AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); }); tabMenu.addAction("Close", [this, clickedTabIndex]() { const AZ::Uuid documentId = GetDocumentTabId(clickedTabIndex); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); + AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); }); auto closeOthersAction = tabMenu.addAction("Close Others", [this, clickedTabIndex]() { const AZ::Uuid documentId = GetDocumentTabId(clickedTabIndex); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); + AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsDocumentSystemRequestBus::Events::CloseAllDocumentsExcept, documentId); }); closeOthersAction->setEnabled(tabBar->count() > 1); tabMenu.exec(QCursor::pos()); @@ -472,14 +480,14 @@ namespace AtomToolsFramework void AtomToolsDocumentMainWindow::closeEvent(QCloseEvent* closeEvent) { bool didClose = true; - AtomToolsDocumentSystemRequestBus::BroadcastResult(didClose, &AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments); + AtomToolsDocumentSystemRequestBus::EventResult(didClose, m_toolId, &AtomToolsDocumentSystemRequestBus::Events::CloseAllDocuments); if (!didClose) { closeEvent->ignore(); return; } - AtomToolsMainWindowNotificationBus::Broadcast(&AtomToolsMainWindowNotifications::OnMainWindowClosing); + AtomToolsMainWindowNotificationBus::Event(m_toolId, &AtomToolsMainWindowNotifications::OnMainWindowClosing); } template diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystem.cpp similarity index 65% rename from Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp rename to Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystem.cpp index 329bc1b1b3..2254e92490 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystemComponent.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Document/AtomToolsDocumentSystem.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -17,7 +18,6 @@ #include #include #include -#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -28,20 +28,16 @@ AZ_POP_DISABLE_WARNING namespace AtomToolsFramework { - AtomToolsDocumentSystemComponent::AtomToolsDocumentSystemComponent() + void AtomToolsDocumentSystem::Reflect(AZ::ReflectContext* context) { - } - - void AtomToolsDocumentSystemComponent::Reflect(AZ::ReflectContext* context) - { - if (AZ::SerializeContext* serialize = azrtti_cast(context)) + if (auto serialize = azrtti_cast(context)) { - serialize->Class() + serialize->Class() ->Version(0); - if (AZ::EditContext* ec = serialize->GetEditContext()) + if (auto editContext = serialize->GetEditContext()) { - ec->Class("AtomToolsDocumentSystemComponent", "") + editContext->Class("AtomToolsDocumentSystem", "") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("System")) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) @@ -49,7 +45,7 @@ namespace AtomToolsFramework } } - if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) + if (auto behaviorContext = azrtti_cast(context)) { behaviorContext->EBus("AtomToolsDocumentSystemRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) @@ -93,40 +89,26 @@ namespace AtomToolsFramework } } - void AtomToolsDocumentSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + AtomToolsDocumentSystem::AtomToolsDocumentSystem(const AZ::Crc32& toolId) + : m_toolId(toolId) { - provided.push_back(AZ_CRC_CE("AtomToolsDocumentSystemService")); + AtomToolsDocumentSystemRequestBus::Handler::BusConnect(m_toolId); + AtomToolsDocumentNotificationBus::Handler::BusConnect(m_toolId); } - void AtomToolsDocumentSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC_CE("AtomToolsDocumentSystemService")); - } - - void AtomToolsDocumentSystemComponent::Init() - { - } - - void AtomToolsDocumentSystemComponent::Activate() + AtomToolsDocumentSystem::~AtomToolsDocumentSystem() { m_documentMap.clear(); - AtomToolsDocumentSystemRequestBus::Handler::BusConnect(); - AtomToolsDocumentNotificationBus::Handler::BusConnect(); - } - - void AtomToolsDocumentSystemComponent::Deactivate() - { AtomToolsDocumentNotificationBus::Handler::BusDisconnect(); AtomToolsDocumentSystemRequestBus::Handler::BusDisconnect(); - m_documentMap.clear(); } - void AtomToolsDocumentSystemComponent::RegisterDocumentType(AZStd::function documentCreator) + void AtomToolsDocumentSystem::RegisterDocumentType(const AtomToolsDocumentFactoryCallback& documentCreator) { m_documentCreator = documentCreator; } - AZ::Uuid AtomToolsDocumentSystemComponent::CreateDocument() + AZ::Uuid AtomToolsDocumentSystem::CreateDocument() { if (!m_documentCreator) { @@ -134,7 +116,7 @@ namespace AtomToolsFramework return AZ::Uuid::CreateNull(); } - AZStd::unique_ptr document(m_documentCreator()); + AZStd::unique_ptr document(m_documentCreator(m_toolId)); if (!document) { AZ_Error("AtomToolsDocument", false, "Failed to create new document"); @@ -146,112 +128,17 @@ namespace AtomToolsFramework return documentId; } - bool AtomToolsDocumentSystemComponent::DestroyDocument(const AZ::Uuid& documentId) + bool AtomToolsDocumentSystem::DestroyDocument(const AZ::Uuid& documentId) { return m_documentMap.erase(documentId) != 0; } - void AtomToolsDocumentSystemComponent::OnDocumentExternallyModified(const AZ::Uuid& documentId) - { - m_documentIdsWithExternalChanges.insert(documentId); - QueueReopenDocuments(); - } - - void AtomToolsDocumentSystemComponent::OnDocumentDependencyModified(const AZ::Uuid& documentId) - { - m_documentIdsWithDependencyChanges.insert(documentId); - QueueReopenDocuments(); - } - - void AtomToolsDocumentSystemComponent::QueueReopenDocuments() - { - if (!m_queueReopenDocuments) - { - m_queueReopenDocuments = true; - QTimer::singleShot(0, [this] { ReopenDocuments(); }); - } - } - - void AtomToolsDocumentSystemComponent::ReopenDocuments() - { - const bool enableHotReload = GetSettingOrDefault("/O3DE/AtomToolsFramework/DocumentSystem/EnableHotReload", true); - if (!enableHotReload) - { - m_documentIdsWithDependencyChanges.clear(); - m_documentIdsWithExternalChanges.clear(); - m_queueReopenDocuments = false; - } - - const bool enableHotReloadPrompts = - GetSettingOrDefault("/O3DE/AtomToolsFramework/DocumentSystem/EnableHotReloadPrompts", true); - - for (const AZ::Uuid& documentId : m_documentIdsWithExternalChanges) - { - m_documentIdsWithDependencyChanges.erase(documentId); - - AZStd::string documentPath; - AtomToolsDocumentRequestBus::EventResult(documentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); - - if (enableHotReloadPrompts && - (QMessageBox::question(QApplication::activeWindow(), - QString("Document was externally modified"), - QString("Would you like to reopen the document:\n%1?").arg(documentPath.c_str()), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) - { - continue; - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - bool openResult = false; - AtomToolsDocumentRequestBus::EventResult(openResult, documentId, &AtomToolsDocumentRequestBus::Events::Open, documentPath); - if (!openResult) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Document could not be opened"), - QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); - } - } - - for (const AZ::Uuid& documentId : m_documentIdsWithDependencyChanges) - { - AZStd::string documentPath; - AtomToolsDocumentRequestBus::EventResult(documentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); - - if (enableHotReloadPrompts && - (QMessageBox::question(QApplication::activeWindow(), - QString("Document dependencies have changed"), - QString("Would you like to update the document with these changes:\n%1?").arg(documentPath.c_str()), - QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) - { - continue; - } - - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - - bool openResult = false; - AtomToolsDocumentRequestBus::EventResult(openResult, documentId, &AtomToolsDocumentRequestBus::Events::Reopen); - if (!openResult) - { - QMessageBox::critical( - QApplication::activeWindow(), QString("Document could not be opened"), - QString("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::CloseDocument, documentId); - } - } - - m_documentIdsWithDependencyChanges.clear(); - m_documentIdsWithExternalChanges.clear(); - m_queueReopenDocuments = false; - } - - AZ::Uuid AtomToolsDocumentSystemComponent::OpenDocument(AZStd::string_view sourcePath) + AZ::Uuid AtomToolsDocumentSystem::OpenDocument(AZStd::string_view sourcePath) { return OpenDocumentImpl(sourcePath, true); } - AZ::Uuid AtomToolsDocumentSystemComponent::CreateDocumentFromFile(AZStd::string_view sourcePath, AZStd::string_view targetPath) + AZ::Uuid AtomToolsDocumentSystem::CreateDocumentFromFile(AZStd::string_view sourcePath, AZStd::string_view targetPath) { const AZ::Uuid documentId = OpenDocumentImpl(sourcePath, false); if (documentId.IsNull()) @@ -266,18 +153,18 @@ namespace AtomToolsFramework } // Send document open notification after creating new one - AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); + AtomToolsDocumentNotificationBus::Event(m_toolId, &AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentId); return documentId; } - bool AtomToolsDocumentSystemComponent::CloseDocument(const AZ::Uuid& documentId) + bool AtomToolsDocumentSystem::CloseDocument(const AZ::Uuid& documentId) { bool isOpen = false; AtomToolsDocumentRequestBus::EventResult(isOpen, documentId, &AtomToolsDocumentRequestBus::Events::IsOpen); if (!isOpen) { // immediately destroy unopened documents - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::DestroyDocument, documentId); + DestroyDocument(documentId); return true; } @@ -289,8 +176,8 @@ namespace AtomToolsFramework if (isModified) { auto selection = QMessageBox::question(QApplication::activeWindow(), - QString("Document has unsaved changes"), - QString("Do you want to save changes to\n%1?").arg(documentPath.c_str()), + QObject::tr("Document has unsaved changes"), + QObject::tr("Do you want to save changes to\n%1?").arg(documentPath.c_str()), QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (selection == QMessageBox::Cancel) { @@ -307,23 +194,24 @@ namespace AtomToolsFramework } } - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + TraceRecorder traceRecorder(m_maxMessageBoxLineCount); bool closeResult = true; AtomToolsDocumentRequestBus::EventResult(closeResult, documentId, &AtomToolsDocumentRequestBus::Events::Close); if (!closeResult) { QMessageBox::critical( - QApplication::activeWindow(), QString("Document could not be closed"), - QString("Failed to close: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + QApplication::activeWindow(), + QObject::tr("Document could not be closed"), + QObject::tr("Failed to close: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); return false; } - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::DestroyDocument, documentId); + DestroyDocument(documentId); return true; } - bool AtomToolsDocumentSystemComponent::CloseAllDocuments() + bool AtomToolsDocumentSystem::CloseAllDocuments() { bool result = true; auto documentMap = m_documentMap; @@ -338,7 +226,7 @@ namespace AtomToolsFramework return result; } - bool AtomToolsDocumentSystemComponent::CloseAllDocumentsExcept(const AZ::Uuid& documentId) + bool AtomToolsDocumentSystem::CloseAllDocumentsExcept(const AZ::Uuid& documentId) { bool result = true; auto documentMap = m_documentMap; @@ -356,7 +244,7 @@ namespace AtomToolsFramework return result; } - bool AtomToolsDocumentSystemComponent::SaveDocument(const AZ::Uuid& documentId) + bool AtomToolsDocumentSystem::SaveDocument(const AZ::Uuid& documentId) { AZStd::string saveDocumentPath; AtomToolsDocumentRequestBus::EventResult(saveDocumentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); @@ -369,26 +257,30 @@ namespace AtomToolsFramework const QFileInfo saveInfo(saveDocumentPath.c_str()); if (saveInfo.exists() && !saveInfo.isWritable()) { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); + QMessageBox::critical( + QApplication::activeWindow(), + QObject::tr("Document could not be saved"), + QObject::tr("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); return false; } - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + TraceRecorder traceRecorder(m_maxMessageBoxLineCount); bool result = false; AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsDocumentRequestBus::Events::Save); if (!result) { QMessageBox::critical( - QApplication::activeWindow(), QString("Document could not be saved"), - QString("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + QApplication::activeWindow(), + QObject::tr("Document could not be saved"), + QObject::tr("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); return false; } return true; } - bool AtomToolsDocumentSystemComponent::SaveDocumentAsCopy(const AZ::Uuid& documentId, AZStd::string_view targetPath) + bool AtomToolsDocumentSystem::SaveDocumentAsCopy(const AZ::Uuid& documentId, AZStd::string_view targetPath) { AZStd::string saveDocumentPath = targetPath; if (saveDocumentPath.empty() || !AzFramework::StringFunc::Path::Normalize(saveDocumentPath)) @@ -399,26 +291,29 @@ namespace AtomToolsFramework const QFileInfo saveInfo(saveDocumentPath.c_str()); if (saveInfo.exists() && !saveInfo.isWritable()) { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); + QMessageBox::critical(QApplication::activeWindow(), + QObject::tr("Document could not be saved"), + QObject::tr("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); return false; } - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + TraceRecorder traceRecorder(m_maxMessageBoxLineCount); bool result = false; AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsDocumentRequestBus::Events::SaveAsCopy, saveDocumentPath); if (!result) { QMessageBox::critical( - QApplication::activeWindow(), QString("Document could not be saved"), - QString("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + QApplication::activeWindow(), + QObject::tr("Document could not be saved"), + QObject::tr("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); return false; } return true; } - bool AtomToolsDocumentSystemComponent::SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) + bool AtomToolsDocumentSystem::SaveDocumentAsChild(const AZ::Uuid& documentId, AZStd::string_view targetPath) { AZStd::string saveDocumentPath = targetPath; if (saveDocumentPath.empty() || !AzFramework::StringFunc::Path::Normalize(saveDocumentPath)) @@ -429,26 +324,30 @@ namespace AtomToolsFramework const QFileInfo saveInfo(saveDocumentPath.c_str()); if (saveInfo.exists() && !saveInfo.isWritable()) { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); + QMessageBox::critical( + QApplication::activeWindow(), + QObject::tr("Document could not be saved"), + QObject::tr("Document could not be overwritten:\n%1").arg(saveDocumentPath.c_str())); return false; } - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + TraceRecorder traceRecorder(m_maxMessageBoxLineCount); bool result = false; AtomToolsDocumentRequestBus::EventResult(result, documentId, &AtomToolsDocumentRequestBus::Events::SaveAsChild, saveDocumentPath); if (!result) { QMessageBox::critical( - QApplication::activeWindow(), QString("Document could not be saved"), - QString("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + QApplication::activeWindow(), + QObject::tr("Document could not be saved"), + QObject::tr("Failed to save: \n%1\n\n%2").arg(saveDocumentPath.c_str()).arg(traceRecorder.GetDump().c_str())); return false; } return true; } - bool AtomToolsDocumentSystemComponent::SaveAllDocuments() + bool AtomToolsDocumentSystem::SaveAllDocuments() { bool result = true; for (const auto& documentPair : m_documentMap) @@ -462,12 +361,110 @@ namespace AtomToolsFramework return result; } - AZ::u32 AtomToolsDocumentSystemComponent::GetDocumentCount() const + AZ::u32 AtomToolsDocumentSystem::GetDocumentCount() const { return aznumeric_cast(m_documentMap.size()); } - AZ::Uuid AtomToolsDocumentSystemComponent::OpenDocumentImpl(AZStd::string_view sourcePath, bool checkIfAlreadyOpen) + + void AtomToolsDocumentSystem::OnDocumentExternallyModified(const AZ::Uuid& documentId) + { + m_documentIdsWithExternalChanges.insert(documentId); + QueueReopenDocuments(); + } + + void AtomToolsDocumentSystem::OnDocumentDependencyModified(const AZ::Uuid& documentId) + { + m_documentIdsWithDependencyChanges.insert(documentId); + QueueReopenDocuments(); + } + + void AtomToolsDocumentSystem::QueueReopenDocuments() + { + if (!m_queueReopenDocuments) + { + m_queueReopenDocuments = true; + QTimer::singleShot(0, [this] { ReopenDocuments(); }); + } + } + + void AtomToolsDocumentSystem::ReopenDocuments() + { + const bool enableHotReload = GetSettingOrDefault("/O3DE/AtomToolsFramework/AtomToolsDocumentSystem/EnableHotReload", true); + if (!enableHotReload) + { + m_documentIdsWithDependencyChanges.clear(); + m_documentIdsWithExternalChanges.clear(); + m_queueReopenDocuments = false; + } + + const bool enableHotReloadPrompts = + GetSettingOrDefault("/O3DE/AtomToolsFramework/AtomToolsDocumentSystem/EnableHotReloadPrompts", true); + + for (const AZ::Uuid& documentId : m_documentIdsWithExternalChanges) + { + m_documentIdsWithDependencyChanges.erase(documentId); + + AZStd::string documentPath; + AtomToolsDocumentRequestBus::EventResult(documentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); + + if (enableHotReloadPrompts && + (QMessageBox::question(QApplication::activeWindow(), + QObject::tr("Document was externally modified"), + QObject::tr("Would you like to reopen the document:\n%1?").arg(documentPath.c_str()), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) + { + continue; + } + + TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool openResult = false; + AtomToolsDocumentRequestBus::EventResult(openResult, documentId, &AtomToolsDocumentRequestBus::Events::Open, documentPath); + if (!openResult) + { + QMessageBox::critical( + QApplication::activeWindow(), + QObject::tr("Document could not be opened"), + QObject::tr("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + CloseDocument(documentId); + } + } + + for (const AZ::Uuid& documentId : m_documentIdsWithDependencyChanges) + { + AZStd::string documentPath; + AtomToolsDocumentRequestBus::EventResult(documentPath, documentId, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); + + if (enableHotReloadPrompts && + (QMessageBox::question(QApplication::activeWindow(), + QObject::tr("Document dependencies have changed"), + QObject::tr("Would you like to update the document with these changes:\n%1?").arg(documentPath.c_str()), + QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)) + { + continue; + } + + TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + + bool openResult = false; + AtomToolsDocumentRequestBus::EventResult(openResult, documentId, &AtomToolsDocumentRequestBus::Events::Reopen); + if (!openResult) + { + QMessageBox::critical( + QApplication::activeWindow(), + QObject::tr("Document could not be opened"), + QObject::tr("Failed to open: \n%1\n\n%2").arg(documentPath.c_str()).arg(traceRecorder.GetDump().c_str())); + CloseDocument(documentId); + } + } + + m_documentIdsWithDependencyChanges.clear(); + m_documentIdsWithExternalChanges.clear(); + m_queueReopenDocuments = false; + } + + AZ::Uuid AtomToolsDocumentSystem::OpenDocumentImpl(AZStd::string_view sourcePath, bool checkIfAlreadyOpen) { AZStd::string requestedPath = sourcePath; if (requestedPath.empty()) @@ -477,7 +474,9 @@ namespace AtomToolsFramework if (!AzFramework::StringFunc::Path::Normalize(requestedPath)) { - QMessageBox::critical(QApplication::activeWindow(), "Error", QString("Document path is invalid:\n%1").arg(requestedPath.c_str())); + QMessageBox::critical(QApplication::activeWindow(), + QObject::tr("Document could not be opened"), + QObject::tr("Document path is invalid:\n%1").arg(requestedPath.c_str())); return AZ::Uuid::CreateNull(); } @@ -490,21 +489,22 @@ namespace AtomToolsFramework AtomToolsDocumentRequestBus::EventResult(openDocumentPath, documentPair.first, &AtomToolsDocumentRequestBus::Events::GetAbsolutePath); if (openDocumentPath == requestedPath) { - AtomToolsDocumentNotificationBus::Broadcast(&AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentPair.first); + AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsDocumentNotificationBus::Events::OnDocumentOpened, documentPair.first); return documentPair.first; } } } - AtomToolsFramework::TraceRecorder traceRecorder(m_maxMessageBoxLineCount); + TraceRecorder traceRecorder(m_maxMessageBoxLineCount); - AZ::Uuid documentId = AZ::Uuid::CreateNull(); - AtomToolsDocumentSystemRequestBus::BroadcastResult(documentId, &AtomToolsDocumentSystemRequestBus::Events::CreateDocument); + AZ::Uuid documentId = CreateDocument(); if (documentId.IsNull()) { QMessageBox::critical( - QApplication::activeWindow(), QString("Document could not be created"), - QString("Failed to create: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); + QApplication::activeWindow(), + QObject::tr("Document could not be opened"), + QObject::tr("Failed to create: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); return AZ::Uuid::CreateNull(); } @@ -513,18 +513,20 @@ namespace AtomToolsFramework if (!openResult) { QMessageBox::critical( - QApplication::activeWindow(), QString("Document could not be opened"), - QString("Failed to open: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); - AtomToolsDocumentSystemRequestBus::Broadcast(&AtomToolsDocumentSystemRequestBus::Events::DestroyDocument, documentId); + QApplication::activeWindow(), + QObject::tr("Document could not be opened"), + QObject::tr("Failed to open: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); + DestroyDocument(documentId); return AZ::Uuid::CreateNull(); } else if (traceRecorder.GetWarningCount(true) > 0) { QMessageBox::warning( - QApplication::activeWindow(), QString("Document opened with warnings"), - QString("Warnings encountered: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); + QApplication::activeWindow(), + QObject::tr("Document opened with warnings"), + QObject::tr("Warnings encountered: \n%1\n\n%2").arg(requestedPath.c_str()).arg(traceRecorder.GetDump().c_str())); } return documentId; } -} +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp index b6d519bd84..bdea04fc46 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindow.cpp @@ -6,8 +6,11 @@ * */ +#include #include #include +#include +#include #include #include @@ -19,11 +22,11 @@ namespace AtomToolsFramework { - AtomToolsMainWindow::AtomToolsMainWindow(QWidget* parent) + AtomToolsMainWindow::AtomToolsMainWindow(const AZ::Crc32& toolId, QWidget* parent) : AzQtComponents::DockMainWindow(parent) + , m_toolId(toolId) + , m_advancedDockManager(new AzQtComponents::FancyDocking(this)) { - m_advancedDockManager = new AzQtComponents::FancyDocking(this); - setDockNestingEnabled(true); setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); @@ -42,20 +45,21 @@ namespace AtomToolsFramework centralWidget->setLayout(centralWidgetLayout); setCentralWidget(centralWidget); - m_assetBrowser = new AtomToolsFramework::AtomToolsAssetBrowser(this); + m_assetBrowser = new AtomToolsAssetBrowser(this); AddDockWidget("Asset Browser", m_assetBrowser, Qt::BottomDockWidgetArea, Qt::Horizontal); AddDockWidget("Python Terminal", new AzToolsFramework::CScriptTermDialog, Qt::BottomDockWidgetArea, Qt::Horizontal); SetDockWidgetVisible("Python Terminal", false); SetupMetrics(); + UpdateWindowTitle(); + resize(1280, 1024); - AtomToolsMainWindowRequestBus::Handler::BusConnect(); + AtomToolsMainWindowRequestBus::Handler::BusConnect(m_toolId); } AtomToolsMainWindow::~AtomToolsMainWindow() { - AtomToolsFramework::PerformanceMonitorRequestBus::Broadcast( - &AtomToolsFramework::PerformanceMonitorRequestBus::Handler::SetProfilerEnabled, false); + PerformanceMonitorRequestBus::Broadcast(&PerformanceMonitorRequestBus::Handler::SetProfilerEnabled, false); AtomToolsMainWindowRequestBus::Handler::BusDisconnect(); } @@ -160,10 +164,12 @@ namespace AtomToolsFramework m_menuHelp = menuBar()->addMenu("&Help"); m_menuFile->addAction("Run &Python...", [this]() { - const QString script = QFileDialog::getOpenFileName(this, "Run Script", QString(), QString("*.py")); + const QString script = QFileDialog::getOpenFileName( + this, QObject::tr("Run Script"), QString(AZ::Utils::GetProjectPath().c_str()), QString("*.py")); if (!script.isEmpty()) { - AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast(&AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByFilename, script.toUtf8().constData()); + AzToolsFramework::EditorPythonRunnerRequestBus::Broadcast( + &AzToolsFramework::EditorPythonRunnerRequestBus::Events::ExecuteByFilename, script.toUtf8().constData()); } }); @@ -213,21 +219,34 @@ namespace AtomToolsFramework m_metricsTimer.start(); connect(&m_metricsTimer, &QTimer::timeout, this, &AtomToolsMainWindow::UpdateMetrics); - AtomToolsFramework::PerformanceMonitorRequestBus::Broadcast( - &AtomToolsFramework::PerformanceMonitorRequestBus::Handler::SetProfilerEnabled, true); + PerformanceMonitorRequestBus::Broadcast(&PerformanceMonitorRequestBus::Handler::SetProfilerEnabled, true); UpdateMetrics(); } void AtomToolsMainWindow::UpdateMetrics() { - AtomToolsFramework::PerformanceMetrics metrics = {}; - AtomToolsFramework::PerformanceMonitorRequestBus::BroadcastResult( - metrics, &AtomToolsFramework::PerformanceMonitorRequestBus::Handler::GetMetrics); + PerformanceMetrics metrics = {}; + PerformanceMonitorRequestBus::BroadcastResult(metrics, &PerformanceMonitorRequestBus::Handler::GetMetrics); m_statusBarCpuTime->setText(tr("CPU Time %1 ms").arg(QString::number(metrics.m_cpuFrameTimeMs, 'f', 2))); m_statusBarGpuTime->setText(tr("GPU Time %1 ms").arg(QString::number(metrics.m_gpuFrameTimeMs, 'f', 2))); int frameRate = metrics.m_cpuFrameTimeMs > 0 ? aznumeric_cast(1000 / metrics.m_cpuFrameTimeMs) : 0; m_statusBarFps->setText(tr("FPS %1").arg(QString::number(frameRate))); } + + void AtomToolsMainWindow::UpdateWindowTitle() + { + AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); + if (!apiName.IsEmpty()) + { + QString title = QString{ "%1 (%2)" }.arg(QApplication::applicationName()).arg(apiName.GetCStr()); + setWindowTitle(title); + } + else + { + AZ_Assert(false, "Render API name not found"); + setWindowTitle(QApplication::applicationName()); + } + } } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.cpp index 3114a5d9f7..c9fce9f86b 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Window/AtomToolsMainWindowSystemComponent.cpp @@ -6,7 +6,6 @@ * */ -#include #include #include #include @@ -25,14 +24,6 @@ namespace AtomToolsFramework if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->EBus("AtomToolsMainWindowFactoryRequestBus") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) - ->Attribute(AZ::Script::Attributes::Category, "Editor") - ->Attribute(AZ::Script::Attributes::Module, "atomtools") - ->Event("CreateMainWindow", &AtomToolsMainWindowFactoryRequestBus::Events::CreateMainWindow) - ->Event("DestroyMainWindow", &AtomToolsMainWindowFactoryRequestBus::Events::DestroyMainWindow) - ; - behaviorContext->EBus("AtomToolsMainWindowRequestBus") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index 041e6e1807..19ee71dc66 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -15,6 +15,7 @@ set(FILES Include/AtomToolsFramework/Communication/LocalSocket.h Include/AtomToolsFramework/Debug/TraceRecorder.h Include/AtomToolsFramework/Document/AtomToolsDocument.h + Include/AtomToolsFramework/Document/AtomToolsDocumentSystem.h Include/AtomToolsFramework/Document/AtomToolsDocumentApplication.h Include/AtomToolsFramework/Document/AtomToolsDocumentMainWindow.h Include/AtomToolsFramework/Document/AtomToolsDocumentSystemRequestBus.h @@ -38,7 +39,6 @@ set(FILES Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h Include/AtomToolsFramework/Window/AtomToolsMainWindow.h Include/AtomToolsFramework/Window/AtomToolsMainWindowRequestBus.h - Include/AtomToolsFramework/Window/AtomToolsMainWindowFactoryRequestBus.h Include/AtomToolsFramework/Window/AtomToolsMainWindowNotificationBus.h Source/Application/AtomToolsApplication.cpp Source/AssetBrowser/AtomToolsAssetBrowser.cpp @@ -53,8 +53,7 @@ set(FILES Source/Document/AtomToolsDocument.cpp Source/Document/AtomToolsDocumentApplication.cpp Source/Document/AtomToolsDocumentMainWindow.cpp - Source/Document/AtomToolsDocumentSystemComponent.cpp - Source/Document/AtomToolsDocumentSystemComponent.h + Source/Document/AtomToolsDocumentSystem.cpp Source/DynamicProperty/DynamicProperty.cpp Source/DynamicProperty/DynamicPropertyGroup.cpp Source/Inspector/InspectorWidget.cpp diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index 8db8ee1eeb..0237d707cc 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -21,8 +21,8 @@ namespace MaterialEditor { - MaterialDocument::MaterialDocument() - : AtomToolsFramework::AtomToolsDocument() + MaterialDocument::MaterialDocument(const AZ::Crc32& toolId) + : AtomToolsFramework::AtomToolsDocument(toolId) { MaterialDocumentRequestBus::Handler::BusConnect(m_id); } @@ -86,12 +86,12 @@ namespace MaterialEditor } } - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentObjectInfoChanged, m_id, + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentObjectInfoChanged, m_id, GetObjectInfoFromDynamicPropertyGroup(group.get()), false); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentModified, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentModified, m_id); return false; } } @@ -826,8 +826,8 @@ namespace MaterialEditor if (groupChange || groupRebuilt) { - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentObjectInfoChanged, m_id, + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentObjectInfoChanged, m_id, GetObjectInfoFromDynamicPropertyGroup(group.get()), groupRebuilt); } return true; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h index 37b3e1922f..e7593453be 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.h @@ -31,9 +31,9 @@ namespace MaterialEditor public: AZ_RTTI(MaterialDocument, "{DBA269AE-892B-415C-8FA1-166B94B0E045}"); AZ_CLASS_ALLOCATOR(MaterialDocument, AZ::SystemAllocator, 0); - AZ_DISABLE_COPY(MaterialDocument); + AZ_DISABLE_COPY_MOVE(MaterialDocument); - MaterialDocument(); + MaterialDocument(const AZ::Crc32& toolId); virtual ~MaterialDocument(); // AtomToolsFramework::AtomToolsDocument overrides... diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 17453bf7af..8e3376adff 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -42,24 +42,26 @@ void InitMaterialEditorResources() namespace MaterialEditor { + static const char* GetBuildTargetName() + { +#if !defined(LY_CMAKE_TARGET) +#error "LY_CMAKE_TARGET must be defined in order to add this source file to a CMake executable target" +#endif + return LY_CMAKE_TARGET; + } + MaterialEditorApplication::MaterialEditorApplication(int* argc, char*** argv) - : Base(argc, argv) + : Base(GetBuildTargetName(), argc, argv) { InitMaterialEditorResources(); QApplication::setApplicationName("O3DE Material Editor"); - // The settings registry has been created at this point, so add the CMake target - AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization( - *AZ::SettingsRegistry::Get(), GetBuildTargetName()); - AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusConnect(); } MaterialEditorApplication::~MaterialEditorApplication() { - AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusDisconnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusDisconnect(); m_window.reset(); } @@ -101,35 +103,20 @@ namespace MaterialEditor { Base::StartCommon(systemEntity); - AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Handler::RegisterDocumentType, - []() { return aznew MaterialDocument(); }); - } + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Handler::RegisterDocumentType, + [](const AZ::Crc32& toolId) { return aznew MaterialDocument(toolId); }); - AZStd::string MaterialEditorApplication::GetBuildTargetName() const - { -#if !defined(LY_CMAKE_TARGET) -#error "LY_CMAKE_TARGET must be defined in order to add this source file to a CMake executable target" -#endif - //! Returns the build system target name of "MaterialEditor" - return AZStd::string{ LY_CMAKE_TARGET }; - } + m_window.reset(aznew MaterialEditorWindow(m_toolId)); - AZStd::vector MaterialEditorApplication::GetCriticalAssetFilters() const - { - return AZStd::vector({ "passes/", "config/", "MaterialEditor/" }); - } - - void MaterialEditorApplication::CreateMainWindow() - { - m_window.reset(aznew MaterialEditorWindow); m_assetBrowserInteractions.reset(aznew AtomToolsFramework::AtomToolsAssetBrowserInteractions); + m_assetBrowserInteractions->RegisterContextMenuActions( [](const AtomToolsFramework::AtomToolsAssetBrowserInteractions::AssetBrowserEntryVector& entries) { return entries.front()->GetEntryType() == AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Source; }, - []([[maybe_unused]] QWidget* caller, QMenu* menu, const AtomToolsFramework::AtomToolsAssetBrowserInteractions::AssetBrowserEntryVector& entries) + [this]([[maybe_unused]] QWidget* caller, QMenu* menu, const AtomToolsFramework::AtomToolsAssetBrowserInteractions::AssetBrowserEntryVector& entries) { const bool isMaterial = AzFramework::StringFunc::Path::IsExtension( entries.front()->GetFullPath().c_str(), AZ::RPI::MaterialSourceData::Extension); @@ -137,17 +124,17 @@ namespace MaterialEditor entries.front()->GetFullPath().c_str(), AZ::RPI::MaterialTypeSourceData::Extension); if (isMaterial || isMaterialType) { - menu->addAction(QObject::tr("Open"), [entries]() + menu->addAction(QObject::tr("Open"), [entries, this]() { - AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, entries.front()->GetFullPath()); }); const QString createActionName = isMaterialType ? QObject::tr("Create Material...") : QObject::tr("Create Child Material..."); - menu->addAction(createActionName, [entries]() + menu->addAction(createActionName, [entries, this]() { const QString defaultPath = AtomToolsFramework::GetUniqueFileInfo( QString(AZ::Utils::GetProjectPath().c_str()) + @@ -155,8 +142,8 @@ namespace MaterialEditor AZ_CORRECT_FILESYSTEM_SEPARATOR + "untitled." + AZ::RPI::MaterialSourceData::Extension).absoluteFilePath(); - AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, entries.front()->GetFullPath(), AtomToolsFramework::GetSaveFileInfo(defaultPath).absoluteFilePath().toUtf8().constData()); }); @@ -175,9 +162,9 @@ namespace MaterialEditor { return entries.front()->GetEntryType() == AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Folder; }, - [](QWidget* caller, QMenu* menu, const AtomToolsFramework::AtomToolsAssetBrowserInteractions::AssetBrowserEntryVector& entries) + [this](QWidget* caller, QMenu* menu, const AtomToolsFramework::AtomToolsAssetBrowserInteractions::AssetBrowserEntryVector& entries) { - menu->addAction(QObject::tr("Create Material..."), [caller, entries]() + menu->addAction(QObject::tr("Create Material..."), [caller, entries, this]() { CreateMaterialDialog createDialog(entries.front()->GetFullPath().c_str(), caller); createDialog.adjustSize(); @@ -186,8 +173,8 @@ namespace MaterialEditor !createDialog.m_materialFileInfo.absoluteFilePath().isEmpty() && !createDialog.m_materialTypeFileInfo.absoluteFilePath().isEmpty()) { - AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::CreateDocumentFromFile, createDialog.m_materialTypeFileInfo.absoluteFilePath().toUtf8().constData(), createDialog.m_materialFileInfo.absoluteFilePath().toUtf8().constData()); } @@ -195,9 +182,15 @@ namespace MaterialEditor }); } - void MaterialEditorApplication::DestroyMainWindow() + void MaterialEditorApplication::Destroy() { m_window.reset(); + Base::Destroy(); + } + + AZStd::vector MaterialEditorApplication::GetCriticalAssetFilters() const + { + return AZStd::vector({ "passes/", "config/", "MaterialEditor/" }); } QWidget* MaterialEditorApplication::GetAppMainWindow() diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h index 0cf4354f6c..4829d31673 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h @@ -10,7 +10,6 @@ #include #include -#include #include #include @@ -21,7 +20,6 @@ namespace MaterialEditor class MaterialEditorApplication : public AtomToolsFramework::AtomToolsDocumentApplication , private AzToolsFramework::EditorWindowRequestBus::Handler - , private AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler { public: AZ_TYPE_INFO(MaterialEditor::MaterialEditorApplication, "{30F90CA5-1253-49B5-8143-19CEE37E22BB}"); @@ -36,15 +34,11 @@ namespace MaterialEditor void CreateStaticModules(AZStd::vector& outModules) override; const char* GetCurrentConfigurationName() const override; void StartCommon(AZ::Entity* systemEntity) override; + void Destroy() override; // AtomToolsFramework::AtomToolsApplication overrides... - AZStd::string GetBuildTargetName() const override; AZStd::vector GetCriticalAssetFilters() const override; - // AtomToolsMainWindowFactoryRequestBus::Handler overrides... - void CreateMainWindow() override; - void DestroyMainWindow() override; - // AzToolsFramework::EditorWindowRequests::Bus::Handler QWidget* GetAppMainWindow() override; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportWidget.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportWidget.cpp index 21b01b5dab..5d8dc1cdc5 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportWidget.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportWidget.cpp @@ -60,9 +60,10 @@ namespace MaterialEditor { static constexpr float DepthNear = 0.01f; - MaterialViewportWidget::MaterialViewportWidget(QWidget* parent) + MaterialViewportWidget::MaterialViewportWidget(const AZ::Crc32& toolId, QWidget* parent) : AtomToolsFramework::RenderViewportWidget(parent) , m_ui(new Ui::MaterialViewportWidget) + , m_toolId(toolId) , m_viewportController(AZStd::make_shared()) { m_ui->setupUi(this); @@ -252,7 +253,7 @@ namespace MaterialEditor OnFieldOfViewChanged(viewportSettings->m_fieldOfView); OnDisplayMapperOperationTypeChanged(viewportSettings->m_displayMapperOperationType); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(m_toolId); MaterialViewportNotificationBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); AZ::TransformNotificationBus::MultiHandler::BusConnect(m_cameraEntity->GetId()); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportWidget.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportWidget.h index 8a660c6603..dcb80dc252 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportWidget.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Viewport/MaterialViewportWidget.h @@ -57,7 +57,7 @@ namespace MaterialEditor , public AZ::TransformNotificationBus::MultiHandler { public: - MaterialViewportWidget(QWidget* parent = nullptr); + MaterialViewportWidget(const AZ::Crc32& toolId, QWidget* parent = nullptr); ~MaterialViewportWidget(); private: @@ -84,6 +84,8 @@ namespace MaterialEditor // AZ::TransformNotificationBus::MultiHandler overrides... void OnTransformChanged(const AZ::Transform&, const AZ::Transform&) override; + const AZ::Crc32 m_toolId = {}; + using DirectionalLightHandle = AZ::Render::DirectionalLightFeatureProcessorInterface::LightHandle; AZ::Data::Instance m_swapChainPass; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index da742d498d..3b9aba86e8 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -6,7 +6,6 @@ * */ -#include #include #include #include @@ -36,11 +35,9 @@ AZ_POP_DISABLE_WARNING namespace MaterialEditor { - MaterialEditorWindow::MaterialEditorWindow(QWidget* parent /* = 0 */) - : Base(parent) + MaterialEditorWindow::MaterialEditorWindow(const AZ::Crc32& toolId, QWidget* parent) + : Base(toolId, parent) { - resize(1280, 1024); - // Among other things, we need the window wrapper to save the main window size, position, and state auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionAutoTitleBarButtons); @@ -52,36 +49,24 @@ namespace MaterialEditor QApplication::setWindowIcon(QIcon(":/Icons/materialeditor.svg")); - AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); - if (!apiName.IsEmpty()) - { - QString title = QString{ "%1 (%2)" }.arg(QApplication::applicationName()).arg(apiName.GetCStr()); - setWindowTitle(title); - } - else - { - AZ_Assert(false, "Render API name not found"); - setWindowTitle(QApplication::applicationName()); - } - setObjectName("MaterialEditorWindow"); m_toolBar = new MaterialEditorToolBar(this); m_toolBar->setObjectName("ToolBar"); addToolBar(m_toolBar); - m_materialViewport = new MaterialViewportWidget(centralWidget()); + m_materialViewport = new MaterialViewportWidget(m_toolId, centralWidget()); m_materialViewport->setObjectName("Viewport"); m_materialViewport->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); centralWidget()->layout()->addWidget(m_materialViewport); m_assetBrowser->SetFilterState("", AZ::RPI::StreamingImageAsset::Group, true); m_assetBrowser->SetFilterState("", AZ::RPI::MaterialAsset::Group, true); - m_assetBrowser->SetOpenHandler([](const AZStd::string& absolutePath) { + m_assetBrowser->SetOpenHandler([this](const AZStd::string& absolutePath) { if (AzFramework::StringFunc::Path::IsExtension(absolutePath.c_str(), AZ::RPI::MaterialSourceData::Extension)) { - AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, absolutePath); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, absolutePath); return; } @@ -93,7 +78,7 @@ namespace MaterialEditor QDesktopServices::openUrl(QUrl::fromLocalFile(absolutePath.c_str())); }); - AddDockWidget("Inspector", new MaterialInspector, Qt::RightDockWidgetArea, Qt::Vertical); + AddDockWidget("Inspector", new MaterialInspector(m_toolId), Qt::RightDockWidgetArea, Qt::Vertical); AddDockWidget("Viewport Settings", new ViewportSettingsInspector, Qt::LeftDockWidgetArea, Qt::Vertical); SetDockWidgetVisible("Viewport Settings", false); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 33b60add5b..0e98e3ac84 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -32,7 +32,7 @@ namespace MaterialEditor using Base = AtomToolsFramework::AtomToolsDocumentMainWindow; - MaterialEditorWindow(QWidget* parent = 0); + MaterialEditorWindow(const AZ::Crc32& toolId, QWidget* parent = 0); protected: void ResizeViewportRenderTarget(uint32_t width, uint32_t height) override; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp index e6e768a7fd..c22e65df2e 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.cpp @@ -15,13 +15,14 @@ namespace MaterialEditor { - MaterialInspector::MaterialInspector(QWidget* parent) + MaterialInspector::MaterialInspector(const AZ::Crc32& toolId, QWidget* parent) : AtomToolsFramework::InspectorWidget(parent) + , m_toolId(toolId) { m_windowSettings = AZ::UserSettings::CreateFind( AZ::Crc32("MaterialEditorWindowSettings"), AZ::UserSettings::CT_GLOBAL); - AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Handler::BusConnect(m_toolId); } MaterialInspector::~MaterialInspector() diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h index fe688e3ad5..901affd1b1 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialInspector/MaterialInspector.h @@ -29,7 +29,7 @@ namespace MaterialEditor public: AZ_CLASS_ALLOCATOR(MaterialInspector, AZ::SystemAllocator, 0); - explicit MaterialInspector(QWidget* parent = nullptr); + MaterialInspector(const AZ::Crc32& toolId, QWidget* parent = nullptr); ~MaterialInspector() override; // AtomToolsFramework::InspectorRequestBus::Handler overrides... @@ -59,6 +59,8 @@ namespace MaterialEditor void RequestPropertyContextMenu([[maybe_unused]] AzToolsFramework::InstanceDataNode* pNode, const QPoint&) override {} void PropertySelectionChanged([[maybe_unused]] AzToolsFramework::InstanceDataNode* pNode, bool) override {} + const AZ::Crc32 m_toolId = {}; + // Tracking the property that is activiley being edited in the inspector const AtomToolsFramework::DynamicProperty* m_activeProperty = {}; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.cpp index 5698e33cec..e7bd6033de 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.cpp @@ -14,8 +14,8 @@ namespace ShaderManagementConsole { - ShaderManagementConsoleDocument::ShaderManagementConsoleDocument() - : AtomToolsFramework::AtomToolsDocument() + ShaderManagementConsoleDocument::ShaderManagementConsoleDocument(const AZ::Crc32& toolId) + : AtomToolsFramework::AtomToolsDocument(toolId) { ShaderManagementConsoleDocumentRequestBus::Handler::BusConnect(m_id); } @@ -37,8 +37,8 @@ namespace ShaderManagementConsole AZ_Error("ShaderManagementConsoleDocument", false, "Could not load shader asset: %s.", shaderPath.c_str()); } - AtomToolsFramework::AtomToolsDocumentNotificationBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentModified, m_id); + AtomToolsFramework::AtomToolsDocumentNotificationBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentNotificationBus::Events::OnDocumentModified, m_id); } const AZ::RPI::ShaderVariantListSourceData& ShaderManagementConsoleDocument::GetShaderVariantListSourceData() const diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.h index 5c3d66b0a9..46002ce1da 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocument.h @@ -24,11 +24,11 @@ namespace ShaderManagementConsole , public ShaderManagementConsoleDocumentRequestBus::Handler { public: - AZ_RTTI(ShaderManagementConsoleDocument, "{DBA269AE-892B-415C-8FA1-166B94B0E045}"); + AZ_RTTI(ShaderManagementConsoleDocument, "{504A74BA-F5DD-49E0-BA5E-A381F61DD524}"); AZ_CLASS_ALLOCATOR(ShaderManagementConsoleDocument, AZ::SystemAllocator, 0); - AZ_DISABLE_COPY(ShaderManagementConsoleDocument); + AZ_DISABLE_COPY_MOVE(ShaderManagementConsoleDocument); - ShaderManagementConsoleDocument(); + ShaderManagementConsoleDocument(const AZ::Crc32& toolId); ~ShaderManagementConsoleDocument(); // AtomToolsFramework::AtomToolsDocument overrides... diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp index 2d61730c4d..43936c59da 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.cpp @@ -47,27 +47,29 @@ void InitShaderManagementConsoleResources() namespace ShaderManagementConsole { + static const char* GetBuildTargetName() + { +#if !defined(LY_CMAKE_TARGET) +#error "LY_CMAKE_TARGET must be defined in order to add this source file to a CMake executable target" +#endif + return LY_CMAKE_TARGET; + } + ShaderManagementConsoleApplication::ShaderManagementConsoleApplication(int* argc, char*** argv) - : Base(argc, argv) + : Base(GetBuildTargetName(), argc, argv) { InitShaderManagementConsoleResources(); QApplication::setApplicationName("O3DE Shader Management Console"); - // The settings registry has been created at this point, so add the CMake target - AZ::SettingsRegistryMergeUtils::MergeSettingsToRegistry_AddBuildSystemTargetSpecialization( - *AZ::SettingsRegistry::Get(), GetBuildTargetName()); - ShaderManagementConsoleRequestBus::Handler::BusConnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusConnect(); - AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusConnect(); } ShaderManagementConsoleApplication::~ShaderManagementConsoleApplication() { ShaderManagementConsoleRequestBus::Handler::BusDisconnect(); AzToolsFramework::EditorWindowRequestBus::Handler::BusDisconnect(); - AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler::BusDisconnect(); m_window.reset(); } @@ -115,40 +117,20 @@ namespace ShaderManagementConsole { Base::StartCommon(systemEntity); - AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Handler::RegisterDocumentType, - []() { return aznew ShaderManagementConsoleDocument(); }); - } + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Handler::RegisterDocumentType, + [](const AZ::Crc32& toolId) { return aznew ShaderManagementConsoleDocument(toolId); }); - AZStd::string ShaderManagementConsoleApplication::GetBuildTargetName() const - { -#if !defined(LY_CMAKE_TARGET) -#error "LY_CMAKE_TARGET must be defined in order to add this source file to a CMake executable target" -#endif - //! Returns the build system target name of "ShaderManagementConsole" - return AZStd::string_view{ LY_CMAKE_TARGET }; - } + m_window.reset(aznew ShaderManagementConsoleWindow(m_toolId)); - AZStd::vector ShaderManagementConsoleApplication::GetCriticalAssetFilters() const - { - return AZStd::vector({ "passes/", "config/" }); - } - - QWidget* ShaderManagementConsoleApplication::GetAppMainWindow() - { - return m_window.get(); - } - - void ShaderManagementConsoleApplication::CreateMainWindow() - { - m_window.reset(aznew ShaderManagementConsoleWindow); m_assetBrowserInteractions.reset(aznew AtomToolsFramework::AtomToolsAssetBrowserInteractions); + m_assetBrowserInteractions->RegisterContextMenuActions( [](const AtomToolsFramework::AtomToolsAssetBrowserInteractions::AssetBrowserEntryVector& entries) { return entries.front()->GetEntryType() == AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Source; }, - []([[maybe_unused]] QWidget* caller, QMenu* menu, const AtomToolsFramework::AtomToolsAssetBrowserInteractions::AssetBrowserEntryVector& entries) + [this]([[maybe_unused]] QWidget* caller, QMenu* menu, const AtomToolsFramework::AtomToolsAssetBrowserInteractions::AssetBrowserEntryVector& entries) { if (AzFramework::StringFunc::Path::IsExtension( entries.front()->GetFullPath().c_str(), AZ::RPI::ShaderSourceData::Extension)) @@ -166,10 +148,10 @@ namespace ShaderManagementConsole else if (AzFramework::StringFunc::Path::IsExtension( entries.front()->GetFullPath().c_str(), AZ::RPI::ShaderVariantListSourceData::Extension)) { - menu->addAction(QObject::tr("Open"), [entries]() + menu->addAction(QObject::tr("Open"), [entries, this]() { - AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, entries.front()->GetFullPath()); }); } @@ -183,9 +165,20 @@ namespace ShaderManagementConsole }); } - void ShaderManagementConsoleApplication::DestroyMainWindow() + void ShaderManagementConsoleApplication::Destroy() { m_window.reset(); + Base::Destroy(); + } + + AZStd::vector ShaderManagementConsoleApplication::GetCriticalAssetFilters() const + { + return AZStd::vector({ "passes/", "config/" }); + } + + QWidget* ShaderManagementConsoleApplication::GetAppMainWindow() + { + return m_window.get(); } AZ::Data::AssetInfo ShaderManagementConsoleApplication::GetSourceAssetInfo(const AZStd::string& sourceAssetFileName) diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h index 232f204790..75d1ab83c8 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/ShaderManagementConsoleApplication.h @@ -11,7 +11,6 @@ #include #include #include -#include #include #include #include @@ -21,7 +20,6 @@ namespace ShaderManagementConsole class ShaderManagementConsoleApplication : public AtomToolsFramework::AtomToolsDocumentApplication , private ShaderManagementConsoleRequestBus::Handler - , private AtomToolsFramework::AtomToolsMainWindowFactoryRequestBus::Handler , private AzToolsFramework::EditorWindowRequestBus::Handler { public: @@ -36,18 +34,14 @@ namespace ShaderManagementConsole void Reflect(AZ::ReflectContext* context) override; const char* GetCurrentConfigurationName() const override; void StartCommon(AZ::Entity* systemEntity) override; + void Destroy() override; // AtomToolsFramework::AtomToolsApplication overrides... - AZStd::string GetBuildTargetName() const override; AZStd::vector GetCriticalAssetFilters() const override; // AzToolsFramework::EditorWindowRequests::Bus::Handler QWidget* GetAppMainWindow() override; - // AtomToolsMainWindowFactoryRequestBus::Handler overrides... - void CreateMainWindow() override; - void DestroyMainWindow() override; - // ShaderManagementConsoleRequestBus::Handler overrides... AZ::Data::AssetInfo GetSourceAssetInfo(const AZStd::string& sourceAssetFileName) override; AZStd::vector FindMaterialAssetsUsingShader(const AZStd::string& shaderFilePath) override; diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp index 04a8a71191..b1bd906f81 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.cpp @@ -26,11 +26,9 @@ AZ_POP_DISABLE_WARNING namespace ShaderManagementConsole { - ShaderManagementConsoleWindow::ShaderManagementConsoleWindow(QWidget* parent /* = 0 */) - : Base(parent) + ShaderManagementConsoleWindow::ShaderManagementConsoleWindow(const AZ::Crc32& toolId, QWidget* parent) + : Base(toolId, parent) { - resize(1280, 1024); - // Among other things, we need the window wrapper to save the main window size, position, and state auto mainWindowWrapper = new AzQtComponents::WindowDecorationWrapper(AzQtComponents::WindowDecorationWrapper::OptionAutoTitleBarButtons); @@ -42,11 +40,11 @@ namespace ShaderManagementConsole setObjectName("ShaderManagementConsoleWindow"); m_assetBrowser->SetFilterState("", AZ::RPI::ShaderAsset::Group, true); - m_assetBrowser->SetOpenHandler([](const AZStd::string& absolutePath) { + m_assetBrowser->SetOpenHandler([this](const AZStd::string& absolutePath) { if (AzFramework::StringFunc::Path::IsExtension(absolutePath.c_str(), AZ::RPI::ShaderVariantListSourceData::Extension)) { - AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Broadcast( - &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, absolutePath); + AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Event( + m_toolId, &AtomToolsFramework::AtomToolsDocumentSystemRequestBus::Events::OpenDocument, absolutePath); return; } diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h index d5dd04c434..1a8ac53992 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Window/ShaderManagementConsoleWindow.h @@ -31,7 +31,7 @@ namespace ShaderManagementConsole using Base = AtomToolsFramework::AtomToolsDocumentMainWindow; - ShaderManagementConsoleWindow(QWidget* parent = 0); + ShaderManagementConsoleWindow(const AZ::Crc32& toolId, QWidget* parent = 0); ~ShaderManagementConsoleWindow() = default; protected: From 600ad3fd044524bf6dbb5012a579fa5002e579ef Mon Sep 17 00:00:00 2001 From: Guthrie Adams Date: Fri, 11 Feb 2022 02:17:37 -0600 Subject: [PATCH 084/133] Fixing compiler errors requiring numeric cast Signed-off-by: Guthrie Adams --- .../Code/Source/Application/AtomToolsApplication.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index 72d7cbf100..bac26451fd 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -69,10 +69,10 @@ namespace AtomToolsFramework m_styleManager.reset(new AzQtComponents::StyleManager(this)); m_styleManager->initialize(this, engineRootPath); - const AZ::u64 updateIntervalWhenActive = - GetSettingOrDefault("/O3DE/AtomToolsFramework/Application/UpdateIntervalWhenActive", 1); - const AZ::u64 updateIntervalWhenNotActive = - GetSettingOrDefault("/O3DE/AtomToolsFramework/Application/UpdateIntervalWhenNotActive", 64); + const int updateIntervalWhenActive = + aznumeric_cast(GetSettingOrDefault("/O3DE/AtomToolsFramework/Application/UpdateIntervalWhenActive", 1)); + const int updateIntervalWhenNotActive = + aznumeric_cast(GetSettingOrDefault("/O3DE/AtomToolsFramework/Application/UpdateIntervalWhenNotActive", 64)); m_timer.setInterval(updateIntervalWhenActive); connect(&m_timer, &QTimer::timeout, this, [this]() From 7150a28ed6050bd27e5a8fc97d556080f7d45c48 Mon Sep 17 00:00:00 2001 From: moraaar Date: Fri, 11 Feb 2022 09:08:33 +0000 Subject: [PATCH 085/133] Mesh Component: Add button to the Mesh Asset field to open mesh FBX settings (#7547) This is an UX improvement for Mesh Component as the user can quickly access FBX settings of the mesh to modify it if they so desire. Video https://user-images.githubusercontent.com/27999040/153414278-f7996b9a-8a28-49d4-92a8-daeb9924b148.mp4 Signed-off-by: moraaar moraaar@amazon.com --- .../RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp | 10 ++++++++++ .../Code/Source/Mesh/EditorMeshComponent.cpp | 3 +++ 2 files changed, 13 insertions(+) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp index 6780763d7c..5685dfece2 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp @@ -15,6 +15,7 @@ #include #include +#include namespace AZ { @@ -35,6 +36,15 @@ namespace AZ ->Field("MaterialSlots", &ModelAsset::m_materialSlots) ->Field("LodAssets", &ModelAsset::m_lodAssets) ; + + // Note: This class needs to have edit context reflection so PropertyAssetCtrl::OnEditButtonClicked + // can open the asset with the preferred asset editor (Scene Settings). + if (auto* editContext = serializeContext->GetEditContext()) + { + editContext->Class("Model Asset", "") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ; + } } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.cpp index 255f639cd7..0d6b87e795 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/EditorMeshComponent.cpp @@ -72,6 +72,9 @@ namespace AZ ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentConfig::m_modelAsset, "Mesh Asset", "Mesh asset reference") + ->Attribute(AZ_CRC_CE("EditButton"), "") + ->Attribute(AZ_CRC_CE("EditDescription"), "Open in Scene Settings") + ->Attribute(AZ_CRC_CE("DisableEditButtonWhenNoAssetSelected"), true) ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentConfig::m_sortKey, "Sort Key", "Transparent meshes are drawn by sort key then depth. Used this to force certain transparent meshes to draw before or after others.") ->Attribute(AZ::Edit::Attributes::Visibility, &MeshComponentConfig::IsAssetSet) ->DataElement(AZ::Edit::UIHandlers::CheckBox, &MeshComponentConfig::m_excludeFromReflectionCubeMaps, "Exclude from reflection cubemaps", "Mesh will not be visible in baked reflection probe cubemaps") From 7a63d33f92e2e98c6d5c6fffd718d499ce848669 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 11 Feb 2022 12:01:22 +0000 Subject: [PATCH 086/133] extract reused manipulator scaling logic Signed-off-by: greerdv --- .../ComponentModes/BoxViewportEdit.cpp | 27 +++++++++---------- .../ComponentModes/BoxViewportEdit.h | 6 +++++ .../PhysX/Code/Editor/ColliderCapsuleMode.cpp | 19 +++++-------- Gems/PhysX/Code/Editor/ColliderSphereMode.cpp | 10 +++---- 4 files changed, 30 insertions(+), 32 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp index cf3d8aa693..a747bb1379 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp @@ -93,29 +93,20 @@ namespace AzToolsFramework linearManipulator->SetViews(AZStd::move(views)); linearManipulator->InstallMouseMoveCallback( - [this, entityComponentIdPair]( - const LinearManipulator::Action& action) + [this, entityComponentIdPair, + transformScale{ linearManipulator->GetSpace().GetUniformScale() }](const LinearManipulator::Action& action) { AZ::Transform boxLocalTransform = AZ::Transform::CreateIdentity(); BoxManipulatorRequestBus::EventResult( boxLocalTransform, entityComponentIdPair, &BoxManipulatorRequests::GetCurrentLocalTransform); - AZ::Transform boxWorldTransform = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult( - boxWorldTransform, m_entityComponentIdPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); - float boxScale = AZ::GetMax(AZ::MinTransformScale, boxWorldTransform.GetUniformScale()); - - // calculate the position of the manipulator in the reference frame of the box - // the local position offset of the manipulator does not take the transform scale into account - // so need to apply it here - const AZ::Vector3 localPosition = boxLocalTransform.GetInverse().TransformPoint( - action.m_start.m_localPosition + action.m_current.m_localPositionOffset / boxScale); + const AZ::Vector3 manipulatorPosition = GetPositionInManipulatorFrame(transformScale, boxLocalTransform, action); // calculate the amount of displacement along an axis this manipulator has moved // clamp movement so it cannot go negative based on axis direction const AZ::Vector3 axisDisplacement = - localPosition.GetAbs() * 2.0f - * AZ::GetMax(0.0f, localPosition.GetNormalized().Dot(action.m_fixed.m_axis)); + manipulatorPosition.GetAbs() * 2.0f + * AZ::GetMax(0.0f, manipulatorPosition.GetNormalized().Dot(action.m_fixed.m_axis)); AZ::Vector3 boxDimensions = AZ::Vector3::CreateZero(); BoxManipulatorRequestBus::EventResult( @@ -148,4 +139,12 @@ namespace AzToolsFramework } } } + + AZ::Vector3 GetPositionInManipulatorFrame(float worldUniformScale, const AZ::Transform& manipulatorLocalTransform, + const LinearManipulator::Action& action) + { + return manipulatorLocalTransform.GetInverse().TransformPoint( + action.m_start.m_localPosition + + action.m_current.m_localPositionOffset / AZ::GetClamp(worldUniformScale, AZ::MinTransformScale, AZ::MaxTransformScale)); + } } // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.h index 98ef17e547..66ea626e12 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.h @@ -31,4 +31,10 @@ namespace AzToolsFramework using BoxManipulators = AZStd::array, 6>; BoxManipulators m_linearManipulators; ///< Manipulators for editing box size. }; + + /// Calculates the position of the manipulator in its own reference frame. + /// Removes the effects of the manipulator local transform, and accounts for world transform scale in + /// the action local offset. + AZ::Vector3 GetPositionInManipulatorFrame(float worldUniformScale, const AZ::Transform& manipulatorLocalTransform, + const LinearManipulator::Action& action); } // namespace AzToolsFramework diff --git a/Gems/PhysX/Code/Editor/ColliderCapsuleMode.cpp b/Gems/PhysX/Code/Editor/ColliderCapsuleMode.cpp index eddd65a7f0..b704f8feec 100644 --- a/Gems/PhysX/Code/Editor/ColliderCapsuleMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderCapsuleMode.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -175,15 +176,12 @@ namespace PhysX void ColliderCapsuleMode::OnRadiusManipulatorMoved(const AzToolsFramework::LinearManipulator::Action& action, const AZ::EntityComponentIdPair& idPair) { // manipulator action offsets do not take entity transform scale into account, so need to apply it here - float transformScale = 1.0f; const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); - AZ::TransformBus::EventResult(transformScale, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldUniformScale); - transformScale = AZ::GetMax(AZ::MinTransformScale, transformScale); - const AZ::Vector3 localPosition = colliderLocalTransform.GetInverse().TransformPoint( - action.m_start.m_localPosition + action.m_current.m_localPositionOffset / transformScale); + const AZ::Vector3 manipulatorPosition = AzToolsFramework::GetPositionInManipulatorFrame( + m_radiusManipulator->GetSpace().GetUniformScale(), colliderLocalTransform, action); // Get the distance the manipulator has moved along the axis. - float extent = localPosition.Dot(action.m_fixed.m_axis); + float extent = manipulatorPosition.Dot(action.m_fixed.m_axis); // Clamp radius to a small value. extent = AZ::GetMax(extent, MinCapsuleRadius); @@ -201,15 +199,12 @@ namespace PhysX void ColliderCapsuleMode::OnHeightManipulatorMoved(const AzToolsFramework::LinearManipulator::Action& action, const AZ::EntityComponentIdPair& idPair) { // manipulator action offsets do not take entity transform scale into account, so need to apply it here - float transformScale = 1.0f; const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); - AZ::TransformBus::EventResult(transformScale, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldUniformScale); - transformScale = AZ::GetMax(AZ::MinTransformScale, transformScale); - const AZ::Vector3 localPosition = colliderLocalTransform.GetInverse().TransformPoint( - action.m_start.m_localPosition + action.m_current.m_localPositionOffset / transformScale); + const AZ::Vector3 manipulatorPosition = AzToolsFramework::GetPositionInManipulatorFrame( + m_heightManipulator->GetSpace().GetUniformScale(), colliderLocalTransform, action); // Get the distance the manipulator has moved along the axis. - float extent = localPosition.Dot(action.m_fixed.m_axis); + float extent = manipulatorPosition.Dot(action.m_fixed.m_axis); // Ensure capsule's half height is always greater than the radius. extent = AZ::GetMax(extent, MinCapsuleHeight); diff --git a/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp b/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp index d292f2dd2a..8d69e28726 100644 --- a/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp +++ b/Gems/PhysX/Code/Editor/ColliderSphereMode.cpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -110,15 +111,12 @@ namespace PhysX void ColliderSphereMode::OnManipulatorMoved(const AzToolsFramework::LinearManipulator::Action& action, const AZ::EntityComponentIdPair& idPair) { // manipulator offsets do not take transform scale into account, need to handle it here - AZ::Transform colliderWorldTransform = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult(colliderWorldTransform, idPair.GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); const AZ::Transform colliderLocalTransform = Utils::GetColliderLocalTransform(idPair); - const float transformScale = AZ::GetMax(AZ::MinTransformScale, colliderWorldTransform.GetUniformScale()); - const AZ::Vector3 localPosition = colliderLocalTransform.GetInverse().TransformPoint( - action.m_start.m_localPosition + action.m_current.m_localPositionOffset / transformScale); + const AZ::Vector3 manipulatorPosition = AzToolsFramework::GetPositionInManipulatorFrame( + m_radiusManipulator->GetSpace().GetUniformScale(), colliderLocalTransform, action); // Get the distance the manipulator has moved along the axis. - float extent = localPosition.Dot(action.m_fixed.m_axis); + float extent = manipulatorPosition.Dot(action.m_fixed.m_axis); // Clamp the distance to a small value to prevent it going negative. extent = AZ::GetMax(extent, MinSphereRadius); From f2233f90cde1ea8efeaee69b6af0024e131a8677 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 11 Feb 2022 12:20:31 +0000 Subject: [PATCH 087/133] update bus usage to new preferred convention Signed-off-by: greerdv --- .../ComponentModes/BoxViewportEdit.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp index a747bb1379..4c08ef6855 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ComponentModes/BoxViewportEdit.cpp @@ -44,15 +44,15 @@ namespace AzToolsFramework AZ::Vector3 nonUniformScale = AZ::Vector3::CreateOne(); AZ::NonUniformScaleRequestBus::EventResult( - nonUniformScale, m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); + nonUniformScale, m_entityComponentIdPair.GetEntityId(), &AZ::NonUniformScaleRequestBus::Events::GetScale); AZ::Vector3 boxDimensions = AZ::Vector3::CreateZero(); BoxManipulatorRequestBus::EventResult( - boxDimensions, m_entityComponentIdPair, &BoxManipulatorRequests::GetDimensions); + boxDimensions, m_entityComponentIdPair, &BoxManipulatorRequestBus::Events::GetDimensions); AZ::Transform boxLocalTransform = AZ::Transform::CreateIdentity(); BoxManipulatorRequestBus::EventResult( - boxLocalTransform, m_entityComponentIdPair, &BoxManipulatorRequests::GetCurrentLocalTransform); + boxLocalTransform, m_entityComponentIdPair, &BoxManipulatorRequestBus::Events::GetCurrentLocalTransform); for (size_t manipulatorIndex = 0; manipulatorIndex < m_linearManipulators.size(); ++manipulatorIndex) { @@ -98,7 +98,7 @@ namespace AzToolsFramework { AZ::Transform boxLocalTransform = AZ::Transform::CreateIdentity(); BoxManipulatorRequestBus::EventResult( - boxLocalTransform, entityComponentIdPair, &BoxManipulatorRequests::GetCurrentLocalTransform); + boxLocalTransform, entityComponentIdPair, &BoxManipulatorRequestBus::Events::GetCurrentLocalTransform); const AZ::Vector3 manipulatorPosition = GetPositionInManipulatorFrame(transformScale, boxLocalTransform, action); @@ -110,12 +110,12 @@ namespace AzToolsFramework AZ::Vector3 boxDimensions = AZ::Vector3::CreateZero(); BoxManipulatorRequestBus::EventResult( - boxDimensions, entityComponentIdPair, &BoxManipulatorRequests::GetDimensions); + boxDimensions, entityComponentIdPair, &BoxManipulatorRequestBus::Events::GetDimensions); // update dimensions - preserve dimensions not effected by this // axis, and update current axis displacement BoxManipulatorRequestBus::Event( - entityComponentIdPair, &BoxManipulatorRequests::SetDimensions, + entityComponentIdPair, &BoxManipulatorRequestBus::Events::SetDimensions, (NotAxis(action.m_fixed.m_axis) * boxDimensions).GetMax(axisDisplacement)); UpdateManipulators(); From d39681a7674d15fb0739f8683775af84c631d913 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 11 Feb 2022 12:29:00 +0000 Subject: [PATCH 088/133] add deprecation notice to functions in BoxManipulatorRequests Signed-off-by: greerdv --- .../AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h index 359b92502e..0d6299f5d4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/BoxManipulatorRequestBus.h @@ -26,6 +26,7 @@ namespace AzToolsFramework virtual AZ::Vector3 GetDimensions() = 0; //! Set the X/Y/Z dimensions of the box shape/collider. virtual void SetDimensions(const AZ::Vector3& dimensions) = 0; + // O3DE_DEPRECATION_NOTICE(GHI-7572) //! @deprecated Because non-uniform scale effects can be complex, it is recommended to separately use //! AZ::TransformBus::Events::GetWorldTM, AZ::NonUniformScaleRequests::GetScale and GetCurrentLocalTransform //! and combine their effects. @@ -36,6 +37,7 @@ namespace AzToolsFramework virtual AZ::Transform GetCurrentTransform() = 0; //! Get the transform of the box relative to the entity. virtual AZ::Transform GetCurrentLocalTransform() = 0; + // O3DE_DEPRECATION_NOTICE(GHI-7572) //! @deprecated Because non-uniform scale effects can be complex, it is recommended to separately use //! AZ::TransformBus::Events::GetWorldTM, AZ::NonUniformScaleRequests::GetScale and GetCurrentLocalTransform //! and combine their effects. From c806b41cffe9563153fc9675796df7b5e006f235 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 11 Feb 2022 13:36:40 +0000 Subject: [PATCH 089/133] make aabb shape component incompatible with non-uniform scale component Signed-off-by: greerdv --- .../Shape/AxisAlignedBoxShapeComponent.cpp | 11 +-- .../Shape/AxisAlignedBoxShapeComponent.h | 2 - .../EditorAxisAlignedBoxShapeComponent.cpp | 9 +-- .../EditorAxisAlignedBoxShapeComponent.h | 2 +- .../Code/Tests/AxisAlignedBoxShapeTest.cpp | 71 ------------------- 5 files changed, 8 insertions(+), 87 deletions(-) diff --git a/Gems/LmbrCentral/Code/Source/Shape/AxisAlignedBoxShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/AxisAlignedBoxShapeComponent.cpp index 7f919bc097..0b1848eb4b 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/AxisAlignedBoxShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/AxisAlignedBoxShapeComponent.cpp @@ -27,6 +27,7 @@ namespace LmbrCentral { incompatible.push_back(AZ_CRC_CE("ShapeService")); incompatible.push_back(AZ_CRC_CE("AxisAlignedBoxShapeService")); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void AxisAlignedBoxShapeComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) @@ -34,11 +35,6 @@ namespace LmbrCentral required.push_back(AZ_CRC_CE("TransformService")); } - void AxisAlignedBoxShapeComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) - { - dependent.push_back(AZ_CRC_CE("NonUniformScaleService")); - } - void AxisAlignedBoxShapeDebugDisplayComponent::Reflect(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast(context)) @@ -54,8 +50,6 @@ namespace LmbrCentral { EntityDebugDisplayComponent::Activate(); ShapeComponentNotificationsBus::Handler::BusConnect(GetEntityId()); - m_nonUniformScale = AZ::Vector3::CreateOne(); - AZ::NonUniformScaleRequestBus::EventResult(m_nonUniformScale, GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); } void AxisAlignedBoxShapeDebugDisplayComponent::Deactivate() @@ -74,7 +68,7 @@ namespace LmbrCentral transform.SetRotation(AZ::Quaternion::CreateIdentity()); saveMatrix = debugDisplay.PopPremultipliedMatrix(); debugDisplay.PushMatrix(transform); - DrawBoxShape(drawParams, m_boxShapeConfig, debugDisplay, m_nonUniformScale); + DrawBoxShape(drawParams, m_boxShapeConfig, debugDisplay); debugDisplay.PopMatrix(); debugDisplay.PushPremultipliedMatrix(saveMatrix); } @@ -104,7 +98,6 @@ namespace LmbrCentral if (changeReason == ShapeChangeReasons::ShapeChanged) { BoxShapeComponentRequestsBus::EventResult(m_boxShapeConfig, GetEntityId(), &BoxShapeComponentRequests::GetBoxConfiguration); - AZ::NonUniformScaleRequestBus::EventResult(m_nonUniformScale, GetEntityId(), &AZ::NonUniformScaleRequests::GetScale); } } diff --git a/Gems/LmbrCentral/Code/Source/Shape/AxisAlignedBoxShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/AxisAlignedBoxShapeComponent.h index e180e1d536..9e6060914f 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/AxisAlignedBoxShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/AxisAlignedBoxShapeComponent.h @@ -33,7 +33,6 @@ namespace LmbrCentral static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); - static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); AxisAlignedBoxShape m_aaboxShape; ///< Stores underlying box type for this component. }; @@ -65,6 +64,5 @@ namespace LmbrCentral void OnShapeChanged(ShapeChangeReasons changeReason) override; BoxShapeConfig m_boxShapeConfig; ///< Stores configuration data for box shape. - AZ::Vector3 m_nonUniformScale = AZ::Vector3::CreateOne(); ///< Caches non-uniform scale for this entity. }; } // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp index f78f2f048d..e8be486731 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.cpp @@ -89,9 +89,10 @@ namespace LmbrCentral provided.push_back(AZ_CRC_CE("AxisAlignedBoxShapeService")); } - void EditorAxisAlignedBoxShapeComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) + void EditorAxisAlignedBoxShapeComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { - dependent.push_back(AZ_CRC_CE("NonUniformScaleService")); + EditorBaseShapeComponent::GetIncompatibleServices(incompatible); + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); } void EditorAxisAlignedBoxShapeComponent::DisplayEntityViewport( @@ -104,7 +105,7 @@ namespace LmbrCentral { DrawBoxShape( { m_aaboxShape.GetBoxConfiguration().GetDrawColor(), m_shapeWireColor, m_aaboxShape.GetBoxConfiguration().IsFilled() }, - m_aaboxShape.GetBoxConfiguration(), debugDisplay, m_aaboxShape.GetCurrentNonUniformScale()); + m_aaboxShape.GetBoxConfiguration(), debugDisplay); }, m_aaboxShape.GetCurrentTransform()); } @@ -163,6 +164,6 @@ namespace LmbrCentral AZ::Vector3 EditorAxisAlignedBoxShapeComponent::GetBoxScale() { - return AZ::Vector3(m_aaboxShape.GetCurrentTransform().GetUniformScale() * m_aaboxShape.GetCurrentNonUniformScale()); + return AZ::Vector3(m_aaboxShape.GetCurrentTransform().GetUniformScale()); } } // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.h b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.h index 8bff4ea7e1..786a18b989 100644 --- a/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.h +++ b/Gems/LmbrCentral/Code/Source/Shape/EditorAxisAlignedBoxShapeComponent.h @@ -38,7 +38,7 @@ namespace LmbrCentral protected: static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); // EditorComponentBase void BuildGameEntity(AZ::Entity* gameEntity) override; diff --git a/Gems/LmbrCentral/Code/Tests/AxisAlignedBoxShapeTest.cpp b/Gems/LmbrCentral/Code/Tests/AxisAlignedBoxShapeTest.cpp index c3e8d06791..a0f3b9e7a9 100644 --- a/Gems/LmbrCentral/Code/Tests/AxisAlignedBoxShapeTest.cpp +++ b/Gems/LmbrCentral/Code/Tests/AxisAlignedBoxShapeTest.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include #include #include @@ -26,7 +25,6 @@ namespace UnitTest AZStd::unique_ptr m_transformComponentDescriptor; AZStd::unique_ptr m_axisAlignedBoxShapeComponentDescriptor; AZStd::unique_ptr m_axisAlignedBoxShapeDebugDisplayComponentDescriptor; - AZStd::unique_ptr m_nonUniformScaleComponentDescriptor; public: void SetUp() override @@ -43,9 +41,6 @@ namespace UnitTest m_axisAlignedBoxShapeDebugDisplayComponentDescriptor = AZStd::unique_ptr(LmbrCentral::AxisAlignedBoxShapeDebugDisplayComponent::CreateDescriptor()); m_axisAlignedBoxShapeDebugDisplayComponentDescriptor->Reflect(&(*m_serializeContext)); - m_nonUniformScaleComponentDescriptor = - AZStd::unique_ptr(AzFramework::NonUniformScaleComponent::CreateDescriptor()); - m_nonUniformScaleComponentDescriptor->Reflect(&(*m_serializeContext)); } void TearDown() override @@ -53,7 +48,6 @@ namespace UnitTest m_transformComponentDescriptor.reset(); m_axisAlignedBoxShapeComponentDescriptor.reset(); m_axisAlignedBoxShapeDebugDisplayComponentDescriptor.reset(); - m_nonUniformScaleComponentDescriptor.reset(); m_serializeContext.reset(); AllocatorsFixture::TearDown(); } @@ -73,23 +67,6 @@ namespace UnitTest entity.GetId(), &LmbrCentral::BoxShapeComponentRequestsBus::Events::SetBoxDimensions, dimensions); } - void CreateAxisAlignedBoxWithNonUniformScale( - const AZ::Transform& transform, const AZ::Vector3& nonUniformScale, const AZ::Vector3& dimensions, AZ::Entity& entity) - { - entity.CreateComponent(); - entity.CreateComponent(); - entity.CreateComponent(); - entity.CreateComponent(); - - entity.Init(); - entity.Activate(); - - AZ::TransformBus::Event(entity.GetId(), &AZ::TransformBus::Events::SetWorldTM, transform); - LmbrCentral::BoxShapeComponentRequestsBus::Event( - entity.GetId(), &LmbrCentral::BoxShapeComponentRequestsBus::Events::SetBoxDimensions, dimensions); - AZ::NonUniformScaleRequestBus::Event(entity.GetId(), &AZ::NonUniformScaleRequests::SetScale, nonUniformScale); - } - void CreateDefaultAxisAlignedBox(const AZ::Transform& transform, AZ::Entity& entity) { CreateAxisAlignedBox(transform, AZ::Vector3(10.0f, 10.0f, 10.0f), entity); @@ -187,52 +164,4 @@ namespace UnitTest EXPECT_TRUE(rayHit); EXPECT_NEAR(distance, 4.0f, 1e-2f); } - - TEST_F(AxisAlignedBoxShapeTest, RayIntersectWithBoxRotatedNonUniformScale) - { - AZ::Entity entity; - CreateAxisAlignedBoxWithNonUniformScale( - AZ::Transform( - AZ::Vector3(2.0f, -5.0f, 3.0f), AZ::Quaternion::CreateFromAxisAngle(AZ::Vector3::CreateAxisY(), AZ::Constants::QuarterPi), - 0.5f), - AZ::Vector3(2.2f, 1.8f, 0.4f), AZ::Vector3(0.2f, 2.6f, 1.2f), entity); - - // This test creates a box of dimensions (2.2, 1.8, 0.4) centered on (2.0, -5, 3) and rotated about the Y axis by 45 degrees. - // The box is tested for axis-alignment by firing various rays and ensuring they either hit or miss the box. Any failure here - // would show the box has been rotated. - - // Ray should just miss the box - bool rayHit = false; - float distance = AZ::Constants::FloatMax; - LmbrCentral::ShapeComponentRequestsBus::EventResult( - rayHit, entity.GetId(), &LmbrCentral::ShapeComponentRequests::IntersectRay, AZ::Vector3(1.8f, -6.2f, 3.0f), - AZ::Vector3(1.0f, 0.0f, 0.0f), distance); - EXPECT_FALSE(rayHit); - - // Ray should just hit the box - rayHit = false; - distance = AZ::Constants::FloatMax; - LmbrCentral::ShapeComponentRequestsBus::EventResult( - rayHit, entity.GetId(), &LmbrCentral::ShapeComponentRequests::IntersectRay, AZ::Vector3(1.8f, -6.1f, 3.0f), - AZ::Vector3(1.0f, 0.0f, 0.0f), distance); - EXPECT_TRUE(rayHit); - EXPECT_NEAR(distance, 0.09f, 1e-3f); - - // Ray should just miss the box - rayHit = false; - distance = AZ::Constants::FloatMax; - LmbrCentral::ShapeComponentRequestsBus::EventResult( - rayHit, entity.GetId(), &LmbrCentral::ShapeComponentRequests::IntersectRay, AZ::Vector3(2.2f, -6.2f, 3.0f), - AZ::Vector3(0.0f, 1.0f, 0.0f), distance); - EXPECT_FALSE(rayHit); - - // Ray should just hit the box - rayHit = false; - distance = AZ::Constants::FloatMax; - LmbrCentral::ShapeComponentRequestsBus::EventResult( - rayHit, entity.GetId(), &LmbrCentral::ShapeComponentRequests::IntersectRay, AZ::Vector3(2.1f, -6.2f, 3.0f), - AZ::Vector3(0.0f, 1.0f, 0.0f), distance); - EXPECT_TRUE(rayHit); - EXPECT_NEAR(distance, 0.03f, 1e-3f); - } } // namespace UnitTest From a2b7f90a78e9eb55a0ee93049dc94a06535634a9 Mon Sep 17 00:00:00 2001 From: Olex Lozitskiy <5432499+AMZN-Olex@users.noreply.github.com> Date: Fri, 11 Feb 2022 11:26:52 -0500 Subject: [PATCH 090/133] Disabling problematic NetBindComponent assert with a configuration option. Signed-off-by: Olex Lozitskiy <5432499+AMZN-Olex@users.noreply.github.com> --- .../Code/Source/Components/NetBindComponent.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index beb17ed9f6..d29e09881c 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -22,6 +22,9 @@ #include #include +AZ_CVAR(bool, bg_AssertNetBindOnDeactrivationWithoutMarkForRemoval, false, nullptr, AZ::ConsoleFunctorFlags::Null, + "If true, assert when a multiplayer entity is deactivated without first calling MarkForRemoval from NetworkEntityManager."); + namespace Multiplayer { void NetBindComponent::Reflect(AZ::ReflectContext* context) @@ -167,10 +170,13 @@ namespace Multiplayer void NetBindComponent::Deactivate() { - AZ_Assert( - m_needsToBeStopped == false, - "Entity (%s) appears to have been improperly deleted. Use MarkForRemoval to correctly clean up a networked entity.", - GetEntity() ? GetEntity()->GetName().c_str() : "null"); + if (bg_AssertNetBindOnDeactrivationWithoutMarkForRemoval) + { + AZ_Assert( + m_needsToBeStopped == false, + "Entity (%s) appears to have been improperly deleted. Use MarkForRemoval to correctly clean up a networked entity.", + GetEntity() ? GetEntity()->GetName().c_str() : "null"); + } m_handleLocalServerRpcMessageEventHandle.Disconnect(); if (NetworkRoleHasController(m_netEntityRole)) { From dbb4e76a3da883f4b0c196798cbf234294e7f602 Mon Sep 17 00:00:00 2001 From: evanchia-ly-sdets <80914607+evanchia-ly-sdets@users.noreply.github.com> Date: Fri, 11 Feb 2022 09:02:22 -0800 Subject: [PATCH 091/133] updating python packages py, pillow, and urllib3 (#7155) * updating python packages py, pillow, and urllib3 Signed-off-by: evanchia * updating dependencies versions as well Signed-off-by: evanchia --- python/requirements.txt | 105 +++++++++++++++++++++++----------------- 1 file changed, 60 insertions(+), 45 deletions(-) diff --git a/python/requirements.txt b/python/requirements.txt index 9648a20ba0..c000be48de 100644 --- a/python/requirements.txt +++ b/python/requirements.txt @@ -6,13 +6,13 @@ attrs==20.1.0 \ --hash=sha256:0ef97238856430dcf9228e07f316aefc17e8939fc8507e18c6501b761ef1a42a \ --hash=sha256:2867b7b9f8326499ab5b0e2d12801fa5c98842d2cbd22b35112ae04bf85b4dff # via -r .\requirements.txt -boto3==1.12.21 \ - --hash=sha256:50105a25e301e20b361b2b8fafee196a425a4758e51f400a0f381d42e4bd909e \ - --hash=sha256:5fe70e656f92e4e649dc4cf05786f57d180e5d491bcb22c80411512ec2b27c15 \ +boto3==1.20.44 \ + --hash=sha256:26f18ca7411615f33d8d1bf60cc8efe5b331a57b3013d5f8f3587cd5350c27cb \ + --hash=sha256:4470f64e4af609ff678055338c96a6f7cbe601d1fb06a4ea7dc8d9223c2e527a \ # via -r .\requirements.txt -botocore==1.15.21 \ - --hash=sha256:4aaf6c94bcaace260138d32eae144be1b5d2ddce9ef0f395da32c68e106ff20f \ - --hash=sha256:86f7f1c489887f9e3c2ede598e2a30f8bd259c11e8ebe25e897e40231b3f4bc8 \ +botocore==1.23.44 \ + --hash=sha256:11483a493de4a76ef218d8cd3980c63550d006a0d082c10d53c0954184ca542a \ + --hash=sha256:8e5317f84fc1118bff58fa6fa79a9b62083e75a2a9c62feb3ea73694c550b99d \ # via -r .\requirements.txt, boto3, s3transfer certifi==2019.11.28 \ --hash=sha256:017c25db2a153ce562900032d5bc68e9f191e44e9a0f762f373977de9df1fbb3 \ @@ -22,6 +22,11 @@ chardet==3.0.4 \ --hash=sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae \ --hash=sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691 \ # via -r .\requirements.txt, requests +charset-normalizer==2.0.10 \ + --hash=sha256:876d180e9d7432c5d1dfd4c5d26b72f099d503e8fcc0feb7532c9289be60fcbd \ + --hash=sha256:cb957888737fc0bbcd78e3df769addb41fd1ff8cf950dc9e7ad7793f1bf44455 \ + # via + # -r requirements.txt, requests colorama==0.4.3 \ --hash=sha256:7d73d2a99753107a36ac6b455ee49046802e59d9d076ef8e47b61499fa29afff \ --hash=sha256:e96da0d330793e2cb9485e9ddfd918d456036c7149416295932478192f4436a1 \ @@ -129,30 +134,40 @@ packaging==20.4 \ --hash=sha256:4357f74f47b9c12db93624a82154e9b120fa8293699949152b22065d556079f8 \ --hash=sha256:998416ba6962ae7fbd6596850b80e17859a5753ba17c32284f67bfff33784181 \ # pytest -pillow==7.0.0 \ - --hash=sha256:0a628977ac2e01ca96aaae247ec2bd38e729631ddf2221b4b715446fd45505be \ - --hash=sha256:4d9ed9a64095e031435af120d3c910148067087541131e82b3e8db302f4c8946 \ - --hash=sha256:54ebae163e8412aff0b9df1e88adab65788f5f5b58e625dc5c7f51eaf14a6837 \ - --hash=sha256:5bfef0b1cdde9f33881c913af14e43db69815c7e8df429ceda4c70a5e529210f \ - --hash=sha256:5f3546ceb08089cedb9e8ff7e3f6a7042bb5b37c2a95d392fb027c3e53a2da00 \ - --hash=sha256:5f7ae9126d16194f114435ebb79cc536b5682002a4fa57fa7bb2cbcde65f2f4d \ - --hash=sha256:62a889aeb0a79e50ecf5af272e9e3c164148f4bd9636cc6bcfa182a52c8b0533 \ - --hash=sha256:7406f5a9b2fd966e79e6abdaf700585a4522e98d6559ce37fc52e5c955fade0a \ - --hash=sha256:8453f914f4e5a3d828281a6628cf517832abfa13ff50679a4848926dac7c0358 \ - --hash=sha256:87269cc6ce1e3dee11f23fa515e4249ae678dbbe2704598a51cee76c52e19cda \ - --hash=sha256:875358310ed7abd5320f21dd97351d62de4929b0426cdb1eaa904b64ac36b435 \ - --hash=sha256:8ac6ce7ff3892e5deaab7abaec763538ffd011f74dc1801d93d3c5fc541feee2 \ - --hash=sha256:91b710e3353aea6fc758cdb7136d9bbdcb26b53cefe43e2cba953ac3ee1d3313 \ - --hash=sha256:9d2ba4ed13af381233e2d810ff3bab84ef9f18430a9b336ab69eaf3cd24299ff \ - --hash=sha256:a62ec5e13e227399be73303ff301f2865bf68657d15ea50b038d25fc41097317 \ - --hash=sha256:ab76e5580b0ed647a8d8d2d2daee170e8e9f8aad225ede314f684e297e3643c2 \ - --hash=sha256:bf4003aa538af3f4205c5fac56eacaa67a6dd81e454ffd9e9f055fff9f1bc614 \ - --hash=sha256:bf598d2e37cf8edb1a2f26ed3fb255191f5232badea4003c16301cb94ac5bdd0 \ - --hash=sha256:c18f70dc27cc5d236f10e7834236aff60aadc71346a5bc1f4f83a4b3abee6386 \ - --hash=sha256:c5ed816632204a2fc9486d784d8e0d0ae754347aba99c811458d69fcdfd2a2f9 \ - --hash=sha256:dc058b7833184970d1248135b8b0ab702e6daa833be14035179f2acb78ff5636 \ - --hash=sha256:ff3797f2f16bf9d17d53257612da84dd0758db33935777149b3334c01ff68865 \ - # via requirements.txt, imageio +pillow==9.0.0 \ + --hash=sha256:03b27b197deb4ee400ed57d8d4e572d2d8d80f825b6634daf6e2c18c3c6ccfa6 \ + --hash=sha256:0b281fcadbb688607ea6ece7649c5d59d4bbd574e90db6cd030e9e85bde9fecc \ + --hash=sha256:0ebd8b9137630a7bbbff8c4b31e774ff05bbb90f7911d93ea2c9371e41039b52 \ + --hash=sha256:113723312215b25c22df1fdf0e2da7a3b9c357a7d24a93ebbe80bfda4f37a8d4 \ + --hash=sha256:2d16b6196fb7a54aff6b5e3ecd00f7c0bab1b56eee39214b2b223a9d938c50af \ + --hash=sha256:2fd8053e1f8ff1844419842fd474fc359676b2e2a2b66b11cc59f4fa0a301315 \ + --hash=sha256:31b265496e603985fad54d52d11970383e317d11e18e856971bdbb86af7242a4 \ + --hash=sha256:3586e12d874ce2f1bc875a3ffba98732ebb12e18fb6d97be482bd62b56803281 \ + --hash=sha256:47f5cf60bcb9fbc46011f75c9b45a8b5ad077ca352a78185bd3e7f1d294b98bb \ + --hash=sha256:490e52e99224858f154975db61c060686df8a6b3f0212a678e5d2e2ce24675c9 \ + --hash=sha256:500d397ddf4bbf2ca42e198399ac13e7841956c72645513e8ddf243b31ad2128 \ + --hash=sha256:52abae4c96b5da630a8b4247de5428f593465291e5b239f3f843a911a3cf0105 \ + --hash=sha256:6579f9ba84a3d4f1807c4aab4be06f373017fc65fff43498885ac50a9b47a553 \ + --hash=sha256:68e06f8b2248f6dc8b899c3e7ecf02c9f413aab622f4d6190df53a78b93d97a5 \ + --hash=sha256:6c5439bfb35a89cac50e81c751317faea647b9a3ec11c039900cd6915831064d \ + --hash=sha256:72c3110228944019e5f27232296c5923398496b28be42535e3b2dc7297b6e8b6 \ + --hash=sha256:72f649d93d4cc4d8cf79c91ebc25137c358718ad75f99e99e043325ea7d56100 \ + --hash=sha256:7aaf07085c756f6cb1c692ee0d5a86c531703b6e8c9cae581b31b562c16b98ce \ + --hash=sha256:80fe92813d208ce8aa7d76da878bdc84b90809f79ccbad2a288e9bcbeac1d9bd \ + --hash=sha256:95545137fc56ce8c10de646074d242001a112a92de169986abd8c88c27566a05 \ + --hash=sha256:97b6d21771da41497b81652d44191489296555b761684f82b7b544c49989110f \ + --hash=sha256:98cb63ca63cb61f594511c06218ab4394bf80388b3d66cd61d0b1f63ee0ea69f \ + --hash=sha256:9f3b4522148586d35e78313db4db0df4b759ddd7649ef70002b6c3767d0fdeb7 \ + --hash=sha256:a09a9d4ec2b7887f7a088bbaacfd5c07160e746e3d47ec5e8050ae3b2a229e9f \ + --hash=sha256:b5050d681bcf5c9f2570b93bee5d3ec8ae4cf23158812f91ed57f7126df91762 \ + --hash=sha256:bb47a548cea95b86494a26c89d153fd31122ed65255db5dcbc421a2d28eb3379 \ + --hash=sha256:bc462d24500ba707e9cbdef436c16e5c8cbf29908278af053008d9f689f56dee \ + --hash=sha256:c2067b3bb0781f14059b112c9da5a91c80a600a97915b4f48b37f197895dd925 \ + --hash=sha256:d154ed971a4cc04b93a6d5b47f37948d1f621f25de3e8fa0c26b2d44f24e3e8f \ + --hash=sha256:d5dcea1387331c905405b09cdbfb34611050cc52c865d71f2362f354faee1e9f \ + --hash=sha256:ee6e2963e92762923956fe5d3479b1fdc3b76c83f290aad131a2f98c3df0593e \ + --hash=sha256:fd0e5062f11cb3e730450a7d9f323f4051b532781026395c4323b8ad055523c4 \ + # via -r requirements.txt pluggy==0.13.1 \ --hash=sha256:15b2acde666561e1298d71b523007ed7364de07029219b604cf808bfa1c765b0 \ --hash=sha256:966c145cd83c96502c3c3868f50408687b38434af77734af1e9ca461a4081d2d \ @@ -191,10 +206,10 @@ psutil==5.8.0 \ --hash=sha256:f4634b033faf0d968bb9220dd1c793b897ab7f1189956e1aa9eae752527127d3 \ --hash=sha256:fcc01e900c1d7bee2a37e5d6e4f9194760a93597c97fee89c4ae51701de03563 # via requirements.txt -py==1.9.0 \ - --hash=sha256:366389d1db726cd2fcfc79732e75410e5fe4d31db13692115529d34069a043c2 \ - --hash=sha256:9ca6883ce56b4e8da7e79ac18787889fa5206c79dcc67fb065376cd2fe03f342 \ - # via -r .\requirements.txt, pytest +py==1.11.0 \ + --hash=sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719 \ + --hash=sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378 \ + # via -r requirements.txt pyparsing==2.4.7 \ --hash=sha256:c203ec8783bf771a155b207279b9bccb8dea02d8f0c9e5f8ead507bc3246ecc1 \ --hash=sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b \ @@ -246,13 +261,13 @@ PyYAML==5.4.1 \ --hash=sha256:e4fac90784481d221a8e4b1162afa7c47ed953be40d31ab4629ae917510051df \ --hash=sha256:fa5ae20527d8e831e8230cbffd9f8fe952815b2b7dae6ffec25318803a7528fc \ # via requirements.txt -requests==2.23.0 \ - --hash=sha256:43999036bfa82904b6af1d99e4882b560e5e2c68e5c4b0aa03b655f3d7d73fee \ - --hash=sha256:b3f43d496c6daba4493e7c431722aeb7dbc6288f52a6e04e7b6023b0247817e6 \ - # via -r .\requirements.txt -s3transfer==0.3.3 \ - --hash=sha256:2482b4259524933a022d59da830f51bd746db62f047d6eb213f2f8855dcb8a13 \ - --hash=sha256:921a37e2aefc64145e7b73d50c71bb4f26f46e4c9f414dc648c6245ff92cf7db \ +requests==2.27.1 \ + --hash=sha256:68d7c56fd5a8999887728ef304a6d12edc7be74f1cfa47714fc8b414525c9a61 \ + --hash=sha256:f22fa1e554c9ddfd16e6e41ac79759e17be9e492b3587efa038054674760e72d \ + # via -r requirements.txt +s3transfer==0.5.0 \ + --hash=sha256:50ed823e1dc5868ad40c8dc92072f757aa0e653a192845c94a3b676f4a62da4c \ + --hash=sha256:9c1dc369814391a6bda20ebbf4b70a0f34630592c9aa520856bf384916af2803 \ # boto3 scipy==1.4.1 \ --hash=sha256:00af72998a46c25bdb5824d2b729e7dabec0c765f9deb0b504f928591f5ff9d4 \ @@ -290,10 +305,10 @@ smmap==3.0.5 \ --hash=sha256:7bfcf367828031dc893530a29cb35eb8c8f2d7c8f2d0989354d75d24c8573714 \ --hash=sha256:84c2751ef3072d4f6b2785ec7ee40244c6f45eb934d9e543e2c51f1bd3d54c50 \ # via smmap2 -urllib3==1.25.8 \ - --hash=sha256:2f3db8b19923a873b3e5256dc9c2dedfa883e33d87c690d9c7913e1f40673cdc \ - --hash=sha256:87716c2d2a7121198ebcb7ce7cccf6ce5e9ba539041cfbaeecfb641dc0bf6acc \ - # via -r .\requirements.txt, botocore, requests +urllib3==1.26.8 \ + --hash=sha256:000ca7f471a233c2251c6c7023ee85305721bfdf18621ebff4fd17a8653427ed \ + --hash=sha256:0e7c33d9a63e7ddfcb86780aac87befc2fbddf46c58dbb487e0855f7ceec283c \ + # via -r requirements.txt wcwidth==0.2.5 \ --hash=sha256:beb4802a9cebb9144e99086eff703a642a13d6a0052920003a230f3294bbe784 \ --hash=sha256:c4d647b99872929fdb7bdcaa4fbe7f01413ed3d98077df798530e5b04f116c83 \ From b67862a1331b6f31c50ffeb8cd7fadc8ce24ab4f Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Fri, 11 Feb 2022 09:37:12 -0800 Subject: [PATCH 092/133] Minor updates from code review feedback. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../Atom/RPI.Edit/Material/MaterialFunctorSourceData.h | 4 ++-- .../Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h | 3 ++- .../Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp | 2 +- .../RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp | 2 ++ .../MaterialEditor/Code/Source/Document/MaterialDocument.cpp | 3 +++ .../Code/Source/Material/EditorMaterialComponentInspector.cpp | 3 +++ 6 files changed, 13 insertions(+), 4 deletions(-) diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceData.h index 8bf88342c3..d26e70831b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialFunctorSourceData.h @@ -112,7 +112,7 @@ namespace AZ //! Returns the name context for the functor. //! It acts like a namespace for any names that the MaterialFunctorSourceData might reference. The namespace //! is automatically applied by the other relevant functions of this RuntimeContext class. - //! Not that by default the MaterialNameContext is not saved as part of the final MaterialFunctor class + //! Note that by default the MaterialNameContext is not saved as part of the final MaterialFunctor class //! (most CreateFunctor() implementations should convert names to indexes anyway) but CreateFunctor() can //! copy it to the created MaterialFunctor for use at runtime if needed. const MaterialNameContext* GetNameContext() const { return m_materialNameContext; } @@ -148,7 +148,7 @@ namespace AZ //! Returns the name context for the functor. //! It acts like a namespace for any names that the MaterialFunctorSourceData might reference. The namespace //! is automatically applied by the other relevant functions of this RuntimeContext class. - //! Not that by default the MaterialNameContext is not saved as part of the final MaterialFunctor class + //! Note that by default the MaterialNameContext is not saved as part of the final MaterialFunctor class //! (most CreateFunctor() implementations should convert names to indexes anyway) but CreateFunctor() can //! copy it to the created MaterialFunctor for use at runtime if needed. const MaterialNameContext* GetNameContext() const { return m_materialNameContext; } diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h index ee2a464290..f1e92a70ea 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Material/MaterialTypeSourceData.h @@ -331,7 +331,8 @@ namespace AZ //! Recursively populates a material type asset with properties from the tree of material property groups. //! @param materialTypeSourceFilePath path to the material type file that is being processed, used to look up relative paths - //! @param propertyIdContext the accumulated prefix that should be applied to any property names encountered in the current @propertyGroup + //! @param materialTypeAssetCreator properties will be added to this creator + //! @param materialNameContext the accumulated name context that should be applied to any property names or connection names encountered in the current @propertyGroup //! @param propertyGroup the current PropertyGroup that is being processed //! @return false if errors are detected and processing should abort bool BuildPropertyList( diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp index 2477360b8c..790b721fb7 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/LuaMaterialFunctorSourceData.cpp @@ -198,7 +198,7 @@ namespace AZ for (const Name& materialProperty : materialPropertyDependencies.GetValue()) { - Name propertyName{materialProperty.GetCStr()}; + Name propertyName{materialProperty}; functor->m_materialNameContext.ContextualizeProperty(propertyName); MaterialPropertyIndex index = propertiesLayout->FindPropertyIndex(propertyName); diff --git a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp index 67b468d5bb..85d1a4ccd9 100644 --- a/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Material/MaterialTypeSourceDataTests.cpp @@ -273,6 +273,8 @@ namespace UnitTest using AZ::RPI::MaterialFunctor::Process; void Process(AZ::RPI::MaterialFunctor::RuntimeContext&) override { + // Intentionally empty, this is where the functor would do it's normal processing, + // but all this test functor does is store the MaterialNameContext. } MaterialNameContext m_nameContext; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index d122a7fff4..13b2519368 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -566,6 +566,9 @@ namespace MaterialEditor AZStd::vector groupNameVector; AZStd::vector groupDisplayNameVector; + + groupNameVector.reserve(propertyGroupStack.size()); + groupDisplayNameVector.reserve(propertyGroupStack.size()); for (auto& group : propertyGroupStack) { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index 37ca44fa43..ff31f3382f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -289,6 +289,9 @@ namespace AZ AZStd::vector groupNameVector; AZStd::vector groupDisplayNameVector; + + groupNameVector.reserve(propertyGroupStack.size()); + groupDisplayNameVector.reserve(propertyGroupStack.size()); for (auto& nextGroup : propertyGroupStack) { From 5f334e30f979cf1d725d528ec6dc309fad5cae24 Mon Sep 17 00:00:00 2001 From: SWMasterson Date: Fri, 11 Feb 2022 09:58:43 -0800 Subject: [PATCH 093/133] Updated missing shaderball assets. (#7556) * Added missing shaderball assets and fixed typo in asset name. Signed-off-by: Sean Masterson * Removed unnecessary files and updated macbeth_shaderballs level Signed-off-by: Sean Masterson --- .../macbeth_shaderballs.prefab | 315 +++++++----------- 1 file changed, 115 insertions(+), 200 deletions(-) diff --git a/AutomatedTesting/Levels/Graphics/macbeth_shaderballs/macbeth_shaderballs.prefab b/AutomatedTesting/Levels/Graphics/macbeth_shaderballs/macbeth_shaderballs.prefab index 22504f168a..69b1eac762 100644 --- a/AutomatedTesting/Levels/Graphics/macbeth_shaderballs/macbeth_shaderballs.prefab +++ b/AutomatedTesting/Levels/Graphics/macbeth_shaderballs/macbeth_shaderballs.prefab @@ -38,7 +38,10 @@ }, "Component_[7874177159288365422]": { "$type": "EditorEntitySortComponent", - "Id": 7874177159288365422 + "Id": 7874177159288365422, + "Child Entity Order": [ + "Entity_[471076350497]" + ] }, "Component_[8018146290632383969]": { "$type": "EditorEntityIconComponent", @@ -110,34 +113,14 @@ "Component_[16871442125196328877]": { "$type": "EditorEntitySortComponent", "Id": 16871442125196328877, - "ChildEntityOrderEntryArray": [ - { - "EntityId": "Entity_[604220336673]" - }, - { - "EntityId": "Entity_[599925369377]", - "SortIndex": 1 - }, - { - "EntityId": "Entity_[475371317793]", - "SortIndex": 2 - }, - { - "EntityId": "Entity_[509731056161]", - "SortIndex": 3 - }, - { - "EntityId": "Entity_[505436088865]", - "SortIndex": 4 - }, - { - "EntityId": "Entity_[539795827233]", - "SortIndex": 5 - }, - { - "EntityId": "Entity_[569860598305]", - "SortIndex": 6 - } + "Child Entity Order": [ + "Entity_[604220336673]", + "Entity_[599925369377]", + "Entity_[475371317793]", + "Entity_[509731056161]", + "Entity_[505436088865]", + "Entity_[539795827233]", + "Entity_[569860598305]" ] }, "Component_[18389136819207633744]": { @@ -263,10 +246,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -370,10 +353,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -477,10 +460,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -584,10 +567,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -691,10 +674,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -798,10 +781,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -905,10 +888,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -944,30 +927,13 @@ "Component_[11056805018150955063]": { "$type": "EditorEntitySortComponent", "Id": 11056805018150955063, - "ChildEntityOrderEntryArray": [ - { - "EntityId": "Entity_[488256219681]" - }, - { - "EntityId": "Entity_[483961252385]", - "SortIndex": 1 - }, - { - "EntityId": "Entity_[479666285089]", - "SortIndex": 2 - }, - { - "EntityId": "Entity_[492551186977]", - "SortIndex": 3 - }, - { - "EntityId": "Entity_[496846154273]", - "SortIndex": 4 - }, - { - "EntityId": "Entity_[501141121569]", - "SortIndex": 5 - } + "Child Entity Order": [ + "Entity_[488256219681]", + "Entity_[483961252385]", + "Entity_[479666285089]", + "Entity_[492551186977]", + "Entity_[496846154273]", + "Entity_[501141121569]" ] }, "Component_[11466054095979053511]": { @@ -1028,30 +994,13 @@ "Component_[11056805018150955063]": { "$type": "EditorEntitySortComponent", "Id": 11056805018150955063, - "ChildEntityOrderEntryArray": [ - { - "EntityId": "Entity_[522615958049]" - }, - { - "EntityId": "Entity_[518320990753]", - "SortIndex": 1 - }, - { - "EntityId": "Entity_[514026023457]", - "SortIndex": 2 - }, - { - "EntityId": "Entity_[526910925345]", - "SortIndex": 3 - }, - { - "EntityId": "Entity_[531205892641]", - "SortIndex": 4 - }, - { - "EntityId": "Entity_[535500859937]", - "SortIndex": 5 - } + "Child Entity Order": [ + "Entity_[522615958049]", + "Entity_[518320990753]", + "Entity_[514026023457]", + "Entity_[526910925345]", + "Entity_[531205892641]", + "Entity_[535500859937]" ] }, "Component_[11466054095979053511]": { @@ -1180,10 +1129,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -1287,10 +1236,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -1394,10 +1343,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -1501,10 +1450,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -1608,10 +1557,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -1715,10 +1664,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -1754,30 +1703,13 @@ "Component_[11056805018150955063]": { "$type": "EditorEntitySortComponent", "Id": 11056805018150955063, - "ChildEntityOrderEntryArray": [ - { - "EntityId": "Entity_[552680729121]" - }, - { - "EntityId": "Entity_[548385761825]", - "SortIndex": 1 - }, - { - "EntityId": "Entity_[544090794529]", - "SortIndex": 2 - }, - { - "EntityId": "Entity_[556975696417]", - "SortIndex": 3 - }, - { - "EntityId": "Entity_[561270663713]", - "SortIndex": 4 - }, - { - "EntityId": "Entity_[565565631009]", - "SortIndex": 5 - } + "Child Entity Order": [ + "Entity_[552680729121]", + "Entity_[548385761825]", + "Entity_[544090794529]", + "Entity_[556975696417]", + "Entity_[561270663713]", + "Entity_[565565631009]" ] }, "Component_[11466054095979053511]": { @@ -1906,10 +1838,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2013,10 +1945,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2120,10 +2052,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2227,10 +2159,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2334,10 +2266,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2441,10 +2373,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2480,30 +2412,13 @@ "Component_[11056805018150955063]": { "$type": "EditorEntitySortComponent", "Id": 11056805018150955063, - "ChildEntityOrderEntryArray": [ - { - "EntityId": "Entity_[582745500193]" - }, - { - "EntityId": "Entity_[578450532897]", - "SortIndex": 1 - }, - { - "EntityId": "Entity_[574155565601]", - "SortIndex": 2 - }, - { - "EntityId": "Entity_[587040467489]", - "SortIndex": 3 - }, - { - "EntityId": "Entity_[591335434785]", - "SortIndex": 4 - }, - { - "EntityId": "Entity_[595630402081]", - "SortIndex": 5 - } + "Child Entity Order": [ + "Entity_[582745500193]", + "Entity_[578450532897]", + "Entity_[574155565601]", + "Entity_[587040467489]", + "Entity_[591335434785]", + "Entity_[595630402081]" ] }, "Component_[11466054095979053511]": { @@ -2632,10 +2547,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2739,10 +2654,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2846,10 +2761,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -2953,10 +2868,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -3060,10 +2975,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } @@ -3167,10 +3082,10 @@ "Configuration": { "ModelAsset": { "assetId": { - "guid": "{D0F73AAF-52B7-507C-B045-DBE2FE2D4403}", - "subId": 268677693 + "guid": "{FD340C30-755C-5911-92A3-19A3F7A77931}", + "subId": 281415304 }, - "assetHint": "objects/shaderball_simple/shaberball_simple_1m.azmodel" + "assetHint": "objects/shaderball/shaderball_default_1m.azmodel" }, "LodOverride": 255 } From b829c08f758b8132e98f1ede8e81c96a9ff6ddfb Mon Sep 17 00:00:00 2001 From: santorac <55155825+santorac@users.noreply.github.com> Date: Fri, 11 Feb 2022 10:12:57 -0800 Subject: [PATCH 094/133] Fixed build error. Added error message if material type file JSON import fails. Signed-off-by: santorac <55155825+santorac@users.noreply.github.com> --- .../RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp index 1af62d1247..f4653a076e 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp @@ -97,6 +97,12 @@ namespace AZ importSettings.m_importer = &jsonImporter; importSettings.m_loadedJsonPath = filePath; AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::ResolveImports(document->GetObject(), document->GetAllocator(), importSettings); + if (result.GetProcessing() != AZ::JsonSerializationResult::Processing::Completed) + { + AZ_Error("MaterialUtils", false, "%s", result.ToString(filePath).c_str()); + return AZ::Failure(); + } + if (importedFiles) { *importedFiles = importSettings.m_importer->GetImportedFiles(); From d7ee248df5f7362d61f27d1a2e036fa5a57d3411 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Fri, 11 Feb 2022 12:50:12 -0600 Subject: [PATCH 095/133] Range adaptor support (#7388) * Updated the SFINAE checks in concepts.h and range.h To use conjunction and disjunction for short-circuiting behavior. Replaced AZStd::optional implementation with std::optional alias Added range adaptor support and the following views: ref_view, owning_view Added bitwise or(|) overload for chaining range adaptor closures together Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding indirectly invocable concepts. These concepts are used to determine whether a callable can be invoked with a dereferenced iterator instance. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Add implementation of range relational function objects Add implementation of range min max functions which uses the range relation function objects(ranges::less, ranges::equal_to, etc...) This is needed to implement ranges::zip_view Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding interface for zip_view which compiles successfully The implementation for the zip view functions still need to be filled. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding function definitions for zip_view classes. Adding empty header of subrange.h for the ranges::subrange class Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding additional view implementations. The following range and view classes have been added: empty_view, single_view and subrange. Moved the AZ_NO_UNIQUE_ADDRESS macro to PlatformDef.h to allow other code to specify the [[no_unique_address]] attribute. Added additional test for view structures. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding missing includes for non-unity builds Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Workaround for NDK21 clang 9.0.9 compile issue. The AZStd::ranges::zip_view::iterator::iter_swap friend function is in the AZStd::ranges namespace, while the customization point object of `AZStd::ranges::customization_point_object::iter_swap` is in the regular namespace of `AZStd::ranges` and the inline namespace of `customization_point`. This issue is fixed in NDK23, but as Jenkins uses NDK21 at the time, the entire zip_view implementation has moved to inline namespace of `zip_view_internal` Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Added iterator algorithm requiremetn concepts Fixed the ambiguity in the ranges::iter_swap exchange overload to exclude itself as a candidate if the iterator reference types are swappable with each other. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding type alias for borrowed_subrange_t Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Fixed convertible to ref_view check in the ranges::all customization_point Updated SFINAE detection of whether AZStd::to_address is invocable Moved the Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Fixed private variable access in ranges::subrange get specialization. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Removing ranges::view constraint from the ranges::views::single customization_point. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding C++23 range overload for string_view. It is detailed in the [C++draft strings](https://eel.is/c++draft/strings#lib:basic_string_view,constructor____) section Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding implementations of ranges, find, search, mismatch and equal functions. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding implementation of ranges split_view along with test. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding const overloads to SceneAPI ProxyPointer container The Proxy Pointer class operator* and operator-> was unable to be invoked with a const instance before. Now it returns a const view of the pointer it contains. This allows it to be invoked in `AZStd::to_address` as part of an SINAE context for the contiguous_iterator concept Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Refactored the to_address implementation to better work with SFINAE. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding general non-unity build fixes This is unrelated to the RangeAdaptor changes. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Allow range algorithms to be used with rvalue ranges Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Workaround MSVC Internal Compiler erroy by removing enable_if condition in the operator bool of the view_interface class. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Corrected the non_propagating_cache helper class to have public functions Fixed the order of creating the perfect forwarding call wrapper for an outer closure around another closure. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Specialized the borrowed_range and view concepts For the AZ PathView class, since it is a immutable view around a path. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Removed inline namespace around the zip_view class. It was needed to workaround a clang 10 or below issue where a friend function in a namespace and a variable within underneath an inline namespace within the function namespace would cause an improper symbol redefinition. The workaround is to create a placeholder namespace containing the inline namespace and then bring that placeholder namespace into the parent scope. https://bugs.llvm.org/show_bug.cgi?id=37556 Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding implementation of the elemetns_view and join_view classes It is up to date with the standard as of the current draft: https://eel.is/c++draft/ranges. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Separated definitions of concepts out of concepts.h This allows the ranges::iter_swap and ranges::swap customization point to be moved outside of the concepts folder and into the ranges folder. The concepts.h header previously had to define those objects to avoid circular dependencies. Added the work around for ranges::iter_swap and ranges::iter_move customization_point causing an improper symbol redefinition in clang 10 or below: https://bugs.llvm.org/show_bug.cgi?id=37556 Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Alias more std:: names into the AZStd namespace. Removed our custom implementation of toaddress. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding more range view test. The join_view and elements_view classes now have UnitTest. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Adding deduction guides for AZStd associative containers Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Moved zip_view::sentinel iterator accessor function to zip_view.inl Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Fixed variable shadowing issues with clang 12+ Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/IO/Path/Path.h | 5 +- Code/Framework/AzCore/AzCore/IO/Path/Path.inl | 16 +- Code/Framework/AzCore/AzCore/PlatformDef.h | 11 +- .../AzCore/RTTI/AzStdOnDemandReflection.inl | 5 +- Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h | 14 +- .../AzCore/Serialization/AZStdContainers.inl | 4 +- .../AzCore/Threading/ThreadSafeObject.h | 1 + .../AzCore/AzCore/std/azstd_files.cmake | 20 + .../AzCore/AzCore/std/concepts/concepts.h | 793 ++++++------- .../AzCore/std/concepts/concepts_assignable.h | 34 + .../std/concepts/concepts_constructible.h | 26 + .../AzCore/std/concepts/concepts_copyable.h | 60 + .../AzCore/std/concepts/concepts_movable.h | 35 + .../AzCore/AzCore/std/containers/map.h | 48 +- .../AzCore/std/containers/node_handle.h | 23 +- .../AzCore/AzCore/std/containers/set.h | 46 +- .../AzCore/std/containers/unordered_map.h | 123 +- .../AzCore/std/containers/unordered_set.h | 103 +- .../AzCore/AzCore/std/function/identity.h | 2 +- .../AzCore/AzCore/std/function/invoke.h | 16 + Code/Framework/AzCore/AzCore/std/iterator.h | 4 - .../AzCore/std/iterator/iterator_primitives.h | 129 ++- Code/Framework/AzCore/AzCore/std/optional.h | 1006 +---------------- .../AzCore/AzCore/std/ranges/all_view.h | 67 ++ .../AzCore/AzCore/std/ranges/elements_view.h | 475 ++++++++ .../AzCore/AzCore/std/ranges/empty_view.h | 37 + .../AzCore/AzCore/std/ranges/iter_move.h | 12 +- .../AzCore/AzCore/std/ranges/iter_swap.h | 120 ++ .../AzCore/AzCore/std/ranges/join_view.h | 430 +++++++ .../AzCore/AzCore/std/ranges/owning_view.h | 114 ++ .../AzCore/AzCore/std/ranges/ranges.h | 429 ++++--- .../AzCore/AzCore/std/ranges/ranges_adaptor.h | 333 ++++++ .../AzCore/std/ranges/ranges_algorithm.h | 996 ++++++++++++++++ .../AzCore/std/ranges/ranges_functional.h | 121 ++ .../AzCore/AzCore/std/ranges/ref_view.h | 77 ++ .../AzCore/AzCore/std/ranges/single_view.h | 89 ++ .../AzCore/AzCore/std/ranges/split_view.h | 235 ++++ .../AzCore/AzCore/std/ranges/subrange.h | 290 +++++ .../Framework/AzCore/AzCore/std/ranges/swap.h | 116 ++ .../AzCore/AzCore/std/ranges/zip_view.h | 395 +++++++ .../AzCore/AzCore/std/ranges/zip_view.inl | 308 +++++ .../AzCore/AzCore/std/string/string_view.h | 41 + Code/Framework/AzCore/AzCore/std/tuple.h | 20 +- .../AzCore/std/typetraits/conjunction.h | 26 +- .../AzCore/std/typetraits/disjunction.h | 25 +- .../AzCore/std/typetraits/is_constructible.h | 43 +- .../AzCore/AzCore/std/typetraits/negation.h | 12 +- Code/Framework/AzCore/AzCore/std/utils.h | 114 +- .../AzCore/Tests/AZStd/ConceptsTests.cpp | 119 ++ .../Tests/AZStd/RangesAlgorithmTests.cpp | 250 ++++ .../AzCore/Tests/AZStd/RangesViewTests.cpp | 483 ++++++++ Code/Framework/AzCore/Tests/Main.cpp | 1 + .../AzCore/Tests/azcoretests_files.cmake | 2 + .../AzFramework/Viewport/ClickDetector.h | 3 +- .../LuaIDE/Source/LUA/BreakpointPanel.cpp | 2 +- .../Containers/Utilities/ProxyPointer.h | 6 +- .../Containers/Utilities/ProxyPointer.inl | 20 + .../Source/TestImpactCommandLineOptions.h | 1 + .../Atom/Feature/CoreLights/ShadowConstants.h | 3 +- .../Shader/ShaderVariantListSourceData.h | 3 +- .../AtomToolsAssetBrowserInteractions.h | 1 + .../Code/Source/PythonBuilderMessageSink.h | 1 + 62 files changed, 6486 insertions(+), 1858 deletions(-) create mode 100644 Code/Framework/AzCore/AzCore/std/concepts/concepts_assignable.h create mode 100644 Code/Framework/AzCore/AzCore/std/concepts/concepts_constructible.h create mode 100644 Code/Framework/AzCore/AzCore/std/concepts/concepts_copyable.h create mode 100644 Code/Framework/AzCore/AzCore/std/concepts/concepts_movable.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/all_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/elements_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/empty_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/iter_swap.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/join_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/owning_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/ranges_adaptor.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/ranges_algorithm.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/ranges_functional.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/ref_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/single_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/split_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/subrange.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/swap.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/zip_view.h create mode 100644 Code/Framework/AzCore/AzCore/std/ranges/zip_view.inl create mode 100644 Code/Framework/AzCore/Tests/AZStd/RangesAlgorithmTests.cpp create mode 100644 Code/Framework/AzCore/Tests/AZStd/RangesViewTests.cpp diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.h b/Code/Framework/AzCore/AzCore/IO/Path/Path.h index 235310a5da..3c2c4f0a8c 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.h +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.h @@ -709,7 +709,10 @@ namespace AZ::IO constexpr reference operator*() const; - constexpr pointer operator->() const; + constexpr pointer operator->() const + { + return &m_stashed_elem; + } constexpr PathIterator& operator++(); diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl index bde2353112..5046b43127 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl @@ -1397,12 +1397,6 @@ namespace AZ::IO return m_stashed_elem; } - template - constexpr auto PathIterator::operator->() const -> pointer - { - return &m_stashed_elem; - } - template constexpr auto PathIterator::operator++() -> PathIterator& { @@ -1542,3 +1536,13 @@ namespace AZ::IO extern template bool operator!=(const PathIterator& lhs, const PathIterator& rhs); } + +namespace AZStd::ranges +{ + // A PathView is a borrowed range, it does not own the content of the Path it is viewing + template<> + inline constexpr bool enable_borrowed_range = true; + + template<> + inline constexpr bool enable_view = true; +} diff --git a/Code/Framework/AzCore/AzCore/PlatformDef.h b/Code/Framework/AzCore/AzCore/PlatformDef.h index 8416099f15..d10b155127 100644 --- a/Code/Framework/AzCore/AzCore/PlatformDef.h +++ b/Code/Framework/AzCore/AzCore/PlatformDef.h @@ -83,7 +83,7 @@ #define AZ_PUSH_DISABLE_WARNING_GCC(_gccOption) /// Compiler specific AZ_POP_DISABLE_WARNING. This needs to be matched with the compiler specific AZ_PUSH_DISABLE_WARNINGs -#define AZ_POP_DISABLE_WARNING_CLANG +#define AZ_POP_DISABLE_WARNING_CLANG #define AZ_POP_DISABLE_WARNING_MSVC \ __pragma(warning(pop)) #define AZ_POP_DISABLE_WARNING_GCC @@ -176,7 +176,7 @@ #define AZ_PUSH_DISABLE_WARNING_3(_1, _2, _gccOption) AZ_PUSH_DISABLE_WARNING_GCC(_gccOption) /// Pops the warning stack. For use matched with an AZ_PUSH_DISABLE_WARNING -#define AZ_POP_DISABLE_WARNING +#define AZ_POP_DISABLE_WARNING _Pragma("GCC diagnostic pop") #endif // defined(AZ_COMPILER_CLANG) @@ -303,3 +303,10 @@ #if !defined(az_has_builtin_wmemmove) #define az_has_builtin_wmemmove false #endif + +// no unique address attribute support in C++17 +#if __has_cpp_attribute(no_unique_address) + #define AZ_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define AZ_NO_UNIQUE_ADDRESS +#endif diff --git a/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl b/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl index bba79e36f7..af814fbd32 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl +++ b/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl @@ -13,6 +13,7 @@ #include #include #include +#include #ifndef AZ_USE_CUSTOM_SCRIPT_BIND struct lua_State; @@ -47,10 +48,6 @@ namespace AZStd class intrusive_ptr; template class shared_ptr; - - // Wrapper types - template - class optional; } namespace AZ diff --git a/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h b/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h index 2cff17a638..0f292140dc 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h +++ b/Code/Framework/AzCore/AzCore/RTTI/TypeInfo.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -89,9 +90,6 @@ namespace AZStd template class function; - template - class optional; - struct monostate; template @@ -150,7 +148,7 @@ namespace AZ template