From 6b3abe3c56d5e267fc61c8341b9dcbf05051d876 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Sat, 24 Apr 2021 10:10:02 -0700 Subject: [PATCH 01/49] Cherrypick from 1.0 branch of... 6c2a243cdc3dbe8cf5cb2ec9063585255607f8e5 LYN-2905 Script Canvas: Saving a graph that contains an Item Variable crashes the Editor Added a check for m_shaderAsset.IsReady() before trying to use the asset data. Also added a check before calling BlockUntilLoadComplete() to prevent reporting an error message unnecessarily. --- .../RPI.Reflect/Material/ShaderCollection.cpp | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp index 4cae8af48e..933eccbd44 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp @@ -40,13 +40,22 @@ namespace AZ // Dependent asset references aren't guaranteed to finish loading by the time this asset is serialized, only by // the time this asset load is completed. But since the data is needed here, we will deliberately block until the // shader asset has finished loading. - shaderVariantReference->m_shaderAsset.QueueLoad(); - shaderVariantReference->m_shaderAsset.BlockUntilLoadComplete(); + if (shaderVariantReference->m_shaderAsset.QueueLoad()) + { + shaderVariantReference->m_shaderAsset.BlockUntilLoadComplete(); + } - shaderVariantReference->m_shaderOptionGroup = ShaderOptionGroup{ - shaderVariantReference->m_shaderAsset->GetShaderOptionGroupLayout(), - shaderVariantReference->m_shaderVariantId - }; + if (shaderVariantReference->m_shaderAsset.IsReady()) + { + shaderVariantReference->m_shaderOptionGroup = ShaderOptionGroup{ + shaderVariantReference->m_shaderAsset->GetShaderOptionGroupLayout(), + shaderVariantReference->m_shaderVariantId + }; + } + else + { + shaderVariantReference->m_shaderOptionGroup = {}; + } } }; From 9db65478ee773d9b350b3c03a76598c3caf55ecc Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Sat, 24 Apr 2021 11:14:40 -0700 Subject: [PATCH 02/49] LYN-2905 Script Canvas: Saving a graph that contains an Item Variable crashes the Editor Set the reflection name for ShaderCollection::Item to "ShaderCollectionItem" so it doesn't show up as just "Item" in Script Canvas. Note that this change was made in main only, not in the 1.0 branch, to de-risk the beta branch. Testing: Ran the repro steps for the bug, and ran the ShaderManagementConsole's GenerateShaderVariantListForMaterials.py script successfully. --- .../RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp index 933eccbd44..7fc75f67fe 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Material/ShaderCollection.cpp @@ -91,7 +91,7 @@ namespace AZ if (BehaviorContext* behaviorContext = azrtti_cast(context)) { - behaviorContext->Class() + behaviorContext->Class("ShaderCollectionItem") ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) ->Attribute(AZ::Script::Attributes::Category, "Shader") ->Attribute(AZ::Script::Attributes::Module, "shader") From d35adce246cc8a817d36271dbce2a7e27bbf84e9 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 29 Apr 2021 11:46:08 +0100 Subject: [PATCH 03/49] adding support for non-uniform scale for decals --- .../Decals/DecalFeatureProcessorInterface.h | 3 ++- .../Source/Decals/DecalFeatureProcessor.cpp | 4 +-- .../Source/Decals/DecalFeatureProcessor.h | 3 ++- .../DecalTextureArrayFeatureProcessor.cpp | 5 ++-- .../DecalTextureArrayFeatureProcessor.h | 3 ++- .../Decals/DecalComponentController.cpp | 25 ++++++++++++++++++- .../Source/Decals/DecalComponentController.h | 9 +++++++ 7 files changed, 44 insertions(+), 8 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h index 214feb2040..2ec7b535d0 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Decals/DecalFeatureProcessorInterface.h @@ -88,7 +88,8 @@ namespace AZ //! Sets the transform of the decal //! Equivalent to calling SetDecalPosition() + SetDecalOrientation() + SetDecalHalfSize() - virtual void SetDecalTransform(DecalHandle handle, const AZ::Transform& world) = 0; + virtual void SetDecalTransform(DecalHandle handle, const AZ::Transform& world, + const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()) = 0; //! Sets the material information for this decal virtual void SetDecalMaterial(DecalHandle handle, const AZ::Data::AssetId) = 0; diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp index 7abc6698fa..b4ce2e6cc9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp @@ -262,7 +262,7 @@ namespace AZ } } - void DecalFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world) + void DecalFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world, const AZ::Vector3& nonUniformScale) { // https://jira.agscollab.com/browse/ATOM-4330 // Original Open 3D Engine uploads a 4x4 matrix rather than quaternion, rotation, scale. @@ -274,7 +274,7 @@ namespace AZ if (handle.IsValid()) { Quaternion orientation = world.GetRotation(); - Vector3 scale = world.GetScale(); + Vector3 scale = world.GetScale() * nonUniformScale; SetDecalHalfSize(handle, scale); SetDecalPosition(handle, world.GetTranslation()); diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.h index 9c4acf6322..5a37a5cf11 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.h @@ -73,7 +73,8 @@ namespace AZ //! Sets the transform of the decal //! Equivalent to calling SetDecalPosition() + SetDecalOrientation() + SetDecalHalfSize() - void SetDecalTransform(DecalHandle handle, const AZ::Transform& world) override; + void SetDecalTransform(DecalHandle handle, const AZ::Transform& world, + const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()) override; //! Sets the material information for this decal void SetDecalMaterial(DecalHandle handle, const AZ::Data::AssetId) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp index 9d1ea4e680..1f1bcc21b2 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.cpp @@ -269,11 +269,12 @@ namespace AZ } } - void DecalTextureArrayFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world) + void DecalTextureArrayFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world, + const AZ::Vector3& nonUniformScale) { if (handle.IsValid()) { - SetDecalHalfSize(handle, world.GetScale()); + SetDecalHalfSize(handle, nonUniformScale * world.GetScale()); SetDecalPosition(handle, world.GetTranslation()); SetDecalOrientation(handle, world.GetRotation()); diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h index 7ab073c7f9..50d51fbe7f 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h @@ -82,7 +82,8 @@ namespace AZ //! Sets the transform of the decal //! Equivalent to calling SetDecalPosition() + SetDecalOrientation() + SetDecalHalfSize() - void SetDecalTransform(const DecalHandle handle, const AZ::Transform& world) override; + void SetDecalTransform(const DecalHandle handle, const AZ::Transform& world, + const AZ::Vector3& nonUniformScale = AZ::Vector3::CreateOne()) override; //! Sets the material information for this decal void SetDecalMaterial(const DecalHandle handle, const AZ::Data::AssetId id) override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.cpp index 22a7e1c6c0..3c748e352e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.cpp @@ -75,6 +75,12 @@ namespace AZ incompatible.push_back(AZ_CRC_CE("DecalService")); } + void DecalComponentController::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) + { + dependent.push_back(AZ_CRC_CE("TransformService")); + dependent.push_back(AZ_CRC_CE("NonUniformScaleService")); + } + DecalComponentController::DecalComponentController(const DecalComponentConfig& config) : m_configuration(config) { @@ -90,6 +96,11 @@ namespace AZ m_handle = m_featureProcessor->AcquireDecal(); } + m_cachedNonUniformScale = AZ::Vector3::CreateOne(); + AZ::NonUniformScaleRequestBus::EventResult(m_cachedNonUniformScale, m_entityId, &AZ::NonUniformScaleRequests::GetScale); + AZ::NonUniformScaleRequestBus::Event(m_entityId, &AZ::NonUniformScaleRequests::RegisterScaleChangedEvent, + m_nonUniformScaleChangedHandler); + AZ::Transform local, world; AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::GetLocalAndWorld, local, world); OnTransformChanged(local, world); @@ -103,6 +114,7 @@ namespace AZ { DecalRequestBus::Handler::BusDisconnect(m_entityId); TransformNotificationBus::Handler::BusDisconnect(m_entityId); + m_nonUniformScaleChangedHandler.Disconnect(); if (m_featureProcessor) { m_featureProcessor->ReleaseDecal(m_handle); @@ -125,7 +137,18 @@ namespace AZ { if (m_featureProcessor) { - m_featureProcessor->SetDecalTransform(m_handle, world); + m_featureProcessor->SetDecalTransform(m_handle, world, m_cachedNonUniformScale); + } + } + + void DecalComponentController::HandleNonUniformScaleChange(const AZ::Vector3& nonUniformScale) + { + m_cachedNonUniformScale = nonUniformScale; + if (m_featureProcessor) + { + AZ::Transform world = AZ::Transform::CreateIdentity(); + AZ::TransformBus::EventResult(world, m_entityId, &AZ::TransformBus::Events::GetWorldTM); + m_featureProcessor->SetDecalTransform(m_handle, world, nonUniformScale); } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.h index dc6b6e70ea..14204c43dc 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Decals/DecalComponentController.h @@ -14,6 +14,7 @@ #include #include +#include #include #include #include @@ -33,6 +34,7 @@ namespace AZ static void Reflect(AZ::ReflectContext* context); static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); + static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); DecalComponentController() = default; DecalComponentController(const DecalComponentConfig& config); @@ -64,11 +66,18 @@ namespace AZ void OpacityChanged(); void SortKeyChanged(); void MaterialChanged(); + void HandleNonUniformScaleChange(const AZ::Vector3& nonUniformScale); DecalComponentConfig m_configuration; DecalFeatureProcessorInterface* m_featureProcessor = nullptr; DecalFeatureProcessorInterface::DecalHandle m_handle; EntityId m_entityId; + AZ::Vector3 m_cachedNonUniformScale = AZ::Vector3::CreateOne(); + + AZ::NonUniformScaleChangedEvent::Handler m_nonUniformScaleChangedHandler + { + [&](const AZ::Vector3& nonUniformScale) { HandleNonUniformScaleChange(nonUniformScale); } + }; }; } // namespace Render } // AZ namespace From 64738c0fc1576b4e9beb0f4333182f318d03a09c Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 29 Apr 2021 11:47:20 +0100 Subject: [PATCH 04/49] adding non-uniform scale service as dependency for mesh component controller --- .../CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp index 9d2196de2b..0957abee65 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp @@ -131,6 +131,7 @@ namespace AZ void MeshComponentController::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) { dependent.push_back(AZ_CRC("TransformService", 0x8ee22c50)); + dependent.push_back(AZ_CRC_CE("NonUniformScaleService")); } void MeshComponentController::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) From 1222286e307d24064a823699c703507451285778 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 29 Apr 2021 14:36:47 +0100 Subject: [PATCH 05/49] removing URL --- .../Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp index b4ce2e6cc9..817897dd62 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalFeatureProcessor.cpp @@ -264,7 +264,7 @@ namespace AZ void DecalFeatureProcessor::SetDecalTransform(DecalHandle handle, const AZ::Transform& world, const AZ::Vector3& nonUniformScale) { - // https://jira.agscollab.com/browse/ATOM-4330 + // ATOM-4330 // Original Open 3D Engine uploads a 4x4 matrix rather than quaternion, rotation, scale. // That is more memory but less calculation because it is doing a matrix inverse rather than a polar decomposition // I've done some experiments and uploading a 3x4 transform matrix with 3x3 matrix inverse should be possible From 009ecbc152c9a4c52ada55d821e0576c6824a34e Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Sat, 1 May 2021 15:53:24 -0700 Subject: [PATCH 06/49] Relocated RayTracingSceneSrg and converted to .azsli --- .../RayTracing}/RayTracingSceneSrg.azsli | 10 +++------ .../RayTracingSceneSrgAll.azsli | 19 ------------------ .../diffuseprobegridraytracing.azshader | Bin 79309 -> 79334 bytes ...probegridraytracing_dx12_0.azshadervariant | Bin 34086 -> 34086 bytes ...probegridraytracing_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...obegridraytracing_vulkan_0.azshadervariant | Bin 36232 -> 36232 bytes ...fuseprobegridraytracingclosesthit.azshader | Bin 79319 -> 79344 bytes ...aytracingclosesthit_dx12_0.azshadervariant | Bin 16754 -> 16754 bytes ...aytracingclosesthit_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...tracingclosesthit_vulkan_0.azshadervariant | Bin 9172 -> 9172 bytes ...raytracingcommon_raytracingglobalsrg.azsrg | 2 +- .../diffuseprobegridraytracingmiss.azshader | Bin 79313 -> 79338 bytes ...egridraytracingmiss_dx12_0.azshadervariant | Bin 16838 -> 16838 bytes ...egridraytracingmiss_null_0.azshadervariant | Bin 4502 -> 4502 bytes ...ridraytracingmiss_vulkan_0.azshadervariant | Bin 10364 -> 10364 bytes .../RayTracing/RayTracingFeatureProcessor.cpp | 2 +- 16 files changed, 5 insertions(+), 28 deletions(-) rename Gems/Atom/Feature/Common/Assets/{ShaderResourceGroups => ShaderLib/Atom/Features/RayTracing}/RayTracingSceneSrg.azsli (96%) delete mode 100644 Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrgAll.azsli diff --git a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli similarity index 96% rename from Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrg.azsli rename to Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli index 0aeb43bcf2..a7bb6cd3b1 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/RayTracing/RayTracingSceneSrg.azsli @@ -10,11 +10,9 @@ * */ -#ifndef AZ_COLLECTING_PARTIAL_SRGS -#error Do not include this file directly. Include the main .srgi file instead. -#endif +#include -partial ShaderResourceGroup RayTracingSceneSrg +ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene { RaytracingAccelerationStructure m_scene; @@ -150,6 +148,4 @@ partial ShaderResourceGroup RayTracingSceneSrg #define MESH_NORMAL_BUFFER_OFFSET 2 ByteAddressBuffer m_meshBuffers[]; -} - - +} \ No newline at end of file diff --git a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrgAll.azsli b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrgAll.azsli deleted file mode 100644 index b1b2bea750..0000000000 --- a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/RayTracingSceneSrgAll.azsli +++ /dev/null @@ -1,19 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -// Please review README.md to understand how this file is used in RayTracingSceneSrg.azsrg generation - -#ifdef AZ_COLLECTING_PARTIAL_SRGS -#include -#endif diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing.azshader b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing.azshader index a781a598bae5e1cecbbe1d75fa6d90a3b625f6ce..804b534277c99e83211f6276d08f434bc053295d 100644 GIT binary patch delta 125 zcmV-@0D}L`>jdWO1dxpphff>3WJVrRv6JCxT_9;^1(BX7BTjQ@VPs`;Y-wUIVRUb8 zFJ@(7bairNb1!mXd317NV`*+@vCqF~2zSz`Y9fzo=ChV*{$&V{6-YSnF#i;jacV2G f$Is$q2nD?nk0;y*aJR8E0TclUu}v(?sQ>@~POCJK delta 103 zcmV-t0GR*g>jcf~1dxppZj^>{MAC&^Q=NV7f!;tKZjqiR3N>?RVPs`;Y-wV#=)Y(P z2a02B-!#&`v#)9XWeEHZH0KJDPn?sAYAdtg&*EeV&N|Iem4rH>lZ$F9m-I9N>If$U J>T8_<001a)Fd+Z{ diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing_dx12_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing_dx12_0.azshadervariant index e9f841047e633f729f147731f9e8b3ed5dc1383b..b3bee56bfde29b0db4ae1ee8da02c26ea4a4ef98 100644 GIT binary patch delta 18 ZcmZ41#k8!8X@guV$3|bB(<>Pm7yv}F23`OF delta 18 ZcmZ41#k8!8X@guVhdRrv?70jK3;;mK1>FDu diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing_null_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracing_null_0.azshadervariant index e399dbcef0fef75481aaf50adde0ecf40c34350d..d9b2f17848938ba5e6d6c71d609d8e5430695825 100644 GIT binary patch delta 16 XcmbQHJWY8+pCHFZU!Bt{85kGPm7yw6U2Ce`A delta 18 ZcmeB}&D1fQX+uLVhdRrv?70jK3;;uZ1}y*p diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit.azshader b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit.azshader index bfed840febab47233bd7efbc8529ce1564a32892..c4a83a26dcc61d813d22d92798d7918b141877b3 100644 GIT binary patch delta 128 zcmV-`0Du42>jd!Y1dx{zhff>3WJVrRv6JCxT_9;^1(B#HBTjQ@VPs`;Y-wUIVRUb8 zFJ@(7bairNb1!mXd317NV`*+@vDv?92v(*>G-_7OinE|;{$&U=YprkZ&EN8qdul7Q i(a+*!2;)JARIRz3B9nY-DwpLn0qO{`O;(u!00010-Z>)x delta 99 zcmV-p0G$8u>jc;91dx{zZj^>{MAC&^Q=NV7f!;tKZjq=b3N>?RVPs`;Y-wV#^1o;Z zU%b6Fq`qF?v$<*hWeB8~BN>&;q^GmL&kbb=c7w0H(^#tQlfcg^m;N*X>If$Pg!t9~ F006w*G2s9J diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_dx12_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_dx12_0.azshadervariant index ee2031bf1a37142304bb7bfca95ce2e36ac459d3..fb5b740f040d6ec0f129ca8671a3c651009d85fa 100644 GIT binary patch delta 18 Zcmey=#Q3R+aYL3P$41|{jC3=9kaF>D05 delta 16 XcmbQHJWY8+pCE_Y|CS%u7#J7;I5h@A diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_vulkan_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingclosesthit_vulkan_0.azshadervariant index e2f5a8cb502b189e07cdec95a357c9d43f7c880f..1eeeffa8be8df2020435b46d5b5de152d8ece66b 100644 GIT binary patch delta 16 XcmccOe#L#m8D)-*zF{*N85kGjdiS1dx#xhff>3WJVrRv6JCxT_9;^1y*bJ4U;SZBO^|8Xklb!a%^d0 zFJW|VZ7*hJVRUtJWpgibVR>|NVPk1-XR*`3Xa^{Jk;V_e?X#L`{$&Ve)u}wHnI$f> ipwA6u2vMlcKO2mee3PNiDwp3h0qO{`P6*{90002M5H^4S delta 102 zcmV-s0Ga>l>jcs31dx#tZj^>{MAC&^Q=NV7f!;tKZjquV3N>?RVPs`;Y-wV#?7(OT zhE_7RJXh(nvuXZi2u!^#t2;G$>64CXE3@R!;$#SV!{+6eVip9Gk7_EH_%s3P2qyoA Ii<Sn-Ln}O7ywN^2OR(a diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_null_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_null_0.azshadervariant index 0f2473b60661c98f9fe92e1ec3d3c4f05a572d03..5f0882548721884c084c7c2a24a650074341a961 100644 GIT binary patch delta 16 XcmbQHJWY8+pCHFZKaQtL3=9kaF`oq3 delta 16 XcmbQHJWY8+pCE_Y|F-Vg3=9kaH8cgA diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_vulkan_0.azshadervariant b/Gems/Atom/Feature/Common/Assets/Shaders/DiffuseGlobalIllumination/diffuseprobegridraytracingmiss_vulkan_0.azshadervariant index bfd979e588d5a15ff3c6ccce525bae8a2c8e6fa9..a5b0e842ef46ceb87c42addd8d1c8e4340b4bc17 100644 GIT binary patch delta 16 Xcmewp@F!qHi3Z0;KaQtL3=9kaLPrJr delta 16 Xcmewp@F!qHi3W$-|F-Vg3=9kaMcf9y diff --git a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp index 0c24c2953d..c4e9306dc9 100644 --- a/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/RayTracing/RayTracingFeatureProcessor.cpp @@ -67,7 +67,7 @@ namespace AZ // load the RayTracingSceneSrg asset Data::Asset rayTracingSceneSrgAsset = - RPI::AssetUtils::LoadAssetByProductPath("shaderlib/raytracingscenesrg_raytracingscenesrg.azsrg", RPI::AssetUtils::TraceLevel::Error); + RPI::AssetUtils::LoadAssetByProductPath("shaderlib/atom/features/raytracing/raytracingscenesrg_raytracingscenesrg.azsrg", RPI::AssetUtils::TraceLevel::Error); AZ_Assert(rayTracingSceneSrgAsset.IsReady(), "Failed to load RayTracingSceneSrg asset"); m_rayTracingSceneSrg = RPI::ShaderResourceGroup::Create(rayTracingSceneSrgAsset); From ce1191c1437b1fc74ee0171a7779132bb030c3e8 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Sat, 1 May 2021 16:02:06 -0700 Subject: [PATCH 07/49] Removed RayTracingSceneSrg.srgi from AutomatedTesting --- .../ShaderLib/raytracingscenesrg.srgi | 28 ------------------- 1 file changed, 28 deletions(-) delete mode 100644 AutomatedTesting/ShaderLib/raytracingscenesrg.srgi diff --git a/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi b/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi deleted file mode 100644 index ac1d663bb8..0000000000 --- a/AutomatedTesting/ShaderLib/raytracingscenesrg.srgi +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#pragma once - -// Please read README.md for an explanation on why scenesrg.srgi and viewsrg.srgi are -// located in this folder (And how you can optionally customize your own scenesrg.srgi -// and viewsrg.srgi in your game project). - -#include - -partial ShaderResourceGroup RayTracingSceneSrg : SRG_RayTracingScene -{ -/* Intentionally Empty. Helps define the SrgSemantic for RayTracingSceneSrg once.*/ -}; - -#define AZ_COLLECTING_PARTIAL_SRGS -#include -#undef AZ_COLLECTING_PARTIAL_SRGS From 3cbbcf1877f8966eae117362bdde338783758a15 Mon Sep 17 00:00:00 2001 From: balibhan Date: Mon, 3 May 2021 12:10:33 +0530 Subject: [PATCH 08/49] SC branch migration --- .../editor_python_test_tools/utils.py | 14 +- .../AssetEditor_CreateScriptEventFile.py | 124 ++ .../scripting/AssetEditor_NewScriptEvent.py | 129 ++ .../Debugging_TargetMultipleEntities.py | 144 ++ .../Debugging_TargetMultipleGraphs.py | 113 + .../Gem/PythonTests/scripting/Docking_Pane.py | 4 +- .../scripting/EditMenu_UndoRedo.py | 123 ++ .../Entity_AddScriptCanvasComponent.py | 88 + .../scripting/FileMenu_New_Open.py | 98 + .../scripting/GraphClose_SavePrompt.py | 110 + .../scripting/Graph_ZoomInZoomOut.py | 120 ++ .../PythonTests/scripting/ImportPathHelper.py | 1 + .../scripting/NodeInspector_RenameVariable.py | 132 ++ .../scripting/NodePalette_ClearSelection.py | 94 + .../scripting/NodePalette_SelectNode.py | 104 + ...EntityActivatedDeactivated_PrintMessage.py | 185 ++ .../scripting/Opening_Closing_Pane.py | 9 +- .../scripting/Pane_RetainOnSCRestart.py | 164 ++ .../PythonTests/scripting/Resizing_Pane.py | 9 +- .../scripting/ScriptCanvas_ChangingAssets.py | 116 + .../scripting/ScriptCanvas_TwoComponents.py | 118 ++ .../scripting/ScriptCanvas_TwoEntities.py | 107 + .../ScriptEvents_SendReceiveAcrossMultiple.py | 120 ++ .../ScriptEvents_SendReceiveSuccessfully.py | 110 + .../PythonTests/scripting/TestSuite_Active.py | 229 +- .../scripting/Toggle_ScriptCanvasTools.py | 137 ++ .../scripting/UnDockedPane_CloseSCWindow.py | 128 ++ .../VariableManager_CreateDeleteVars.py | 123 ++ .../activator.scriptcanvas | 778 +++++++ .../controller.scriptcanvas | 1865 +++++++++++++++++ .../deactivator.scriptcanvas | 766 +++++++ .../ScriptCanvas_TwoComponents0.scriptcanvas | 365 ++++ .../ScriptCanvas_TwoComponents1.scriptcanvas | 365 ++++ .../ScriptCanvas/T92563191_test.scriptcanvas | 750 +++++++ .../ScriptCanvas/T92567320.scriptcanvas | 1266 +++++++++++ .../ScriptCanvas/T92567321A.scriptcanvas | 778 +++++++ .../ScriptCanvas/T92567321B.scriptcanvas | 880 ++++++++ .../TestAssets/T92567320.scriptevents | 116 + .../TestAssets/T92567321.scriptevents | 166 ++ 39 files changed, 11024 insertions(+), 24 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py create mode 100644 AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py create mode 100644 AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/activator.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/controller.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/deactivator.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents0.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents1.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/T92563191_test.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/T92567320.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/T92567321A.scriptcanvas create mode 100644 AutomatedTesting/ScriptCanvas/T92567321B.scriptcanvas create mode 100644 AutomatedTesting/TestAssets/T92567320.scriptevents create mode 100644 AutomatedTesting/TestAssets/T92567321.scriptevents diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py index a9f6d0aa02..c7f1aba031 100644 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py +++ b/AutomatedTesting/Gem/PythonTests/EditorPythonTestTools/editor_python_test_tools/utils.py @@ -265,6 +265,7 @@ class Tracer: self.warnings = [] self.errors = [] self.asserts = [] + self.prints = [] self.has_warnings = False self.has_errors = False self.has_asserts = False @@ -310,6 +311,11 @@ class Tracer: def __repr__(self): return f"[Assert: {self.message}]" + + class PrintInfo: + def __init__(self, args): + self.window = args[0] + self.message = args[1] def _on_warning(self, args): warningInfo = Tracer.WarningInfo(args) @@ -331,13 +337,19 @@ class Tracer: Report.info("Tracer caught Assert: %s:%i[%s] \"%s\"" % (assertInfo.filename, assertInfo.line, assertInfo.function, assertInfo.message)) self.has_asserts = True return False - + + def _on_printf(self, args): + printInfo = Tracer.PrintInfo(args) + self.prints.append(printInfo) + return False + def __enter__(self): self.handler = azlmbr.debug.TraceMessageBusHandler() self.handler.connect(None) self.handler.add_callback("OnPreAssert", self._on_assert) self.handler.add_callback("OnPreWarning", self._on_warning) self.handler.add_callback("OnPreError", self._on_error) + self.handler.add_callback("OnPrintf", self._on_printf) return self def __exit__(self, type, value, traceback): diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py new file mode 100644 index 0000000000..dcbbf47f0c --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_CreateScriptEventFile.py @@ -0,0 +1,124 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92569013 +Test Case Title: Script Event file can be created +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569013 +""" + + +# fmt: off +class Tests(): + new_event_created = ("New Script Event created", "New Script Event not created") + child_event_created = ("Child Event created", "Child not created") + file_saved = ("Script event file saved", "Script event file did not save") + console_error = ("No unexpected error in console", "Error found in console") + console_warning = ("No unexpected warning in console", "Warning found in console") +# fmt: on + + +def CreateScriptEventFile(): + """ + Summary: + Script Event file can be created + + Expected Behavior: + File is created without any errors and warnings in Console + + Test Steps: + 1) Open Asset Editor + 2) Get Asset Editor Qt object + 3) Create new Script Event Asset + 4) Add new child event + 5) Save the Script Event file + 6) Verify if file is created + 7) Verify console for errors/warnings + 8) Close Asset Editor + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + from utils import Report + from utils import TestHelper as helper + from utils import Tracer + import pyside_utils + + # Open 3D Engine imports + import azlmbr.legacy.general as general + import azlmbr.editor as editor + import azlmbr.bus as bus + + # Pyside imports + from PySide2 import QtWidgets + + GENERAL_WAIT = 1.0 # seconds + + FILE_PATH = os.path.join("AutomatedTesting", "ScriptCanvas", "test_file.scriptevent") + + # 1) Open Asset Editor + general.idle_enable(True) + # Initially close the Asset Editor and then reopen to ensure we don't have any existing assets open + general.close_pane("Asset Editor") + general.open_pane("Asset Editor") + helper.wait_for_condition(lambda: general.is_pane_visible("Asset Editor"), 5.0) + + # 2) Get Asset Editor Qt object + editor_window = pyside_utils.get_editor_main_window() + asset_editor_widget = editor_window.findChild(QtWidgets.QDockWidget, "Asset Editor").findChild( + QtWidgets.QWidget, "AssetEditorWindowClass" + ) + container = asset_editor_widget.findChild(QtWidgets.QWidget, "ContainerForRows") + menu_bar = asset_editor_widget.findChild(QtWidgets.QMenuBar) + + # 3) Create new Script Event Asset + action = pyside_utils.find_child_by_pattern(menu_bar, {"type": QtWidgets.QAction, "text": "Script Events"}) + action.trigger() + result = helper.wait_for_condition( + lambda: container.findChild(QtWidgets.QFrame, "Events") is not None, 3 * GENERAL_WAIT + ) + Report.result(Tests.new_event_created, result) + + # 4) Add new child event + add_event = container.findChild(QtWidgets.QFrame, "Events").findChild(QtWidgets.QToolButton, "") + add_event.click() + result = helper.wait_for_condition( + lambda: asset_editor_widget.findChild(QtWidgets.QFrame, "EventName") is not None, GENERAL_WAIT + ) + Report.result(Tests.child_event_created, result) + + with Tracer() as section_tracer: + # 5) Save the Script Event file + editor.AssetEditorWidgetRequestsBus(bus.Broadcast, "SaveAssetAs", FILE_PATH) + + # 6) Verify if file is created + result = helper.wait_for_condition(lambda: os.path.exists(FILE_PATH), 3 * GENERAL_WAIT) + Report.result(Tests.file_saved, result) + + # 7) Verify console for errors/warnings + Report.result(Tests.console_error, not section_tracer.has_errors) + Report.result(Tests.console_warning, not section_tracer.has_warnings) + + # 8) Close Asset Editor + general.close_pane("Asset Editor") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(CreateScriptEventFile) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py new file mode 100644 index 0000000000..1f801d4eeb --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/AssetEditor_NewScriptEvent.py @@ -0,0 +1,129 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92568942 +Test Case Title: Clicking the "+" button and selecting "New Script Event" opens the +Asset Editor with a new Script Event asset +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568942 +""" + +from PySide2 import QtWidgets +import azlmbr.legacy.general as general + +import editor_python_test_tools.pyside_utils as pyside_utils +from editor_python_test_tools.utils import TestHelper as helper +from editor_python_test_tools.utils import Report + + +class Tests: + action_found = "New Script event action found" + asset_editor_opened = "Asset Editor opened" + new_asset = "Asset Editor created with new asset" + script_event = "New Script event created in Asset Editor" + + +GENERAL_WAIT = 0.5 # seconds + + +class TestAssetEditor_NewScriptEvent: + """ + Summary: + Clicking the "+" button in Node Palette and creating New Script Event opens Asset Editor + + Expected Behavior: + Clicking the "+" button and selecting "New Script Event" opens the Asset Editor with a + new Script Event asset + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Close any existing AssetEditor window + 3) Get the SC window object + 4) Click on New Script Event on Node palette + 5) Verify if Asset Editor opened + 6) Verify if a new asset with Script Canvas category is opened + 7) Close Script Canvas and Asset Editor + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + @pyside_utils.wrap_async + async def run_test(self): + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Close any existing AssetEditor window + general.close_pane("Asset Editor") + helper.wait_for_condition(lambda: not general.is_pane_visible("Asset Editor"), 5.0) + + # 3) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + frame = node_palette.findChild(QtWidgets.QFrame, "searchCustomization") + button = frame.findChild(QtWidgets.QToolButton) + pyside_utils.click_button_async(button) + + # 4) Click on New Script Event on Node palette + menu = None + + def menu_has_focus(): + nonlocal menu + for fw in [ + QtWidgets.QApplication.activePopupWidget(), + QtWidgets.QApplication.activeModalWidget(), + QtWidgets.QApplication.focusWidget(), + QtWidgets.QApplication.activeWindow(), + ]: + print(fw) + if fw and isinstance(fw, QtWidgets.QMenu) and fw.isVisible(): + menu = fw + return True + return False + + await pyside_utils.wait_for_condition(menu_has_focus, GENERAL_WAIT) + action = await pyside_utils.wait_for_action_in_menu(menu, {"text": "New Script Event"}) + Report.info(f"{Tests.action_found}: {action is not None}") + action.trigger() + pyside_utils.queue_hide_event(menu) + + # 5) Verify if Asset Editor opened + result = helper.wait_for_condition(lambda: general.is_pane_visible("Asset Editor"), GENERAL_WAIT) + Report.info(f"{Tests.asset_editor_opened}: {result}") + + # 6) Verify if a new asset with Script Canvas category is opened + asset_editor = editor_window.findChild(QtWidgets.QDockWidget, "Asset Editor") + row_container = asset_editor.findChild(QtWidgets.QWidget, "ContainerForRows") + # NOTE: QWidget ContainerForRows will have frames of Name, Category, ToolTip etc. + # To validate if a new script event file is generated, we check for + # QFrame Category and its value + categories = row_container.findChildren(QtWidgets.QFrame, "Category") + Report.info(f"{Tests.new_asset}: {len(categories)>0}") + result = False + for frame in categories: + line_edit = frame.findChild(QtWidgets.QLineEdit) + result = True if (line_edit and line_edit.text() == "Script Events") else False + Report.info(f"{Tests.script_event}: {result}") + + # 7) Close Script Canvas and Asset Editor + general.close_pane("Script Canvas") + general.close_pane("Asset Editor") + + +test = TestAssetEditor_NewScriptEvent() +test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py new file mode 100644 index 0000000000..a26cb4f923 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleEntities.py @@ -0,0 +1,144 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92568856 +Test Case Title: Multiple Entities can be targeted in the Debugger tool +URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568856 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "New level not created") + entities_found = ("Entities are found in Logging window", "Entities are not found in Logging window") + select_multiple_targets = ("Multiple targets are selected", "Multiple targets are not selected") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def Debugging_TargetMultipleEntities(): + """ + Summary: + Multiple Entities can be targeted in the Debugger tool + + Expected Behavior: + Selected files can be checked for logging. + Upon checking, checkboxes of the parent folders change to either full or partial check. + + Test Steps: + 1) Create temp level + 2) Create two entities with scriptcanvas components + 3) Set values for scriptcanvas + 4) Open Script Canvas window and get sc opbject + 5) Open Debugging(Logging) window + 6) Click on Entities tab in logging window + 7) Verify if the scriptcanvas exist under entities + 8) Verify if the entities can be selected + 9) Close Debugging window and Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets + from PySide2.QtCore import Qt + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.asset as asset + import azlmbr.bus as bus + + import os + import pyside_utils + import hydra_editor_utils as hydra + from utils import TestHelper as helper + from utils import Report + + LEVEL_NAME = "tmp_level" + ASSET_NAME_1 = "ScriptCanvas_TwoComponents0.scriptcanvas" + ASSET_NAME_2 = "ScriptCanvas_TwoComponents1.scriptcanvas" + ASSET_1 = os.path.join("scriptcanvas", ASSET_NAME_1) + ASSET_2 = os.path.join("scriptcanvas", ASSET_NAME_2) + WAIT_TIME = 3.0 + + def get_asset(asset_path): + return asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create two entities with scriptcanvas components + position = math.Vector3(512.0, 512.0, 32.0) + test_entity_1 = hydra.Entity("test_entity_1") + test_entity_1.create_entity(position, ["Script Canvas"]) + test_entity_2 = hydra.Entity("test_entity_2") + test_entity_2.create_entity(position, ["Script Canvas"]) + + # 3) Set values for scriptcanvas + test_entity_1.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_1)) + test_entity_2.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_2)) + + # 4) Open Script Canvas window and get sc opbject + general.open_pane("Script Canvas") + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 5) Open Debugging(Logging) window + if ( + sc.findChild(QtWidgets.QDockWidget, "LoggingWindow") is None + or not sc.findChild(QtWidgets.QDockWidget, "LoggingWindow").isVisible() + ): + action = pyside_utils.find_child_by_pattern(sc, {"text": "Debugging", "type": QtWidgets.QAction}) + action.trigger() + logging_window = sc.findChild(QtWidgets.QDockWidget, "LoggingWindow") + + # 6) Click on Entities tab in logging window + button = pyside_utils.find_child_by_pattern(logging_window, {"type": QtWidgets.QPushButton, "text": "Entities"}) + button.click() + + # 7) Verify if the scriptcanvas exist under entities + entities = logging_window.findChild(QtWidgets.QWidget, "entitiesPage") + tree = entities.findChild(QtWidgets.QTreeView, "pivotTreeView") + asset_1_mi = pyside_utils.find_child_by_pattern(tree, ASSET_NAME_1.lower()) + asset_2_mi = pyside_utils.find_child_by_pattern(tree, ASSET_NAME_2.lower()) + result = asset_1_mi is not None and asset_2_mi is not None + Report.critical_result(Tests.entities_found, result) + + # 8) Verify if the entities can be selected + tree.expandAll() + tree.model().setData(asset_1_mi, 2, Qt.CheckStateRole) + tree.model().setData(asset_2_mi, 2, Qt.CheckStateRole) + checklist = [asset_1_mi, asset_1_mi.parent(), asset_2_mi, asset_2_mi.parent()] + result = all([index.data(Qt.CheckStateRole) == 2 for index in checklist]) + Report.critical_result(Tests.select_multiple_targets, result) + + # 9) Close Debugging window and Script Canvas window + logging_window.close() + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(Debugging_TargetMultipleEntities) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py new file mode 100644 index 0000000000..4aa5c822a7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Debugging_TargetMultipleGraphs.py @@ -0,0 +1,113 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92569137 +Test Case Title: Multiple Graphs can be targeted in the Debugger tool +URLs of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569137 +""" + + +# fmt: off +class Tests(): + select_multiple_targets = ("Multiple targets are selected", "Multiple targets are not selected") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def Debugging_TargetMultipleGraphs(): + """ + Summary: + Multiple Graphs can be targeted in the Debugger tool + + Expected Behavior: + Selected files can be checked for logging. + Upon checking, checkboxes of the parent folders change to either full or partial check. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Debugging Tool if not opened already + 4) Select Graphs tab under logging window + 5) Select multiple targets from levels and scriptcanvas + 6) Verify if multiple targets are selected + 7) Close Debugging window and Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets + from PySide2.QtCore import Qt + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + from utils import Report + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 6.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Debugging Tool if not opened already + if ( + sc.findChild(QtWidgets.QDockWidget, "LoggingWindow") is None + or not sc.findChild(QtWidgets.QDockWidget, "LoggingWindow").isVisible() + ): + action = pyside_utils.find_child_by_pattern(sc, {"text": "Debugging", "type": QtWidgets.QAction}) + action.trigger() + logging_window = sc.findChild(QtWidgets.QDockWidget, "LoggingWindow") + + # 4) Select Graphs tab under logging window + button = pyside_utils.find_child_by_pattern(logging_window, {"type": QtWidgets.QPushButton, "text": "Graphs"}) + button.click() + + # 5) Select multiple targets from levels and scriptcanvas + graphs = logging_window.findChild(QtWidgets.QWidget, "graphsPage") + tree = graphs.findChild(QtWidgets.QTreeView, "pivotTreeView") + # Select the first child under levels + level_model_index = pyside_utils.find_child_by_pattern(tree, "levels") + level_child_index = pyside_utils.get_item_view_index(tree, 0, 0, level_model_index) + tree.model().setData(level_child_index, 2, Qt.CheckStateRole) + # Select the first child under scriptcanvas + sc_model_index = pyside_utils.find_child_by_pattern(tree, "scriptcanvas") + sc_child_index = pyside_utils.get_item_view_index(tree, 0, 0, sc_model_index) + tree.model().setData(sc_child_index, 2, Qt.CheckStateRole) + + # 6) Verify if multiple targets are selected + result = all([index.data(Qt.CheckStateRole) != 0 for index in (level_model_index, sc_model_index)]) + result = result and all([index.data(Qt.CheckStateRole) == 2 for index in (level_child_index, sc_child_index)]) + Report.result(Tests.select_multiple_targets, result) + + # 7) Close Debugging window and Script Canvas window + logging_window.close() + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Debugging_TargetMultipleGraphs) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py index 25dd83e5e2..4fa1e1257f 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Docking_Pane.py @@ -16,7 +16,6 @@ URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702 # fmt: off class Tests(): - open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") pane_opened = ("Pane is opened successfully", "Failed to open pane") dock_pane = ("Pane is docked successfully", "Failed to dock Pane into one or more allowed area") # fmt: on @@ -78,8 +77,7 @@ def Docking_Pane(): # 1) Open Script Canvas window (Tools > Script Canvas) general.open_pane("Script Canvas") - is_sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) - Report.result(Tests.open_sc_window, is_sc_visible) + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) # 2) Make sure Node Palette pane is opened editor_window = pyside_utils.get_editor_main_window() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py new file mode 100644 index 0000000000..a87d9e9be9 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/EditMenu_UndoRedo.py @@ -0,0 +1,123 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92569049 +Test Case Title: Edit > Undo undoes the last action +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569049 +Test case ID: T92569051 +Test Case Title: Edit > Redo redoes the last undone action +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569051 +""" + + +# fmt: off +class Tests(): + variable_created = ("New variable created", "New variable not created") + undo_worked = ("Undo action working", "Undo action did not work") + redo_worked = ("Redo action working", "Redo action did not work") +# fmt: on + + +def EditMenu_UndoRedo(): + """ + Summary: + Edit > Undo undoes the last action + Edit > Redo redoes the last undone action + We create a new variable in variable manager, undo and verify if variable is removed, + redo it and verify if the variable is created again. + + Expected Behavior: + The last action is undone. + The last undone action is redone. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Variable Manager if not opened already + 4) Create Graph + 5) Create new variable + 6) Verify if the variable is created initially + 7) Trigger Undo action and verify if variable is removed in Variable Manager + 8) Trigger Redo action and verify if variable is readded in Variable Manager + 9) Close SC window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets, QtCore + + import azlmbr.legacy.general as general + + import pyside_utils + + # 1) Open Script Canvas window + general.idle_enable(True) + general.open_pane("Script Canvas") + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Variable Manager if not opened already + if sc.findChild(QtWidgets.QDockWidget, "VariableManager") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Variable Manager", "type": QtWidgets.QAction}) + action.trigger() + variable_manager = sc.findChild(QtWidgets.QDockWidget, "VariableManager") + + # 4) Create Graph + action = pyside_utils.find_child_by_pattern(sc, {"objectName": "action_New_Script", "type": QtWidgets.QAction}) + action.trigger() + + # 5) Create new variable + add_button = variable_manager.findChild(QtWidgets.QPushButton, "addButton") + add_button.click() # Click on Create Variable button + # Select variable type + table_view = variable_manager.findChild(QtWidgets.QTableView, "variablePalette") + model_index = pyside_utils.find_child_by_pattern(table_view, "Boolean") + # Click on it to create variable + pyside_utils.item_view_index_mouse_click(table_view, model_index) + + # 6) Verify if the variable is created initially + graph_vars = variable_manager.findChild(QtWidgets.QTableView, "graphVariables") + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == 1 # since we added 1 variable, rowcount=1 + Report.result(Tests.variable_created, result) + + # 7) Trigger Undo action and verify if variable is removed in Variable Manager + action = sc.findChild(QtWidgets.QAction, "action_Undo") + action.trigger() + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == 0 # since we triggered undo, rowcount=0 + Report.result(Tests.undo_worked, result) + + # 8) Trigger Redo action and verify if variable is readded in Variable Manager + action = sc.findChild(QtWidgets.QAction, "action_Redo") + action.trigger() + result = ( + graph_vars.model().rowCount(QtCore.QModelIndex()) == 1 + ) # since action is redone 1 variable is readded, rowcount=1 + Report.result(Tests.redo_worked, result) + + # 9) Close SC window + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(EditMenu_UndoRedo) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py new file mode 100644 index 0000000000..fd8e9b1173 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Entity_AddScriptCanvasComponent.py @@ -0,0 +1,88 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92562978 +Test Case Title: Script Canvas Component can be added to an entity +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562978 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "Failed to create new level") + entity_created = ("Test Entity created", "Failed to create test entity") + add_sc_component = ("Script Canvas component added to entity", "Failed to add SC component to entity") + no_errors_found = ("Tracer found no errors", "One or more errors found by Tracer") + no_warnings_found = ("Tracer found no warnings", "One or more warnings found by Tracer") +# fmt: on + + +def Entity_AddScriptCanvasComponent(): + """ + Summary: + verify if Script Canvas component can be added to Entity without any issue + + Expected Behavior: + Script Canvas Component is added to the entity successfully without issue. + + Test Steps: + 1) Create temp level + 2) Create test entity + 3) Start Tracer + 4) Add Script Canvas component to test entity + 5) Search for errors and warnings + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from utils import TestHelper as helper + from utils import Tracer + from editor_entity_utils import EditorEntity + import azlmbr.legacy.general as general + + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 # SECONDS + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create new entity + test_entity = EditorEntity.create_editor_entity("test_entity") + Report.result(Tests.entity_created, test_entity.id.IsValid()) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Add Script Canvas component to test entity + test_entity.add_component("Script Canvas") + Report.result(Tests.add_sc_component, test_entity.has_component("Script Canvas")) + + # 5) Search for errors and warnings + Report.result(Tests.no_errors_found, not section_tracer.has_errors) + Report.result(Tests.no_warnings_found, not section_tracer.has_warnings) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(Entity_AddScriptCanvasComponent) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py new file mode 100644 index 0000000000..f72ac8ea01 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/FileMenu_New_Open.py @@ -0,0 +1,98 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92569037 +Test Case Title: File > New Script creates a new script +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569037 +Test case ID: T92569039 +Test Case Title: File > Open opens the Open... dialog +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569039 +""" + +import os +import sys +from PySide2 import QtWidgets +import azlmbr.legacy.general as general + +import editor_python_test_tools.pyside_utils as pyside_utils +from editor_python_test_tools.utils import Report + +# fmt: off +class Tests(): + new_action = "File->New action working as expected" + open_action = "File->Open action working as expected" +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +class TestFileMenuNewOpen: + """ + Summary: + When clicked on File->New, new script opens and File->Open should open the FileBrowser + + Expected Behavior: + New and Open actions should work as expected. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Trigger File->New action + 4) Verify if New tab is opened + 5) Trigger File->Open action + 6) Close Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + @pyside_utils.wrap_async + async def run_test(self): + # 1) Open Script Canvas window (Tools > Script Canvas) + general.open_pane("Script Canvas") + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + sc_tabs = sc_main.findChild(QtWidgets.QTabWidget, "ScriptCanvasTabs") + + # 3) Trigger File->New action + initial_tabs_count = sc_tabs.count() + action = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + action.trigger() + + # 4) Verify if New tab is opened + general.idle_wait(GENERAL_WAIT) + Report.info(f"{Tests.new_action}: {sc_tabs.count() == initial_tabs_count + 1}") + + # 5) Trigger File->Open action + action = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_Open", "type": QtWidgets.QAction}) + pyside_utils.trigger_action_async(action) + general.idle_wait(GENERAL_WAIT) + popup = await pyside_utils.wait_for_modal_widget() + Report.info(f"{Tests.open_action}: {popup and 'Open' in popup.windowTitle()}") + popup.close() + + # 6) Close Script Canvas window + general.close_pane("Script Canvas") + + +test = TestFileMenuNewOpen() +test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py new file mode 100644 index 0000000000..ce610b159b --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/GraphClose_SavePrompt.py @@ -0,0 +1,110 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92563070 +Test Case Title: Graphs can be closed by clicking X on the Graph name tab +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563070 +Test case ID: T92563068 +Test Case Title: Save Prompt: User is prompted to save a graph on close after +creating a new graph +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563068 +""" + +import os +import sys +from PySide2 import QtWidgets +import azlmbr.legacy.general as general + +import editor_python_test_tools.pyside_utils as pyside_utils +from editor_python_test_tools.utils import TestHelper as helper +from editor_python_test_tools.utils import Report + +# fmt: off +class Tests(): + new_graph = "New graph created" + save_prompt = "Save prompt opened as expected" + close_graph = "Close button worked as expected" +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +class TestGraphCloseSavePrompt: + """ + Summary: + The graph is closed when x button is clicked. + Save Prompt is opened before closing. + + Expected Behavior: + New and Open actions should work as expected. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Trigger File->New action + 4) Verify if New tab is opened + 5) Close new tab using X on top of graph and check for save dialog + 6) Check if tab is closed + 7) Close Script Canvas window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + @pyside_utils.wrap_async + async def run_test(self): + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + sc_tabs = sc_main.findChild(QtWidgets.QTabWidget, "ScriptCanvasTabs") + tab_bar = sc_tabs.findChild(QtWidgets.QTabBar) + + # 3) Trigger File->New action + initial_tabs_count = sc_tabs.count() + action = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + action.trigger() + + # 4) Verify if New tab is opened + result = helper.wait_for_condition(lambda: sc_tabs.count() == initial_tabs_count + 1, GENERAL_WAIT) + Report.info(f"{Tests.new_graph}: {result}") + + # 5) Close new tab using X on top of graph and check for save dialog + close_button = tab_bar.findChildren(QtWidgets.QAbstractButton)[0] + pyside_utils.click_button_async(close_button) + popup = await pyside_utils.wait_for_modal_widget() + if popup: + Report.info(f"{Tests.save_prompt}: {popup.findChild(QtWidgets.QDialog, 'SaveChangesDialog') is not None}") + dont_save = popup.findChild(QtWidgets.QPushButton, "m_continueButton") + dont_save.click() + + # 6) Check if tab is closed + await pyside_utils.wait_for_condition(lambda: sc_tabs.count() == initial_tabs_count, 5.0) + Report.info(f"{Tests.close_graph}: {sc_tabs.count()==initial_tabs_count}") + + # 7) Close Script Canvas window + general.close_pane("Script Canvas") + + +test = TestGraphCloseSavePrompt() +test.run_test() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py new file mode 100644 index 0000000000..a93b6e61d1 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Graph_ZoomInZoomOut.py @@ -0,0 +1,120 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92569079 +Test Case Title: View > Zoom In zooms the graph in +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569079 +Test case ID: T92569081 +Test Case Title: View > Zoom In zooms the graph out +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569081 +""" + + +# fmt: off +class Tests(): + zoom_in = ("Zoom In action working as expected", "Zoom In action not working as expected") + zoom_out = ("Zoom Out action working as expected", "Zoom Out action not working as expected") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def Graph_ZoomInZoomOut(): + """ + Summary: + The graph can be zoomed in and zoomed out. + + Expected Behavior: + The graph is zoomed in when when we click View->ZoomIn + The graph is zoomed out when when we click View->ZoomOut + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Create new graph + 4) Get initial graph transform values + 5) Trigger Zoom In and verify if the graph transform scale is increased + 6) Trigger Zoom Out and verify if the graph transform scale is decreased + 7) Close Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + # Helper imports + import ImportPathHelper as imports + + imports.init() + + from PySide2 import QtWidgets + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + from utils import Report + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + sc_main = sc.findChild(QtWidgets.QMainWindow) + + # 3) Create new graph + create_new_graph = pyside_utils.find_child_by_pattern( + sc_main, {"objectName": "action_New_Script", "type": QtWidgets.QAction} + ) + create_new_graph.trigger() + + # 4) Get initial graph transform values + graphics_view = sc_main.findChild(QtWidgets.QGraphicsView) + # NOTE: transform m11 and m22 are horizontal and vertical scales of graph + # they increase when zoomed in and decreased when zoomed out + curr_m11, curr_m22 = graphics_view.transform().m11(), graphics_view.transform().m22() + + # 5) Trigger Zoom In and verify if the graph transform scale is increased + zin = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_ZoomIn", "type": QtWidgets.QAction}) + zin.trigger() + result = helper.wait_for_condition( + lambda: curr_m11 < graphics_view.transform().m11() and curr_m22 < graphics_view.transform().m22(), GENERAL_WAIT, + ) + Report.result(Tests.zoom_in, result) + + # 6) Trigger Zoom Out and verify if the graph transform scale is decreased + curr_m11, curr_m22 = graphics_view.transform().m11(), graphics_view.transform().m22() + zout = pyside_utils.find_child_by_pattern(sc_main, {"objectName": "action_ZoomOut", "type": QtWidgets.QAction}) + zout.trigger() + result = helper.wait_for_condition( + lambda: curr_m11 > graphics_view.transform().m11() and curr_m22 > graphics_view.transform().m22(), GENERAL_WAIT, + ) + Report.result(Tests.zoom_out, result) + + # 7) Close Script Canvas window + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Graph_ZoomInZoomOut) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py index 8aede24d0e..a45024cebf 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/ImportPathHelper.py @@ -13,4 +13,5 @@ def init(): import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') + sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../EditorPythonTestTools/editor_python_test_tools') \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py new file mode 100644 index 0000000000..33d3f4137a --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodeInspector_RenameVariable.py @@ -0,0 +1,132 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92568982 +Test Case Title: Renaming variables in the Node Inspector +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568982 +""" + + +# fmt: off +class Tests(): + variable_created = ("New variable created", "New variable is not created") + node_inspector_rename = ("Variable is renamed in Node Inspector", "Variable is not renamed in Node Inspector") + variable_manager_rename = ("Variable is renamed in Variable Manager", "Variable is not renamed in Variable Manager") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def NodeInspector_RenameVariable(): + """ + Summary: + Renaming variables in the Node Inspector, renames the actual variable. + + Expected Behavior: + The Variable's name is changed in both Node Inspector and Variable Manager. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Variable Manager if not opened already + 4) Open Node Inspector if not opened already + 5) Create new graph and a new variable in Variable manager + 6) Click on the variable + 7) Update name in Node Inspector and click on ENTER + 8) Verify if the name is updated in Node inspector and Variable manager + 9) Close Script Canvas window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + TEST_NAME = "test name" + + from PySide2 import QtWidgets, QtCore, QtTest + from PySide2.QtCore import Qt + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + + def open_tool(sc, dock_widget_name, pane_name): + if sc.findChild(QtWidgets.QDockWidget, dock_widget_name) is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": pane_name, "type": QtWidgets.QAction}) + action.trigger() + tool = sc.findChild(QtWidgets.QDockWidget, dock_widget_name) + return tool + + # 1) Open Script Canvas window + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Variable Manager if not opened already + variable_manager = open_tool(sc, "VariableManager", "Variable Manager") + + # 4) Open Node Inspector if not opened already + node_inspector = open_tool(sc, "NodeInspector", "Node Inspector") + + # 5) Create new graph and a new variable in Variable manager + action = pyside_utils.find_child_by_pattern(sc, {"objectName": "action_New_Script", "type": QtWidgets.QAction}) + action.trigger() + graph_vars = variable_manager.findChild(QtWidgets.QTableView, "graphVariables") + add_button = variable_manager.findChild(QtWidgets.QPushButton, "addButton") + add_button.click() + # Select variable type + table_view = variable_manager.findChild(QtWidgets.QTableView, "variablePalette") + model_index = pyside_utils.find_child_by_pattern(table_view, "Boolean") + # Click on it to create variable + pyside_utils.item_view_index_mouse_click(table_view, model_index) + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == 1 + var_mi = pyside_utils.find_child_by_pattern(graph_vars, "Variable 1") + result = result and (var_mi is not None) + Report.critical_result(Tests.variable_created, result) + + # 6) Click on the variable + pyside_utils.item_view_index_mouse_click(graph_vars, var_mi) + + # 7) Update name in Node Inspector and click on ENTER + helper.wait_for_condition( + lambda: node_inspector.findChild(QtWidgets.QWidget, "ContainerForRows") is not None, GENERAL_WAIT + ) + row_container = node_inspector.findChild(QtWidgets.QWidget, "ContainerForRows") + name_frame = row_container.findChild(QtWidgets.QWidget, "Name") + name_line_edit = name_frame.findChild(QtWidgets.QLineEdit) + name_line_edit.setText(TEST_NAME) + QtTest.QTest.keyClick(name_line_edit, Qt.Key_Return, Qt.NoModifier) + + # 8) Verify if the name is updated in Node inspector and Variable manager + helper.wait_for_condition(lambda: var_mi.data(Qt.DisplayRole) == TEST_NAME, GENERAL_WAIT) + Report.critical_result(Tests.node_inspector_rename, name_line_edit.text() == TEST_NAME) + Report.critical_result(Tests.variable_manager_rename, var_mi.data(Qt.DisplayRole) == TEST_NAME) + + # 9) Close Script Canvas window + general.close_pane("Script Canvas") + + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(NodeInspector_RenameVariable) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py new file mode 100644 index 0000000000..de30e46767 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_ClearSelection.py @@ -0,0 +1,94 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92562993 +Test Case Title: Clicking the X button on the Search Box clears the currently entered string +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562993 +""" + + +# fmt: off +class Tests(): + set_search_string = ("Search string is set", "Search string is not set") + search_string_cleared = ("Search string cleared as expected", "Search string not cleared") +# fmt: on + + +def NodePalette_ClearSelection(): + """ + Summary: + We enter some string in the Node Palette Search box, and click on the X button to verify if the + search string got cleared. + + Expected Behavior: + Clicking the X button on the Search Box clears the currently entered string + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Node Manager if not opened already + 4) Set some string in the Search box + 5) Verify if the test string is set + 6) Clear search string and verify if it is cleared + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets + + from utils import TestHelper as helper + + import azlmbr.legacy.general as general + + import pyside_utils + + TEST_STRING = "Test String" + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 3.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Node Manager if not opened already + if sc.findChild(QtWidgets.QDockWidget, "NodePalette") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Palette", "type": QtWidgets.QAction}) + action.trigger() + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + search_frame = node_palette.findChild(QtWidgets.QFrame, "searchFrame") + + # 4) Set some string in the Search box + search_box = search_frame.findChild(QtWidgets.QLineEdit, "searchFilter") + search_box.setText(TEST_STRING) + + # 5) Verify if the test string is set + Report.result(Tests.set_search_string, search_box.text() == TEST_STRING) + + # 6) Clear search string and verify if it is cleared + clear_text_button = search_frame.findChild(QtWidgets.QToolButton, "ClearToolButton") + clear_text_button.click() + Report.result(Tests.search_string_cleared, search_box.text() == "") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(NodePalette_ClearSelection) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py new file mode 100644 index 0000000000..2ab76071a6 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/NodePalette_SelectNode.py @@ -0,0 +1,104 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + + +Test case ID: T92568940 +Test Case Title: Categories and Nodes can be selected +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568940 +""" + + +# fmt: off +class Tests(): + category_selected = ("Category can be selected", "Category cannot be selected") + node_selected = ("Node can be selected", "Node cannot be selected") +# fmt: on + + +GENERAL_WAIT = 0.5 # seconds + + +def NodePalette_SelectNode(): + """ + Summary: + Categories and Nodes can be selected + + Expected Behavior: + When clicked on Node Palette, nodes and categories can be selected. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Expand QTreeView + 4) Click on category and check if it is selected + 5) Click on node and check if it is selected + 6) Close Script Canvas window + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + CATEGORY = "AI" + NODE = "Find Path To Entity" + + from PySide2 import QtWidgets + import azlmbr.legacy.general as general + + import pyside_utils + from utils import TestHelper as helper + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + if sc.findChild(QtWidgets.QDockWidget, "NodePalette") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Node Palette", "type": QtWidgets.QAction}) + action.trigger() + node_palette = sc.findChild(QtWidgets.QDockWidget, "NodePalette") + tree = node_palette.findChild(QtWidgets.QTreeView, "treeView") + + # 3) Expand QTreeView + tree.expandAll() + + # 4) Click on category and check if it is selected + category_index = pyside_utils.find_child_by_hierarchy(tree, CATEGORY) + tree.scrollTo(category_index) + pyside_utils.item_view_index_mouse_click(tree, category_index) + pyside_utils.wait_for_condition(tree.selectedIndexes() and tree.selectedIndexes()[0] == category_index) + Report.result(Tests.category_selected, tree.selectedIndexes()[0] == category_index) + + # 5) Click on node and check if it is selected + node_index = pyside_utils.find_child_by_pattern(tree, NODE) + helper.wait_for_condition(lambda: tree.isExpanded(node_index), GENERAL_WAIT) + pyside_utils.item_view_index_mouse_click(tree, node_index) + pyside_utils.wait_for_condition(tree.selectedIndexes()[0] == node_index) + Report.result(Tests.node_selected, tree.selectedIndexes()[0] == node_index) + + # 6) Close Script Canvas window + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(NodePalette_SelectNode) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py new file mode 100644 index 0000000000..cea1230348 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py @@ -0,0 +1,185 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92569253 // T92569254 +Test Case Title: On Entity Activated // On Entity Deactivated +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92569253 // https://testrail.agscollab.com/index.php?/tests/view/92569254 +""" + + +# fmt: off +class Tests(): + level_created = ("Successfully created temp level", "Failed to create temp level") + controller_exists = ("Successfully found controller entity", "Failed to find controller entity") + activated_exists = ("Successfully found activated entity", "Failed to find activated entity") + deactivated_exists = ("Successfully found deactivated entity","Failed to find deactivated entity") + start_states_correct = ("Start states set up successfully", "Start states set up incorrectly") + game_mode_entered = ("Successfully entered game mode" "Failed to enter game mode") + lines_found = ("Successfully found expected prints", "Failed to find expected prints") + game_mode_exited = ("Successfully exited game mode" "Failed to exit game mode") +# fmt: on + + +def OnEntityActivatedDeactivated_PrintMessage(): + """ + Summary: + Verify that the On Entity Activation node is working as expected + + Expected Behavior: + Upon entering game mode, the Controller entity will wait 1 second and then activate the ActivationTest + entity. The script attached to ActivationTest will print out a message on activation. The Controller + will also deactivate the DeactivationTest entity, which should print a message. + + Test Steps: + 1) Create temp level + 2) Setup the level + 3) Validate the entities + 4) Start the Tracer + 5) Enter Game Mode + 6) Validate Print message + 7) Exit game mode + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + + from utils import TestHelper as helper + from editor_entity_utils import EditorEntity as Entity + from utils import Report + from utils import Tracer + + import azlmbr.legacy.general as general + + EditorEntity = str + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 # SECONDS + EXPECTED_LINES = ["Activator Script: Activated", "Deactivator Script: Deactivated"] + controller_dict = { + "name": "Controller", + "status": "active", + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "controller.scriptcanvas") + } + activated_dict = { + "name": "ActivationTest", + "status": "inactive", + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "activator.scriptcanvas") + } + deactivated_dict = { + "name": "DeactivationTest", + "status": "active", + "path": os.path.join("ScriptCanvas", "OnEntityActivatedScripts", "deactivator.scriptcanvas") + } + + def get_asset(asset_path): + return azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False) + + def setup_level(): + def create_editor_entity(entity_dict:dict, entity_to_activate:EditorEntity=None, entity_to_deactivate:EditorEntity=None) -> EditorEntity: + entity = Entity.create_editor_entity(entity_dict["name"]) + entity.set_start_status(entity_dict["status"]) + sc_component = entity.add_component("Script Canvas") + sc_component.set_component_property_value("Script Canvas Asset|Script Canvas Asset", get_asset(entity_dict["path"])) + + if entity_dict["name"] == "Controller": + sc_component.get_property_tree() + sc_component.set_component_property_value("Properties|Variable Fields|Variables|[0]|Name,Value|Datum|Datum|EntityToActivate", entity_to_activate.id) + sc_component.set_component_property_value("Properties|Variable Fields|Variables|[1]|Name,Value|Datum|Datum|EntityToDeactivate", entity_to_deactivate.id) + return entity + + activated = create_editor_entity(activated_dict) + deactivated = create_editor_entity(deactivated_dict) + create_editor_entity(controller_dict, activated, deactivated) + + def validate_entity_exist(entity_name: str, test_tuple: tuple): + """ + Validate the entity with the given name exists in the level + :return: entity: editor entity object + """ + entity = Entity.find_editor_entity(entity_name) + Report.critical_result(test_tuple, entity.id.IsValid()) + return entity + + def validate_start_state(entity:EditorEntity, expected_state:str): + """ + Validate that the starting state of the entity is correct, if it isn't then attempt to rectify and recheck. + :return: bool: Whether state is set as expected + """ + state_options = { + "active": azlmbr.globals.property.EditorEntityStartStatus_StartActive, + "inactive": azlmbr.globals.property.EditorEntityStartStatus_StartInactive, + "editor": azlmbr.globals.property.EditorEntityStartStatus_EditorOnly, + } + if expected_state.lower() not in state_options.keys(): + raise ValueError(f"{expected_state} is an invalid option; valid options: active, inactive, or editor.") + + state = entity.get_start_status() + if state != state_options[expected_state]: + # If state fails to set, set_start_status will assert + entity.set_start_status(expected_state) + return True + + def validate_entities_in_level(): + controller = validate_entity_exist(controller_dict["name"], Tests.controller_exists) + state1_correct = validate_start_state(controller, controller_dict["status"]) + + act_tester = validate_entity_exist(activated_dict["name"], Tests.activated_exists) + state2_correct = validate_start_state(act_tester, activated_dict["status"]) + + deac_tester = validate_entity_exist(deactivated_dict["name"], Tests.deactivated_exists) + state3_correct = validate_start_state(deac_tester, deactivated_dict["status"]) + + all_states_correct = state1_correct and state2_correct and state3_correct + Report.critical_result(Tests.start_states_correct, all_states_correct) + + def locate_expected_lines(line_list: list): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + print(f"bhanu: {found_lines}") + return all(line in found_lines for line in line_list) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Setup the level + setup_level() + + # 3) Validate the entities + validate_entities_in_level() + + # 4) Start the Tracer + with Tracer() as section_tracer: + + # 5) Enter Game Mode + helper.enter_game_mode(Tests.game_mode_entered) + + # 6) Validate Print message + helper.wait_for_condition(lambda: locate_expected_lines(EXPECTED_LINES), WAIT_TIME) + + Report.result(Tests.lines_found, locate_expected_lines(EXPECTED_LINES)) + + # 7) Exit game mode + helper.exit_game_mode(Tests.game_mode_exited) + + +if __name__ == "__main__": + import ImportPathHelper as imports + imports.init() + + from utils import Report + + Report.start_test(OnEntityActivatedDeactivated_PrintMessage) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py index 6100285092..666f052240 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Opening_Closing_Pane.py @@ -17,7 +17,6 @@ URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702 # fmt: off class Tests(): - open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") default_visible = ("All the panes visible by default", "One or more panes do not visible by default") open_panes = ("All the Panes opened successfully", "Failed to open one or more panes") close_pane = ("All the Panes closed successfully", "Failed to close one or more panes") @@ -49,11 +48,6 @@ def Opening_Closing_Pane(): :return: None """ - # Helper imports - import ImportPathHelper as imports - - imports.init() - from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import editor_python_test_tools.pyside_utils as pyside_utils @@ -82,8 +76,7 @@ def Opening_Closing_Pane(): # 1) Open Script Canvas window (Tools > Script Canvas) general.open_pane("Script Canvas") - is_sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) - Report.result(Tests.open_sc_window, is_sc_visible) + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) # 2) Restore default layout editor_window = pyside_utils.get_editor_main_window() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py new file mode 100644 index 0000000000..fa5e9e6068 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Pane_RetainOnSCRestart.py @@ -0,0 +1,164 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: C1702821 // C1702832 +Test Case Title: Retain visibility, size and location upon Script Canvas restart +URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702821 and + https://testrail.agscollab.com/index.php?/cases/view/1702832 +""" + + +# fmt: off +class Tests(): + relaunch_sc = ("Script Canvas window is relaunched", "Failed to relaunch Script Canvas window") + test_panes_visible = ("All the test panes are opened", "Failed to open one or more test panes") + close_pane_1 = ("Test pane 1 is closed", "Failed to close test pane 1") + visiblity_retained = ("Test pane retained its visiblity on SC restart", "Failed to retain visiblity of test pane on SC restart") + resize_pane_3 = ("Test pane 3 resized successfully", "Failed to resize Test pane 3") + size_retained = ("Test pane retained its size on SC restart", "Failed to retain size of test pane on SC restart") + location_changed = ("Location of test pane 2 changed successfully", "Failed to change locatio of test pane 2") + location_retained = ("Test pane retained its location on SC restart", "Failed to retain location of test pane on SC restart") +# fmt: on + + +def Pane_RetainOnSCRestart(): + """ + Summary: + The Script Canvas window is opened to verify if Script canvas panes can retain its visibility, size and location + upon ScriptCanvas restart. + + Expected Behavior: + The ScriptCanvas pane retain it's visiblity, size and location upon ScriptCanvas restart. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Make sure test panes are open and visible + 3) Close test pane 1 + 4) Change dock location of test pane 2 + 5) Resize test pane 3 + 6) Relaunch Script Canvas + 7) Verify if test pane 1 retain its visiblity + 8) Verify if location of test pane 2 is retained + 9) Verify if size of test pane 3 is retained + 10) Restore default layout and close SC window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + # Helper imports + from utils import Report + from utils import TestHelper as helper + import pyside_utils + + # Open 3D Engine Imports + import azlmbr.legacy.general as general + + # Pyside imports + from PySide2 import QtCore, QtWidgets + from PySide2.QtCore import Qt + + # Constants + TEST_PANE_1 = "NodePalette" # test visibility + TEST_PANE_2 = "VariableManager" # test location + TEST_PANE_3 = "NodeInspector" # test size + SCALE_INT = 10 # Random resize scale integer + DOCKAREA = Qt.TopDockWidgetArea # Preferred top area since no widget is docked on top + + def click_menu_option(window, option_text): + action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) + action.trigger() + + def find_pane(window, pane_name): + return window.findChild(QtWidgets.QDockWidget, pane_name) + + # Test starts here + general.idle_enable(True) + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 3.0) + + # 2) Make sure test panes are open and visible + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + click_menu_option(sc, "Restore Default Layout") + test_pane_1 = sc.findChild(QtWidgets.QDockWidget, TEST_PANE_1) + test_pane_2 = sc.findChild(QtWidgets.QDockWidget, TEST_PANE_2) + test_pane_3 = sc.findChild(QtWidgets.QDockWidget, TEST_PANE_3) + + Report.result( + Tests.test_panes_visible, test_pane_1.isVisible() and test_pane_2.isVisible() and test_pane_3.isVisible() + ) + + # Initiate try block here to restore default in finally block + try: + # 3) Close test pane + test_pane_1.close() + Report.result(Tests.close_pane_1, not test_pane_1.isVisible()) + + # 4) Change dock location of test pane 2 + sc_main = sc.findChild(QtWidgets.QMainWindow) + sc_main.addDockWidget(DOCKAREA, find_pane(sc_main, TEST_PANE_2), QtCore.Qt.Vertical) + Report.result(Tests.location_changed, sc_main.dockWidgetArea(find_pane(sc_main, TEST_PANE_2)) == DOCKAREA) + + # 5) Resize test pane 3 + initial_size = test_pane_3.frameSize() + test_pane_3.resize(initial_size.width() + SCALE_INT, initial_size.height() + SCALE_INT) + new_size = test_pane_3.frameSize() + resize_success = ( + abs(initial_size.width() - new_size.width()) == abs(initial_size.height() - new_size.height()) == SCALE_INT + ) + Report.result(Tests.resize_pane_3, resize_success) + + # 6) Relaunch Script Canvas + general.close_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 2.0) + + general.open_pane("Script Canvas") + sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + Report.result(Tests.relaunch_sc, sc_visible) + + # 7) Verify if test pane 1 retain its visiblity + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + Report.result(Tests.visiblity_retained, not find_pane(sc, TEST_PANE_1).isVisible()) + + # 8) Verify if location of test pane 2 is retained + sc_main = sc.findChild(QtWidgets.QMainWindow) + Report.result(Tests.location_retained, sc_main.dockWidgetArea(find_pane(sc_main, TEST_PANE_2)) == DOCKAREA) + + # 9) Verify if size of test pane 3 is retained + test_pane_3 = sc.findChild(QtWidgets.QDockWidget, TEST_PANE_3) + retained_size = test_pane_3.frameSize() + retain_success = retained_size != initial_size + Report.result(Tests.size_retained, retain_success) + + finally: + # 10) Restore default layout and close SC window + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + click_menu_option(sc, "Restore Default Layout") + sc.close() + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Pane_RetainOnSCRestart) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py index 9262e76cb0..180f577953 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/Resizing_Pane.py @@ -16,7 +16,6 @@ URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702 # fmt: off class Tests(): - open_sc_window = ("Script Canvas window is opened", "Failed to open Script Canvas window") open_pane = ("Pane opened successfully", "Failed to open pane") resize_pane = ("Pane window resized successfully", "Failed to resize pane window") # fmt: on @@ -46,11 +45,6 @@ def Resizing_Pane(): :return: None """ - # Helper imports - import ImportPathHelper as imports - - imports.init() - from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper import editor_python_test_tools.pyside_utils as pyside_utils @@ -76,8 +70,7 @@ def Resizing_Pane(): # 1) Open Script Canvas window (Tools > Script Canvas) general.open_pane("Script Canvas") - is_sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) - Report.result(Tests.open_sc_window, is_sc_visible) + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) # 2) Restore default layout editor_window = pyside_utils.get_editor_main_window() diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py new file mode 100644 index 0000000000..38d60ad871 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_ChangingAssets.py @@ -0,0 +1,116 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92562986 +Test Case Title: Changing the assigned Script Canvas Asset on an entity properly updates +level functionality +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92562986 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "New level not created") + entity_created = ("Test Entity created", "Test Entity not created") + game_mode_entered = ("Game Mode successfully entered", "Game mode failed to enter") + game_mode_exited = ("Game Mode successfully exited", "Game mode failed to exited") + found_lines = ("Expected log lines were found", "Expected log lines were not found") +# fmt: on + + +def ScriptCanvas_ChangingAssets(): + """ + Summary: + Changing the assigned Script Canvas Asset on an entity properly updates level functionality + + Expected Behavior: + When game mode is entered, respective strings of assigned assets should be printed + + Test Steps: + 1) Create temp level + 2) Create new entity + 3) Start Tracer + 4) Set first script and evaluate + 5) Set second script and evaluate + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import os + + from utils import TestHelper as helper + from utils import Tracer + import hydra_editor_utils as hydra + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.asset as asset + import azlmbr.bus as bus + import azlmbr.paths as paths + + LEVEL_NAME = "tmp_level" + ASSET_1 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents0.scriptcanvas") + ASSET_2 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents1.scriptcanvas") + EXP_LINE_1 = "Greetings from the first script" + EXP_LINE_2 = "Greetings from the second script" + WAIT_TIME = 3.0 # SECONDS + + def get_asset(asset_path): + return asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + + def find_expected_line(expected_line): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + return expected_line in found_lines + + def set_asset_evaluate(test_entity, ASSET_PATH, EXP_LINE): + # Set Script Canvas entity + test_entity.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_PATH)) + + # Enter/exit game mode + helper.enter_game_mode(Tests.game_mode_entered) + helper.wait_for_condition(lambda: find_expected_line(EXP_LINE), WAIT_TIME) + Report.result(Tests.found_lines, find_expected_line(EXP_LINE)) + helper.exit_game_mode(Tests.game_mode_exited) + + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create new entity + position = math.Vector3(512.0, 512.0, 32.0) + test_entity = hydra.Entity("test_entity") + test_entity.create_entity(position, ["Script Canvas"]) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Set first script and evaluate + set_asset_evaluate(test_entity, ASSET_1, EXP_LINE_1) + + # 5) Set second script and evaluate + set_asset_evaluate(test_entity, ASSET_2, EXP_LINE_2) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(ScriptCanvas_ChangingAssets) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py new file mode 100644 index 0000000000..896bee96e5 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoComponents.py @@ -0,0 +1,118 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92563190 +Test Case Title: A single Entity with two Script Canvas components works properly +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563190 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "New level not created") + game_mode_entered = ("Game Mode successfully entered", "Game mode failed to enter") + game_mode_exited = ("Game Mode successfully exited", "Game mode failed to exited") + found_lines = ("Expected log lines were found", "Expected log lines were not found") +# fmt: on + + +class LogLines: + expected_lines = ["Greetings from the first script", "Greetings from the second script"] + + +def ScriptCanvas_TwoComponents(): + """ + Summary: + A test entity contains two Script Canvas components with different unique script canvas files. + Each of these files will have a print node set to activate on graph start. + + Expected Behavior: + When game mode is entered, two unique strings should be printed out to the console + + Test Steps: + 1) Create level + 2) Create entity with SC components + 3) Start Tracer + 4) Enter game mode + 5) Wait for expected lines to be found + 6) Report if expected lines were found + 7) Exit game mode + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + + from utils import TestHelper as helper + import hydra_editor_utils as hydra + from utils import Report + from utils import Tracer + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.asset as asset + import azlmbr.bus as bus + + LEVEL_NAME = "tmp_level" + ASSET_1 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents0.scriptcanvas") + ASSET_2 = os.path.join("scriptcanvas", "ScriptCanvas_TwoComponents1.scriptcanvas") + WAIT_TIME = 3.0 # SECONDS + + def get_asset(asset_path): + return asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + + def locate_expected_lines(): + found_lines = [] + for printInfo in section_tracer.prints: + found_lines.append(printInfo.message.strip()) + + return all(line in found_lines for line in LogLines.expected_lines) + + # 1) Create level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create entity with SC components + position = math.Vector3(512.0, 512.0, 32.0) + test_entity = hydra.Entity("test_entity") + test_entity.create_entity(position, ["Script Canvas", "Script Canvas"]) + test_entity.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_1)) + test_entity.get_set_test(1, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_2)) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Enter game mode + helper.enter_game_mode(Tests.game_mode_entered) + + # 5) Wait for expected lines to be found + helper.wait_for_condition(locate_expected_lines, WAIT_TIME) + + # 6) Report if expected lines were found + Report.result(Tests.found_lines, locate_expected_lines()) + + # 7) Exit game mode + helper.exit_game_mode(Tests.game_mode_exited) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(ScriptCanvas_TwoComponents) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py new file mode 100644 index 0000000000..401e6c0271 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptCanvas_TwoEntities.py @@ -0,0 +1,107 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92563191 +Test Case Title: Two Entities can use the same Graph asset successfully at RunTime +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92563191 +""" + + +# fmt: off +class Tests(): + level_created = ("New level created", "New level not created") + game_mode_entered = ("Game Mode successfully entered", "Game mode failed to enter") + game_mode_exited = ("Game Mode successfully exited", "Game mode failed to exited") + found_lines = ("Expected log lines were found", "Expected log lines were not found") +# fmt: on + + +def ScriptCanvas_TwoEntities(): + """ + Summary: + Two Entities can use the same Graph asset successfully at RunTime. The script canvas asset + attached to the enties will print the respective entity names. + + Expected Behavior: + When game mode is entered, respective strings of different entities should be printed. + + Test Steps: + 1) Create temp level + 2) Create two new entities with different names + 3) Set ScriptCanvas asset to both the entities + 4) Enter/Exit game mode and verify log lines + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + import os + + from utils import TestHelper as helper + from utils import Tracer + import hydra_editor_utils as hydra + import azlmbr.legacy.general as general + import azlmbr.math as math + import azlmbr.asset as asset + import azlmbr.bus as bus + + LEVEL_NAME = "tmp_level" + ASSET_PATH = os.path.join("scriptcanvas", "T92563191_test.scriptcanvas") + EXPECTED_LINES = ["Entity Name: test_entity_1", "Entity Name: test_entity_2"] + WAIT_TIME = 0.5 # SECONDS + + def get_asset(asset_path): + return asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", asset_path, math.Uuid(), False) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create two new entities with different names + position = math.Vector3(512.0, 512.0, 32.0) + test_entity_1 = hydra.Entity("test_entity_1") + test_entity_1.create_entity(position, ["Script Canvas"]) + + test_entity_2 = hydra.Entity("test_entity_2") + test_entity_2.create_entity(position, ["Script Canvas"]) + + # 3) Set ScriptCanvas asset to both the entities + test_entity_1.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_PATH)) + test_entity_2.get_set_test(0, "Script Canvas Asset|Script Canvas Asset", get_asset(ASSET_PATH)) + + # 4) Enter/Exit game mode and verify log lines + with Tracer() as section_tracer: + + helper.enter_game_mode(Tests.game_mode_entered) + # wait for WAIT_TIME to let the script print strings + general.idle_wait(WAIT_TIME) + helper.exit_game_mode(Tests.game_mode_exited) + + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + result = all(line in found_lines for line in EXPECTED_LINES) + + Report.result(Tests.found_lines, result) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(ScriptCanvas_TwoEntities) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py new file mode 100644 index 0000000000..d671229cdf --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveAcrossMultiple.py @@ -0,0 +1,120 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92567321 +Test Case Title: Script Events: Can send and receive a script event across multiple entities successfully +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567321 +""" + + +# fmt: off +class Tests(): + level_created = ("Successfully created temporary level", "Failed to create temporary level") + entitya_created = ("Successfully created EntityA", "Failed to create EntityA") + entityb_created = ("Successfully created EntityB", "Failed to create EntityB") + enter_game_mode = ("Successfully entered game mode", "Failed to enter game mode") + lines_found = ("Successfully found expected message", "Failed to find expected message") + exit_game_mode = ("Successfully exited game mode", "Failed to exit game mode") +# fmt: on + + +def ScriptEvents_SendReceiveAcrossMultiple(): + """ + Summary: + EntityA and EntityB will be created in a level. Attached to both will be a Script Canvas component. The Script Event created for the test will be sent from EntityA to EntityB. + + Expected Behavior: + The output of the Script Event should be printed to the console + + Test Steps: + 1) Create test level + 2) Create EntityA/EntityB (add scriptcanvas files part of entity setup) + 3) Start Tracer + 4) Enter Game Mode + 5) Read for line + 6) Exit Game Mode + + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + + from editor_entity_utils import EditorEntity as Entity + from utils import Report + from utils import TestHelper as helper + from utils import Tracer + + import azlmbr.legacy.general as general + + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 + ASSET_PREFIX = "T92567321" + asset_paths = { + "event": os.path.join("TestAssets", f"{ASSET_PREFIX}.scriptevents"), + "assetA": os.path.join("ScriptCanvas", f"{ASSET_PREFIX}A.scriptcanvas"), + "assetB": os.path.join("ScriptCanvas", f"{ASSET_PREFIX}B.scriptcanvas"), + } + sc_for_entities = { + "EntityA": asset_paths["assetA"], + "EntityB": asset_paths["assetB"] + } + EXPECTED_LINES = ["Incoming Message Received"] + + def get_asset(asset_path): + return azlmbr.asset.AssetCatalogRequestBus(azlmbr.bus.Broadcast, "GetAssetIdByPath", asset_path, azlmbr.math.Uuid(), False) + + def create_editor_entity(name, sc_asset): + entity = Entity.create_editor_entity(name) + sc_comp = entity.add_component("Script Canvas") + sc_comp.set_component_property_value("Script Canvas Asset|Script Canvas Asset", get_asset(sc_asset)) + Report.critical_result(Tests.__dict__[name.lower()+"_created"], entity.id.isValid()) + + def locate_expected_lines(line_list: list): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + + return all(line in found_lines for line in line_list) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create EntityA/EntityB + for key in sc_for_entities.keys(): + create_editor_entity(key, sc_for_entities[key]) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Enter Game Mode + helper.enter_game_mode(Tests.enter_game_mode) + + # 5) Read for line + lines_located = helper.wait_for_condition(lambda: locate_expected_lines(EXPECTED_LINES), WAIT_TIME) + Report.result(Tests.lines_found, lines_located) + + # 6) Exit Game Mode + helper.exit_game_mode(Tests.exit_game_mode) + + +if __name__ == "__main__": + import ImportPathHelper as imports + imports.init() + + from utils import Report + + Report.start_test(ScriptEvents_SendReceiveAcrossMultiple) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py new file mode 100644 index 0000000000..b5e26d14ae --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/ScriptEvents_SendReceiveSuccessfully.py @@ -0,0 +1,110 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92567320 +Test Case Title: Script Events: Can send and receive a script event successfully +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92567320 +""" + + +# fmt: off +class Tests(): + level_created = ("Successfully created temporary level", "Failed to create temporary level") + entity_created = ("Successfully created test entity", "Failed to create test entity") + enter_game_mode = ("Successfully entered game mode", "Failed to enter game mode") + lines_found = ("Successfully found expected message", "Failed to find expected message") + exit_game_mode = ("Successfully exited game mode", "Failed to exit game mode") +# fmt: on + + +def ScriptEvents_SendReceiveSuccessfully(): + """ + Summary: + An entity exists in the level that contains a Script Canvas component. In the graph is both a Send Event + and a Receive Event. + + Expected Behavior: + After entering game mode the graph on the entity should print an expected message to the console + + Test Steps: + 1) Create test level + 2) Create test entity + 3) Start Tracer + 4) Enter Game Mode + 5) Read for line + 6) Exit Game Mode + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + import os + from editor_entity_utils import EditorEntity as Entity + from utils import Report + from utils import TestHelper as helper + from utils import Tracer + + import azlmbr.legacy.general as general + import azlmbr.asset as asset + import azlmbr.math as math + import azlmbr.bus as bus + + LEVEL_NAME = "tmp_level" + WAIT_TIME = 3.0 # SECONDS + EXPECTED_LINES = ["T92567320: Message Received"] + SC_ASSET_PATH = os.path.join("ScriptCanvas", "T92567320.scriptcanvas") + + def create_editor_entity(name, sc_asset): + entity = Entity.create_editor_entity(name) + sc_comp = entity.add_component("Script Canvas") + asset_id = asset.AssetCatalogRequestBus(bus.Broadcast, "GetAssetIdByPath", sc_asset, math.Uuid(), False) + sc_comp.set_component_property_value("Script Canvas Asset|Script Canvas Asset", asset_id) + Report.critical_result(Tests.entity_created, entity.id.isValid()) + + def locate_expected_lines(line_list: list): + found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] + + return all(line in found_lines for line in line_list) + + # 1) Create temp level + general.idle_enable(True) + result = general.create_level_no_prompt(LEVEL_NAME, 128, 1, 512, True) + Report.critical_result(Tests.level_created, result == 0) + helper.wait_for_condition(lambda: general.get_current_level_name() == LEVEL_NAME, WAIT_TIME) + general.close_pane("Error Report") + + # 2) Create test entity + create_editor_entity("TestEntity", SC_ASSET_PATH) + + # 3) Start Tracer + with Tracer() as section_tracer: + + # 4) Enter Game Mode + helper.enter_game_mode(Tests.enter_game_mode) + + # 5) Read for line + lines_located = helper.wait_for_condition(lambda: locate_expected_lines(EXPECTED_LINES), WAIT_TIME) + Report.result(Tests.lines_found, lines_located) + + # 6) Exit Game Mode + helper.exit_game_mode(Tests.exit_game_mode) + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(ScriptEvents_SendReceiveSuccessfully) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py index 8c34f29ebf..d87f2986bf 100755 --- a/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/TestSuite_Active.py @@ -12,22 +12,243 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. import pytest import os import sys +sys.path.append(os.path.dirname(__file__)) +import ImportPathHelper as imports +imports.init() + +import hydra_test_utils as hydra +import ly_test_tools.environment.file_system as file_system from ly_test_tools import LAUNCHERS - -sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') - from base import TestAutomationBase +TEST_DIRECTORY = os.path.dirname(__file__) + + @pytest.mark.SUITE_periodic @pytest.mark.parametrize("launcher_platform", ['windows_editor']) @pytest.mark.parametrize("project", ["AutomatedTesting"]) class TestAutomation(TestAutomationBase): - + @pytest.mark.test_case_id("C1702834", "C1702823") + def test_Opening_Closing_Pane(self, request, workspace, editor, launcher_platform): + from . import Opening_Closing_Pane as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("C1702824") def test_Docking_Pane(self, request, workspace, editor, launcher_platform): from . import Docking_Pane as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.test_case_id("C1702829") def test_Resizing_Pane(self, request, workspace, editor, launcher_platform): from . import Resizing_Pane as test_module self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92563190") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptCanvas_TwoComponents(self, request, workspace, editor, launcher_platform, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptCanvas_TwoComponents as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92562986") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptCanvas_ChangingAssets(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptCanvas_ChangingAssets as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569079", "T92569081") + def test_Graph_ZoomInZoomOut(self, request, workspace, editor, launcher_platform): + from . import Graph_ZoomInZoomOut as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92568940") + def test_NodePalette_SelectNode(self, request, workspace, editor, launcher_platform): + from . import NodePalette_SelectNode as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569253") + @pytest.mark.test_case_id("T92569254") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_OnEntityActivatedDeactivated_PrintMessage(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import OnEntityActivatedDeactivated_PrintMessage as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92562993") + def test_NodePalette_ClearSelection(self, request, workspace, editor, launcher_platform, project): + from . import NodePalette_ClearSelection as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92563191") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptCanvas_TwoEntities(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptCanvas_TwoEntities as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569013") + def test_AssetEditor_CreateScriptEventFile(self, request, workspace, editor, launcher_platform, project): + def teardown(): + file_system.delete( + [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True + ) + request.addfinalizer(teardown) + file_system.delete( + [os.path.join(workspace.paths.project(), "ScriptCanvas", "test_file.scriptevent")], True, True + ) + from . import AssetEditor_CreateScriptEventFile as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569165", "T92569167", "T92569168", "T92569170") + def test_Toggle_ScriptCanvasTools(self, request, workspace, editor, launcher_platform): + from . import Toggle_ScriptCanvasTools as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92568982") + def test_NodeInspector_RenameVariable(self, request, workspace, editor, launcher_platform, project): + from . import NodeInspector_RenameVariable as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569137") + def test_Debugging_TargetMultipleGraphs(self, request, workspace, editor, launcher_platform, project): + from . import Debugging_TargetMultipleGraphs as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92568856") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_Debugging_TargetMultipleEntities(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import Debugging_TargetMultipleEntities as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92569049", "T92569051") + def test_EditMenu_UndoRedo(self, request, workspace, editor, launcher_platform, project): + from . import EditMenu_UndoRedo as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("C1702825", "C1702831") + def test_UnDockedPane_CloseSCWindow(self, request, workspace, editor, launcher_platform): + from . import UnDockedPane_CloseSCWindow as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92562978") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_Entity_AddScriptCanvasComponent(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import Entity_AddScriptCanvasComponent as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("C1702821", "C1702832") + def test_Pane_RetainOnSCRestart(self, request, workspace, editor, launcher_platform): + from . import Pane_RetainOnSCRestart as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92567321") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptEvents_SendReceiveAcrossMultiple(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptEvents_SendReceiveAcrossMultiple as test_module + self._run_test(request, workspace, editor, test_module) + + @pytest.mark.test_case_id("T92567320") + @pytest.mark.parametrize("level", ["tmp_level"]) + def test_ScriptEvents_SendReceiveSuccessfully(self, request, workspace, editor, launcher_platform, project, level): + def teardown(): + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + request.addfinalizer(teardown) + file_system.delete([os.path.join(workspace.paths.project(), "Levels", level)], True, True) + from . import ScriptEvents_SendReceiveSuccessfully as test_module + self._run_test(request, workspace, editor, test_module) + +# NOTE: We had to use hydra_test_utils.py, as TestAutomationBase run_test method +# fails because of pyside_utils import +@pytest.mark.SUITE_periodic +@pytest.mark.parametrize("launcher_platform", ["windows_editor"]) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestScriptCanvasTests(object): + """ + The following tests use hydra_test_utils.py to launch the editor and validate the results. + """ + + @pytest.mark.test_case_id("T92569037", "T92569039") + def test_FileMenu_New_Open(self, request, editor, launcher_platform): + expected_lines = [ + "File->New action working as expected: True", + "File->Open action working as expected: True", + ] + hydra.launch_and_validate_results( + request, TEST_DIRECTORY, editor, "FileMenu_New_Open.py", expected_lines, auto_test_mode=False, timeout=60, + ) + + @pytest.mark.test_case_id("T92568942") + def test_AssetEditor_NewScriptEvent(self, request, editor, launcher_platform): + expected_lines = [ + "New Script event action found: True", + "Asset Editor opened: True", + "Asset Editor created with new asset: True", + "New Script event created in Asset Editor: True", + ] + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "AssetEditor_NewScriptEvent.py", + expected_lines, + auto_test_mode=False, + timeout=60, + ) + + @pytest.mark.test_case_id("T92563068", "T92563070") + def test_GraphClose_SavePrompt(self, request, editor, launcher_platform): + expected_lines = [ + "New graph created: True", + "Save prompt opened as expected: True", + "Close button worked as expected: True", + ] + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "GraphClose_SavePrompt.py", + expected_lines, + auto_test_mode=False, + timeout=60, + ) + + @pytest.mark.test_case_id("T92564789", "T92568873") + def test_VariableManager_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] + expected_lines.extend([f"Success: {var_type} variable is deleted" for var_type in var_types]) + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "VariableManager_CreateDeleteVars.py", + expected_lines, + auto_test_mode=False, + timeout=60, + ) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py new file mode 100644 index 0000000000..4024e28277 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/Toggle_ScriptCanvasTools.py @@ -0,0 +1,137 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: C92569165, C92569167, C92569168, C92569170 +Test Case Title: Tools > Node Palette toggles the Node Palette + Tools > Node Inspector toggles the Node Inspector + Tools > Bookmarks toggles the Bookmarks + Tools > Variable Manager toggles the Variable Manager + +URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/92569165 + https://testrail.agscollab.com/index.php?/cases/view/92569167 + https://testrail.agscollab.com/index.php?/cases/view/92569168 + https://testrail.agscollab.com/index.php?/cases/view/92569170 +""" + + +# fmt: off +class Tests(): + node_palette_opened = ("NodePalette is opened successfully", "Failed to open NodePalette") + node_inspector_opened = ("NodeInspector is opened successfully", "Failed to open NodeInspector") + bookmark_opened = ("Bookmarks is opened successfully", "Failed to open Bookmarks") + variable_manager_opened = ("VariableManager is opened successfully", "Failed to open VariableManager") + node_palette_closed_by_start = ("NodePalette is closed successfully", "Failed to close NodePalette") + node_inspector_closed_by_start = ("NodeInspector is closed successfully", "Failed to close NodeInspector") + bookmark_closed_by_start = ("Bookmarks is closed successfully", "Failed to close Bookmarks") + variable_manager_closed_by_start = ("VariableManager is closed successfully", "Failed to close VariableManager") + node_palette_closed_by_end = ("NodePalette is closed successfully", "Failed to close NodePalette") + node_inspector_closed_by_end = ("NodeInspector is closed successfully", "Failed to close NodeInspector") + bookmark_closed_by_end = ("Bookmarks is closed successfully", "Failed to close Bookmarks") + variable_manager_closed_by_end = ("VariableManager is closed successfully", "Failed to close VariableManager") +# fmt: on + + +def Toggle_ScriptCanvasTools(): + """ + Summary: + Toggle Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas. + Make sure each pane opens and closes successfully. + + Expected Behavior: + Each pane opens and closes successfully. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Make sure Node Palette, Node Inspector, Bookmarks and Variable Manager panes are closed in Script Canvas window + 3) Open Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas window + 4) Close Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas window + 5) Restore default layout + 6) Close Script Canvas window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from utils import Report + from utils import TestHelper as helper + import pyside_utils + + # Open 3D Engine imports + import azlmbr.legacy.general as general + + # Pyside imports + from PySide2 import QtWidgets + + def click_menu_option(window, option_text): + action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) + action.trigger() + + def find_pane(window, pane_name): + return window.findChild(QtWidgets.QDockWidget, pane_name) + + def close_tool(window, pane_widget, test_tuple): + pane = find_pane(window, pane_widget) + pane.close() + Report.result(test_tuple, not pane.isVisible()) + + def open_tool(window, pane_widget, tool, test_tuple): + pane = find_pane(window, pane_widget) + if not pane.isVisible(): + click_menu_option(window, tool) + pane = find_pane(window, pane_widget) + Report.result(test_tuple, pane.isVisible()) + + # Test starts here + general.idle_enable(True) + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Make sure Node Palette, Node Inspector, Bookmarks and Variable Manager panes are closed in Script Canvas window + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + close_tool(sc, "NodePalette", Tests.node_palette_closed_by_start) + close_tool(sc, "NodeInspector", Tests.node_inspector_closed_by_start) + close_tool(sc, "BookmarkDockWidget", Tests.bookmark_closed_by_start) + close_tool(sc, "VariableManager", Tests.variable_manager_closed_by_start) + + # 3) Open Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas window + open_tool(sc, "NodePalette", "Node Palette", Tests.node_palette_opened) + open_tool(sc, "NodeInspector", "Node Inspector", Tests.node_inspector_opened) + open_tool(sc, "BookmarkDockWidget", "Bookmarks", Tests.bookmark_opened) + open_tool(sc, "VariableManager", "Variable Manager", Tests.variable_manager_opened) + + # 4) Close Node Palette, Node Inspector, Bookmarks and Variable Manager in Script Canvas window + close_tool(sc, "NodePalette", Tests.node_palette_closed_by_end) + close_tool(sc, "NodeInspector", Tests.node_inspector_closed_by_end) + close_tool(sc, "BookmarkDockWidget", Tests.bookmark_closed_by_end) + close_tool(sc, "VariableManager", Tests.variable_manager_closed_by_end) + + # 5) Restore default layout + # Need this step to restore to default in case of test failure + click_menu_option(sc, "Restore Default Layout") + + # 6) Close Script Canvas window + sc.close() + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(Toggle_ScriptCanvasTools) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py new file mode 100644 index 0000000000..875f28ec95 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/UnDockedPane_CloseSCWindow.py @@ -0,0 +1,128 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: C1702825 // C1702831 +Test Case Title: Undocking // Closing script canvas with the pane floating +URLs of the test case: https://testrail.agscollab.com/index.php?/cases/view/1702825 & + https://testrail.agscollab.com/index.php?/cases/view/1702831 +""" + + +# fmt: off +class Tests(): + undock_pane = ("Pane is undocked successfully", "Failed to undock pane") + close_sc_window = ("Script Canvas window is closed", "Failed to close Script Canvas window") + pane_closed = ("Pane is closed successfully", "Failed to close the pane") +# fmt: on + + +def UnDockedPane_CloseSCWindow(): + """ + Summary: + The Script Canvas window is opened with one of the pane undocked. + Verify if undocked pane closes upon closing Script canvas window. + + Expected Behavior: + The undocked pane closes when Script Canvas window closed. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Undock Node Palette pane + 3) Connect to Pane visibility signal emitter to verify pane closed + 4) Close Script Canvas window + 5) Restore default layout + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + # Helper imports + from utils import Report + from utils import TestHelper as helper + import pyside_utils + + # Open 3D Engine imports + import azlmbr.legacy.general as general + + # Pyside imports + from PySide2 import QtWidgets + + TEST_PANE = "NodePalette" # Chosen most commonly used pane + + def click_menu_option(window, option_text): + action = pyside_utils.find_child_by_pattern(window, {"text": option_text, "type": QtWidgets.QAction}) + action.trigger() + + def find_pane(window, pane_name): + return window.findChild(QtWidgets.QDockWidget, pane_name) + + def on_top_level_changed(): + # This function has test condition always True since it gets emitted only when condition satisfied + Report.result(Tests.undock_pane, True) + + def on_pane_closed(): + # This function has test condition always True since it gets emitted only when condition satisfied + Report.result(Tests.pane_closed, True) + + # Test starts here + general.idle_enable(True) + + # 1) Open Script Canvas window (Tools > Script Canvas) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + + # 2) Undock Node Palette pane + # Make sure Node Palette pane is opened + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + pane = find_pane(sc, TEST_PANE) + if not pane.isVisible(): + click_menu_option(sc, "Node Palette") + pane = find_pane(sc, TEST_PANE) # New reference + + # We drag/drop pane over the graph since it doesn't allow docking, so this will undock it + try: + graph = find_pane(sc, "GraphCanvasEditorCentralWidget") + try: + pane.topLevelChanged.connect(on_top_level_changed) + pyside_utils.drag_and_drop(pane, graph) + finally: + pane.topLevelChanged.disconnect(on_top_level_changed) + + # 3) Connect to Pane visibility signal emitter to verify pane closed + # No need to disconnect this since pane widget gets deleted when SC window closed + pane.visibilityChanged.connect(on_pane_closed) + + # 4) Close Script Canvas window + sc.close() + is_sc_visible = helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 2.0) + Report.result(Tests.close_sc_window, not is_sc_visible) + + finally: + # 5) Restore default layout + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 5.0) + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + click_menu_option(sc, "Restore Default Layout") + sc.close() + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + + from utils import Report + + Report.start_test(UnDockedPane_CloseSCWindow) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py new file mode 100644 index 0000000000..6facc324d4 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/scripting/VariableManager_CreateDeleteVars.py @@ -0,0 +1,123 @@ +""" +All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or +its licensors. + +For complete copyright and license terms please see the LICENSE at the root of this +distribution (the "License"). All use of this software is governed by the License, +or, if provided, by the license below or the license accompanying this file. Do not +remove or modify any license notices. This file is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + +Test case ID: T92564789 +Test Case Title: Each Variable type can be created +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92564789 +Test case ID: T92568873 +Test Case Title: Each Variable type can be deleted +URL of the test case: https://testrail.agscollab.com/index.php?/tests/view/92568873 +""" + + +def VariableManager_CreateDeleteVars(): + """ + Summary: + Each variable type can be created and deleted in variable manager. + + Expected Behavior: + Each variable type can be created and deleted in variable manager. + + Test Steps: + 1) Open Script Canvas window (Tools > Script Canvas) + 2) Get the SC window object + 3) Open Variable Manager if not opened already + 4) Create Graph + 5) Create variable of each type and verify if it is created + 6) Delete each type of variable and verify if it is deleted + 7) Close SC window + + Note: + - This test file must be called from the Open 3D Engine Editor command terminal + - Any passed and failed tests are written to the Editor.log file. + Parsing the file or running a log_monitor are required to observe the test results. + + :return: None + """ + + from PySide2 import QtWidgets, QtCore, QtTest + + from PySide2.QtCore import Qt + + from utils import TestHelper as helper + + import azlmbr.legacy.general as general + + import pyside_utils + + def generate_test_tuple(var_type, action): + return (f"{var_type} variable is {action}d", f"{var_type} variable is not {action}d") + + # 1) Open Script Canvas window + general.idle_enable(True) + general.open_pane("Script Canvas") + helper.wait_for_condition(lambda: general.is_pane_visible("Script Canvas"), 10.0) + + # 2) Get the SC window object + editor_window = pyside_utils.get_editor_main_window() + sc = editor_window.findChild(QtWidgets.QDockWidget, "Script Canvas") + + # 3) Open Variable Manager if not opened already + if sc.findChild(QtWidgets.QDockWidget, "VariableManager") is None: + action = pyside_utils.find_child_by_pattern(sc, {"text": "Variable Manager", "type": QtWidgets.QAction}) + action.trigger() + variable_manager = sc.findChild(QtWidgets.QDockWidget, "VariableManager") + + # 4) Create Graph + action = pyside_utils.find_child_by_pattern(sc, {"objectName": "action_New_Script", "type": QtWidgets.QAction}) + action.trigger() + + graph_vars = variable_manager.findChild(QtWidgets.QTableView, "graphVariables") + + var_types = ["Boolean", "Color", "EntityID", "Number", "String", "Transform", "Vector2", "Vector3", "Vector4"] + + # 5) Create variable of each type and verify if it is created + for index, var_type in enumerate(var_types): + # Create new variable + add_button = variable_manager.findChild(QtWidgets.QPushButton, "addButton") + add_button.click() # Click on Create Variable button + # Select variable type + table_view = variable_manager.findChild(QtWidgets.QTableView, "variablePalette") + model_index = pyside_utils.find_child_by_pattern(table_view, var_type) + # Click on it to create variable + pyside_utils.item_view_index_mouse_click(table_view, model_index) + # Verify if the variable is created + # NOTE: To check if variable of a type is created, we are checking 1) rowcount + # 2) If we have row with variable "Variable " + # 3) Type of variable, which is next column of the variable name + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == ( + index + 1 + ) # since we added 1 variable, rowcount will increase by 1 + var_mi = pyside_utils.find_child_by_pattern(graph_vars, f"Variable {index+1}") + result = result and (var_mi is not None) and (var_mi.siblingAtColumn(1).data(Qt.DisplayRole) == var_type) + Report.result(generate_test_tuple(var_type, "create"), result) + + # 6) Delete each type of variable and verify if it is deleted + for index, var_type in enumerate(var_types): + # Delete variable and verify if its deleted + # NOTE: To check if variable of a type is deleted, we are checking rowcount + var_mi = pyside_utils.find_child_by_pattern(graph_vars, f"Variable {index+1}") + pyside_utils.item_view_index_mouse_click(graph_vars, var_mi) + QtTest.QTest.keyClick(graph_vars, Qt.Key_Delete, Qt.NoModifier) + # since variable is deleted, rowcount will decrease by 1 + result = graph_vars.model().rowCount(QtCore.QModelIndex()) == (len(var_types) - (index + 1)) + Report.result(generate_test_tuple(var_type, "delete"), result) + + # 7) Close SC window + general.close_pane("Script Canvas") + + +if __name__ == "__main__": + import ImportPathHelper as imports + + imports.init() + from utils import Report + + Report.start_test(VariableManager_CreateDeleteVars) diff --git a/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/activator.scriptcanvas b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/activator.scriptcanvas new file mode 100644 index 0000000000..89d86f0d54 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/activator.scriptcanvas @@ -0,0 +1,778 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/controller.scriptcanvas b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/controller.scriptcanvas new file mode 100644 index 0000000000..83a899798e --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/controller.scriptcanvas @@ -0,0 +1,1865 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/deactivator.scriptcanvas b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/deactivator.scriptcanvas new file mode 100644 index 0000000000..ca98ee303a --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/OnEntityActivatedScripts/deactivator.scriptcanvas @@ -0,0 +1,766 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents0.scriptcanvas b/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents0.scriptcanvas new file mode 100644 index 0000000000..af3afead19 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents0.scriptcanvas @@ -0,0 +1,365 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents1.scriptcanvas b/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents1.scriptcanvas new file mode 100644 index 0000000000..0a16717520 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/ScriptCanvas_TwoComponents1.scriptcanvas @@ -0,0 +1,365 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/T92563191_test.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92563191_test.scriptcanvas new file mode 100644 index 0000000000..f0797739a5 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92563191_test.scriptcanvas @@ -0,0 +1,750 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/T92567320.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92567320.scriptcanvas new file mode 100644 index 0000000000..d509442435 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92567320.scriptcanvas @@ -0,0 +1,1266 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/T92567321A.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92567321A.scriptcanvas new file mode 100644 index 0000000000..644a5daa17 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92567321A.scriptcanvas @@ -0,0 +1,778 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/ScriptCanvas/T92567321B.scriptcanvas b/AutomatedTesting/ScriptCanvas/T92567321B.scriptcanvas new file mode 100644 index 0000000000..54c83c2933 --- /dev/null +++ b/AutomatedTesting/ScriptCanvas/T92567321B.scriptcanvas @@ -0,0 +1,880 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/TestAssets/T92567320.scriptevents b/AutomatedTesting/TestAssets/T92567320.scriptevents new file mode 100644 index 0000000000..63cf20f2d0 --- /dev/null +++ b/AutomatedTesting/TestAssets/T92567320.scriptevents @@ -0,0 +1,116 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/AutomatedTesting/TestAssets/T92567321.scriptevents b/AutomatedTesting/TestAssets/T92567321.scriptevents new file mode 100644 index 0000000000..6f9308ad02 --- /dev/null +++ b/AutomatedTesting/TestAssets/T92567321.scriptevents @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 3df5f53e5ee465cc3f8f580a9d18095300d8c9d1 Mon Sep 17 00:00:00 2001 From: balibhan Date: Tue, 4 May 2021 15:16:31 +0530 Subject: [PATCH 09/49] updating timeout --- AutomatedTesting/Gem/PythonTests/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt index 6d3727195e..2a8423bd5a 100644 --- a/AutomatedTesting/Gem/PythonTests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/CMakeLists.txt @@ -68,7 +68,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) TEST_SUITE periodic TEST_SERIAL PATH ${CMAKE_CURRENT_LIST_DIR}/scripting/TestSuite_Active.py - TIMEOUT 1500 + TIMEOUT 3000 RUNTIME_DEPENDENCIES Legacy::Editor AZ::AssetProcessor From a206896074d29e93901e883805f486cf55b8a360 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 16:13:38 +0100 Subject: [PATCH 10/49] remove QPoint from lower-level interfaces, switch to use AzFramework::ScreenPoint --- .../ViewportInteraction.h | 7 +++-- .../Source/ViewportInteraction.cpp | 10 ++++--- .../Manipulators/EditorVertexSelection.cpp | 7 ++--- .../Manipulators/SurfaceManipulator.cpp | 9 ++---- .../Viewport/ViewportMessages.h | 12 ++++---- .../ViewportSelection/EditorHelpers.cpp | 10 +++---- .../ViewportSelection/EditorSelectionUtil.cpp | 4 +-- .../ViewportSelection/EditorSelectionUtil.h | 2 +- .../EditorTransformComponentSelection.cpp | 8 ++--- Code/Sandbox/Editor/EditorViewportWidget.cpp | 29 +++++++++--------- Code/Sandbox/Editor/EditorViewportWidget.h | 9 +++--- Code/Sandbox/Editor/RenderViewport.cpp | 13 ++++---- Code/Sandbox/Editor/RenderViewport.h | 17 +++++++---- .../Editor/ViewportManipulatorController.cpp | 3 +- .../Viewport/RenderViewportWidget.h | 7 +++-- .../Source/Viewport/RenderViewportWidget.cpp | 30 +++++++++---------- 16 files changed, 91 insertions(+), 86 deletions(-) diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h index 56ff2010cd..884562d7e8 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ViewportInteraction.h @@ -38,8 +38,9 @@ namespace AzManipulatorTestFramework void SetGridSize(float size) override; void SetAngularStep(float step) override; int GetViewportId() const override; - AZStd::optional ViewportScreenToWorld(const QPoint& screenPosition, float depth) override; - AZStd::optional ViewportScreenToWorldRay(const QPoint& screenPosition) override; + AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) override; + AZStd::optional ViewportScreenToWorldRay( + const AzFramework::ScreenPoint& screenPosition) override; private: // ViewportInteractionRequestBus ... bool GridSnappingEnabled(); @@ -47,7 +48,7 @@ namespace AzManipulatorTestFramework bool ShowGrid(); bool AngleSnappingEnabled(); float AngleStep(); - QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); private: AZStd::unique_ptr m_nullDebugDisplayRequests; const int m_viewportId = 1234; // Arbitrary viewport id for manipulator tests diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp index 11f2a32441..4ab36e58f5 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp @@ -66,10 +66,10 @@ namespace AzManipulatorTestFramework return m_angularStep; } - QPoint ViewportInteraction::ViewportWorldToScreen(const AZ::Vector3& worldPosition) + AzFramework::ScreenPoint ViewportInteraction::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { auto pos = AzFramework::WorldToScreen(worldPosition, m_cameraState); - return QPoint(pos.m_x, pos.m_y); + return AzFramework::ScreenPoint(pos.m_x, pos.m_y); } void ViewportInteraction::SetCameraState(const AzFramework::CameraState& cameraState) @@ -117,12 +117,14 @@ namespace AzManipulatorTestFramework return m_viewportId; } - AZStd::optional ViewportInteraction::ViewportScreenToWorld([[maybe_unused]]const QPoint& screenPosition, [[maybe_unused]]float depth) + AZStd::optional ViewportInteraction::ViewportScreenToWorld( + [[maybe_unused]] const AzFramework::ScreenPoint& screenPosition, [[maybe_unused]] float depth) { return {}; } - AZStd::optional ViewportInteraction::ViewportScreenToWorldRay([[maybe_unused]]const QPoint& screenPosition) + AZStd::optional ViewportInteraction::ViewportScreenToWorldRay( + [[maybe_unused]] const AzFramework::ScreenPoint& screenPosition) { return {}; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp index 089037bbf3..4d10a4c171 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/EditorVertexSelection.cpp @@ -127,8 +127,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint( - mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates)); + mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates); AZ::Transform worldFromLocal; AZ::TransformBus::EventResult(worldFromLocal, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); @@ -402,10 +401,10 @@ namespace AzToolsFramework vertexIndex, localVertex); const AZ::Vector3 worldVertex = worldFromLocal.TransformPoint(AZ::AdaptVertexOut(localVertex)); - const QPoint screenPosition = GetScreenPosition(viewportId, worldVertex); + const AzFramework::ScreenPoint screenPosition = GetScreenPosition(viewportId, worldVertex); // check if a vertex is inside the box select region - if (editorBoxSelect.BoxRegion()->contains(screenPosition)) + if (editorBoxSelect.BoxRegion()->contains(ViewportInteraction::QPointFromScreenPoint(screenPosition))) { // see if vertexIndex is in active selection auto vertexIt = AZStd::find( diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp index e4d0cd59dd..f570c20a7e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Manipulators/SurfaceManipulator.cpp @@ -103,8 +103,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, interaction.m_interactionId.m_viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint( - interaction.m_mousePick.m_screenCoordinates)); + interaction.m_mousePick.m_screenCoordinates); m_startInternal = CalculateManipulationDataStart( worldFromLocalUniformScale, worldSurfacePosition, GetLocalPosition(), @@ -129,8 +128,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, interaction.m_interactionId.m_viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint( - interaction.m_mousePick.m_screenCoordinates)); + interaction.m_mousePick.m_screenCoordinates); const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); @@ -150,8 +148,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, interaction.m_interactionId.m_viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint( - interaction.m_mousePick.m_screenCoordinates)); + interaction.m_mousePick.m_screenCoordinates); const GridSnapParameters gridSnapParams = GridSnapSettings(interaction.m_interactionId.m_viewportId); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h index a9949d382e..6ceb175fe4 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h @@ -21,8 +21,6 @@ #include #include -class QPoint; // LYN-2315 in-progress, remove this - namespace AzFramework { struct ScreenPoint; @@ -167,14 +165,14 @@ namespace AzToolsFramework /// Return the angle snapping/step size. virtual float AngleStep() = 0; /// Transform a point in world space to screen space coordinates. - virtual QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) = 0; + virtual AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) = 0; /// Transform a point in screen space coordinates to a vector in world space based on clip space depth. /// Depth specifies a relative camera depth to project in the range of [0.f, 1.f]. /// Returns the world space position if successful. - virtual AZStd::optional ViewportScreenToWorld(const QPoint& screenPosition, float depth) = 0; + virtual AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) = 0; /// Casts a point in screen space to a ray in world space originating from the viewport camera frustum's near plane. /// Returns a ray containing the ray's origin and a direction normal, if successful. - virtual AZStd::optional ViewportScreenToWorldRay(const QPoint& screenPosition) = 0; + virtual AZStd::optional ViewportScreenToWorldRay(const AzFramework::ScreenPoint& screenPosition) = 0; protected: ~ViewportInteractionRequests() = default; @@ -207,9 +205,9 @@ namespace AzToolsFramework public: /// Given a point in screen space, return the picked entity (if any). /// Picked EntityId will be returned, InvalidEntityId will be returned on failure. - virtual AZ::EntityId PickEntity(const QPoint& point) = 0; + virtual AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) = 0; /// Given a point in screen space, return the terrain position in world space. - virtual AZ::Vector3 PickTerrain(const QPoint& point) = 0; + virtual AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) = 0; /// Return the terrain height given a world position in 2d (xy plane). virtual float TerrainHeight(const AZ::Vector2& position) = 0; /// Given the current view frustum (viewport) return all visible entities. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp index f3abc70fba..68a5b43d73 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorHelpers.cpp @@ -141,16 +141,16 @@ namespace AzToolsFramework const AZ::Vector3& entityPosition = m_entityDataCache->GetVisibleEntityPosition(entityCacheIndex); // selecting based on 2d icon - should only do it when visible and not selected - const QPoint screenPosition = GetScreenPosition(viewportId, entityPosition); + const AzFramework::ScreenPoint screenPosition = GetScreenPosition(viewportId, entityPosition); const float distSqFromCamera = cameraState.m_position.GetDistanceSq(entityPosition); const auto iconRange = static_cast(GetIconScale(distSqFromCamera) * s_iconSize * 0.5f); const auto screenCoords = mouseInteraction.m_mouseInteraction.m_mousePick.m_screenCoordinates; - if ( screenCoords.m_x >= screenPosition.x() - iconRange - && screenCoords.m_x <= screenPosition.x() + iconRange - && screenCoords.m_y >= screenPosition.y() - iconRange - && screenCoords.m_y <= screenPosition.y() + iconRange) + if ( screenCoords.m_x >= screenPosition.m_x - iconRange + && screenCoords.m_x <= screenPosition.m_x + iconRange + && screenCoords.m_y >= screenPosition.m_y - iconRange + && screenCoords.m_y <= screenPosition.m_y + iconRange) { entityIdUnderCursor = entityId; break; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp index 95095bd3c8..3be4bc9db2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.cpp @@ -53,11 +53,11 @@ namespace AzToolsFramework return AZ::GetMax(projectedCameraDistance, cameraState.m_nearClip) / apparentDistance; } - QPoint GetScreenPosition(const int viewportId, const AZ::Vector3& worldTranslation) + AzFramework::ScreenPoint GetScreenPosition(const int viewportId, const AZ::Vector3& worldTranslation) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - QPoint screenPosition = QPoint(); + auto screenPosition = AzFramework::ScreenPoint(0, 0); ViewportInteraction::ViewportInteractionRequestBus::EventResult( screenPosition, viewportId, &ViewportInteraction::ViewportInteractionRequestBus::Events::ViewportWorldToScreen, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h index 65e0a99bfe..9936fb9afd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorSelectionUtil.h @@ -45,7 +45,7 @@ namespace AzToolsFramework const AZ::Vector3& worldPosition, const AzFramework::CameraState& cameraState); /// Map from world space to screen space. - QPoint GetScreenPosition(int viewportId, const AZ::Vector3& worldTranslation); + AzFramework::ScreenPoint GetScreenPosition(int viewportId, const AZ::Vector3& worldTranslation); /// Given a mouse interaction, determine if the pick ray from its position /// in screen space intersected an aabb in world space. diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index ec22a2f7c8..9388f3f5f0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -316,14 +316,14 @@ namespace AzToolsFramework template static void BoxSelectAddRemoveToEntitySelection( - const AZStd::optional& boxSelect, const QPoint& screenPosition, const AZ::EntityId visibleEntityId, + const AZStd::optional& boxSelect, const AzFramework::ScreenPoint& screenPosition, const AZ::EntityId visibleEntityId, const EntityIdContainer& incomingEntityIds, EntityIdContainer& outgoingEntityIds, EditorTransformComponentSelection& entityTransformComponentSelection, EntitySelectFuncType selectFunc1, EntitySelectFuncType selectFunc2, Compare outgoingCheck) { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::AzToolsFramework); - if (boxSelect->contains(screenPosition)) + if (boxSelect->contains(ViewportInteraction::QPointFromScreenPoint(screenPosition))) { const auto entityIt = incomingEntityIds.find(visibleEntityId); @@ -389,7 +389,7 @@ namespace AzToolsFramework const AZ::EntityId entityId = entityDataCache.GetVisibleEntityId(entityCacheIndex); const AZ::Vector3& entityPosition = entityDataCache.GetVisibleEntityPosition(entityCacheIndex); - const QPoint screenPosition = GetScreenPosition(viewportId, entityPosition); + const AzFramework::ScreenPoint screenPosition = GetScreenPosition(viewportId, entityPosition); if (currentKeyboardModifiers.Ctrl()) { @@ -927,7 +927,7 @@ namespace AzToolsFramework ViewportInteraction::MainEditorViewportInteractionRequestBus::EventResult( worldSurfacePosition, viewportId, &ViewportInteraction::MainEditorViewportInteractionRequestBus::Events::PickTerrain, - ViewportInteraction::QPointFromScreenPoint(mouseInteraction.m_mousePick.m_screenCoordinates)); + mouseInteraction.m_mousePick.m_screenCoordinates); // convert to local space - snap if enabled const GridSnapParameters gridSnapParams = GridSnapSettings(viewportId); diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 3c42b2db32..29b37e7d92 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -321,8 +321,8 @@ AzToolsFramework::ViewportInteraction::MousePick EditorViewportWidget::BuildMous using namespace AzToolsFramework::ViewportInteraction; MousePick mousePick; - mousePick.m_screenCoordinates = AzFramework::ScreenPoint(point.x(), point.y()); - const auto& ray = m_renderViewport->ViewportScreenToWorldRay(point); + mousePick.m_screenCoordinates = ScreenPointFromQPoint(point); + const auto& ray = m_renderViewport->ViewportScreenToWorldRay(mousePick.m_screenCoordinates); if (ray.has_value()) { mousePick.m_rayOrigin = ray.value().origin; @@ -1132,14 +1132,14 @@ float EditorViewportWidget::AngleStep() return GetViewManager()->GetGrid()->GetAngleSnap(); } -AZ::Vector3 EditorViewportWidget::PickTerrain(const QPoint& point) +AZ::Vector3 EditorViewportWidget::PickTerrain(const AzFramework::ScreenPoint& point) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - return LYVec3ToAZVec3(ViewToWorld(point, nullptr, true)); + return LYVec3ToAZVec3(ViewToWorld(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), nullptr, true)); } -AZ::EntityId EditorViewportWidget::PickEntity(const QPoint& point) +AZ::EntityId EditorViewportWidget::PickEntity(const AzFramework::ScreenPoint& point) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); @@ -1148,7 +1148,7 @@ AZ::EntityId EditorViewportWidget::PickEntity(const QPoint& point) AZ::EntityId entityId; HitContext hitInfo; hitInfo.view = this; - if (HitTest(point, hitInfo)) + if (HitTest(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), hitInfo)) { if (hitInfo.object && (hitInfo.object->GetType() == OBJTYPE_AZENTITY)) { @@ -1174,7 +1174,7 @@ void EditorViewportWidget::FindVisibleEntities(AZStd::vector& visi visibleEntitiesOut.assign(m_entityVisibilityQuery.Begin(), m_entityVisibilityQuery.End()); } -QPoint EditorViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) +AzFramework::ScreenPoint EditorViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { return m_renderViewport->ViewportWorldToScreen(worldPosition); } @@ -2002,7 +2002,7 @@ Vec3 EditorViewportWidget::WorldToView3D(const Vec3& wp, [[maybe_unused]] int nF ////////////////////////////////////////////////////////////////////////// QPoint EditorViewportWidget::WorldToView(const Vec3& wp) const { - return m_renderViewport->ViewportWorldToScreen(LYVec3ToAZVec3(wp)); + return AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(m_renderViewport->ViewportWorldToScreen(LYVec3ToAZVec3(wp))); } ////////////////////////////////////////////////////////////////////////// QPoint EditorViewportWidget::WorldToViewParticleEditor(const Vec3& wp, int width, int height) const @@ -2024,7 +2024,8 @@ QPoint EditorViewportWidget::WorldToViewParticleEditor(const Vec3& wp, int width } ////////////////////////////////////////////////////////////////////////// -Vec3 EditorViewportWidget::ViewToWorld(const QPoint& vp, bool* collideWithTerrain, bool onlyTerrain, bool bSkipVegetation, bool bTestRenderMesh, bool* collideWithObject) const +Vec3 EditorViewportWidget::ViewToWorld( + const QPoint& vp, bool* collideWithTerrain, bool onlyTerrain, bool bSkipVegetation, bool bTestRenderMesh, bool* collideWithObject) const { AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); @@ -2035,7 +2036,7 @@ Vec3 EditorViewportWidget::ViewToWorld(const QPoint& vp, bool* collideWithTerrai AZ_UNUSED(bSkipVegetation) AZ_UNUSED(collideWithObject) - auto ray = m_renderViewport->ViewportScreenToWorldRay(vp); + auto ray = m_renderViewport->ViewportScreenToWorldRay(AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(vp)); if (!ray.has_value()) { return Vec3(0, 0, 0); @@ -2152,7 +2153,7 @@ bool EditorViewportWidget::RayRenderMeshIntersection(IRenderMesh* pRenderMesh, c void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float sz, float* px, float* py, float* pz) const { AZ::Vector3 wp; - wp = m_renderViewport->ViewportScreenToWorld({(int)sx, m_rcClient.bottom() - ((int)sy)}, sz).value_or(wp); + wp = m_renderViewport->ViewportScreenToWorld(AzFramework::ScreenPoint{(int)sx, m_rcClient.bottom() - ((int)sy)}, sz).value_or(wp); *px = wp.GetX(); *py = wp.GetY(); *pz = wp.GetZ(); @@ -2160,9 +2161,9 @@ void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float sz, flo void EditorViewportWidget::ProjectToScreen(float ptx, float pty, float ptz, float* sx, float* sy, float* sz) const { - QPoint screenPosition = m_renderViewport->ViewportWorldToScreen(AZ::Vector3{ptx, pty, ptz}); - *sx = screenPosition.x(); - *sy = screenPosition.y(); + AzFramework::ScreenPoint screenPosition = m_renderViewport->ViewportWorldToScreen(AZ::Vector3{ptx, pty, ptz}); + *sx = screenPosition.m_x; + *sy = screenPosition.m_y; *sz = 0.f; } diff --git a/Code/Sandbox/Editor/EditorViewportWidget.h b/Code/Sandbox/Editor/EditorViewportWidget.h index 472f7e3c62..8673d258cc 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.h +++ b/Code/Sandbox/Editor/EditorViewportWidget.h @@ -196,15 +196,15 @@ public: bool ShowGrid(); bool AngleSnappingEnabled(); float AngleStep(); - QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition); // AzToolsFramework::ViewportFreezeRequestBus bool IsViewportInputFrozen() override; void FreezeViewportInput(bool freeze) override; // AzToolsFramework::MainEditorViewportInteractionRequestBus - AZ::EntityId PickEntity(const QPoint& point) override; - AZ::Vector3 PickTerrain(const QPoint& point) override; + AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) override; + AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) override; float TerrainHeight(const AZ::Vector2& position) override; void FindVisibleEntities(AZStd::vector& visibleEntitiesOut) override; bool ShowingWorldSpace() override; @@ -557,8 +557,7 @@ private: void PushDisableRendering(); void PopDisableRendering(); bool IsRenderingDisabled() const; - AzToolsFramework::ViewportInteraction::MousePick BuildMousePickInternal( - const QPoint& point) const; + AzToolsFramework::ViewportInteraction::MousePick BuildMousePickInternal(const QPoint& point) const; void RestoreViewportAfterGameMode(); void UpdateCameraFromViewportContext(); diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index cac1840b75..08eda98cf6 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -2043,14 +2043,14 @@ float CRenderViewport::AngleStep() return GetViewManager()->GetGrid()->GetAngleSnap(); } -AZ::Vector3 CRenderViewport::PickTerrain(const QPoint& point) +AZ::Vector3 CRenderViewport::PickTerrain(const AzFramework::ScreenPoint& point) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - return LYVec3ToAZVec3(ViewToWorld(point, nullptr, true)); + return LYVec3ToAZVec3(ViewToWorld(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), nullptr, true)); } -AZ::EntityId CRenderViewport::PickEntity(const QPoint& point) +AZ::EntityId CRenderViewport::PickEntity(const AzFramework::ScreenPoint& point) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); @@ -2059,7 +2059,7 @@ AZ::EntityId CRenderViewport::PickEntity(const QPoint& point) AZ::EntityId entityId; HitContext hitInfo; hitInfo.view = this; - if (HitTest(point, hitInfo)) + if (HitTest(AzToolsFramework::ViewportInteraction::QPointFromScreenPoint(point), hitInfo)) { if (hitInfo.object && (hitInfo.object->GetType() == OBJTYPE_AZENTITY)) { @@ -2100,12 +2100,13 @@ void CRenderViewport::FindVisibleEntities(AZStd::vector& visibleEn } } -QPoint CRenderViewport::ViewportWorldToScreen(const AZ::Vector3& worldPosition) +AzFramework::ScreenPoint CRenderViewport::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); PreWidgetRendering(); - const QPoint screenPosition = WorldToView(AZVec3ToLYVec3(worldPosition)); + const AzFramework::ScreenPoint screenPosition = + AzToolsFramework::ViewportInteraction::ScreenPointFromQPoint(WorldToView(AZVec3ToLYVec3(worldPosition))); PostWidgetRendering(); return screenPosition; diff --git a/Code/Sandbox/Editor/RenderViewport.h b/Code/Sandbox/Editor/RenderViewport.h index 2edbd86770..9985408d25 100644 --- a/Code/Sandbox/Editor/RenderViewport.h +++ b/Code/Sandbox/Editor/RenderViewport.h @@ -190,17 +190,24 @@ public: bool ShowGrid() override; bool AngleSnappingEnabled() override; float AngleStep() override; - QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; - AZStd::optional ViewportScreenToWorld(const QPoint&, float) override { return {}; } - AZStd::optional ViewportScreenToWorldRay(const QPoint&) override { return {}; } + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; + AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint&, float) override + { + return {}; + } + AZStd::optional ViewportScreenToWorldRay( + const AzFramework::ScreenPoint&) override + { + return {}; + } // AzToolsFramework::ViewportFreezeRequestBus bool IsViewportInputFrozen() override; void FreezeViewportInput(bool freeze) override; // AzToolsFramework::MainEditorViewportInteractionRequestBus - AZ::EntityId PickEntity(const QPoint& point) override; - AZ::Vector3 PickTerrain(const QPoint& point) override; + AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) override; + AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) override; float TerrainHeight(const AZ::Vector2& position) override; void FindVisibleEntities(AZStd::vector& visibleEntitiesOut) override; bool ShowingWorldSpace() override; diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.cpp b/Code/Sandbox/Editor/ViewportManipulatorController.cpp index fc376b27d0..43d2fb1f2c 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.cpp +++ b/Code/Sandbox/Editor/ViewportManipulatorController.cpp @@ -112,8 +112,7 @@ bool ViewportManipulatorControllerInstance::HandleInputChannelEvent(const AzFram m_state.m_mousePick.m_screenCoordinates = screenPosition; AZStd::optional ray; ViewportInteractionRequestBus::EventResult( - ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, - QPoint(screenPosition.m_x, screenPosition.m_y)); + ray, GetViewportId(), &ViewportInteractionRequestBus::Events::ViewportScreenToWorldRay, screenPosition); if (ray.has_value()) { diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h index 5dbbf04f1b..8e64c1467e 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -94,9 +94,10 @@ namespace AtomToolsFramework bool ShowGrid() override; bool AngleSnappingEnabled() override; float AngleStep() override; - QPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; - AZStd::optional ViewportScreenToWorld(const QPoint& screenPosition, float depth) override; - AZStd::optional ViewportScreenToWorldRay(const QPoint& screenPosition) override; + AzFramework::ScreenPoint ViewportWorldToScreen(const AZ::Vector3& worldPosition) override; + AZStd::optional ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) override; + AZStd::optional ViewportScreenToWorldRay( + const AzFramework::ScreenPoint& screenPosition) override; // AzToolsFramework::ViewportInteraction::ViewportMouseCursorRequestBus::Handler ... void BeginCursorCapture() override; diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index 483b4bc55b..5f3c553601 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -407,44 +407,43 @@ namespace AtomToolsFramework return 0.0f; } - QPoint RenderViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) + AzFramework::ScreenPoint RenderViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { - AZ::RPI::ViewPtr currentView = m_viewportContext->GetDefaultView(); - if (currentView == nullptr) + if (AZ::RPI::ViewPtr currentView = m_viewportContext->GetDefaultView(); + currentView == nullptr) { - return QPoint(); + return AzFramework::ScreenPoint(0, 0); } - AzFramework::ScreenPoint position = AzFramework::WorldToScreen( - worldPosition, - GetCameraState() - ); - return {position.m_x, position.m_y}; + + return AzFramework::WorldToScreen(worldPosition, GetCameraState()); } - AZStd::optional RenderViewportWidget::ViewportScreenToWorld(const QPoint& screenPosition, float depth) + AZStd::optional RenderViewportWidget::ViewportScreenToWorld(const AzFramework::ScreenPoint& screenPosition, float depth) { const auto& cameraProjection = m_viewportContext->GetCameraProjectionMatrix(); const auto& cameraView = m_viewportContext->GetCameraViewMatrix(); const AZ::Vector4 normalizedScreenPosition { - screenPosition.x() * 2.f / width() - 1.0f, - (height() - screenPosition.y()) * 2.f / height() - 1.0f, + screenPosition.m_x * 2.f / width() - 1.0f, + (height() - screenPosition.m_y) * 2.f / height() - 1.0f, 1.f - depth, // [GFX TODO] [ATOM-1501] Currently we always assume reverse depth 1.f }; + AZ::Matrix4x4 worldFromScreen = cameraProjection * cameraView; worldFromScreen.InvertFull(); - AZ::Vector4 projectedPosition = worldFromScreen * normalizedScreenPosition; - if (projectedPosition.GetW() == 0.f) + const AZ::Vector4 projectedPosition = worldFromScreen * normalizedScreenPosition; + if (projectedPosition.GetW() == 0.0f) { return {}; } + return projectedPosition.GetAsVector3() / projectedPosition.GetW(); } AZStd::optional RenderViewportWidget::ViewportScreenToWorldRay( - const QPoint& screenPosition) + const AzFramework::ScreenPoint& screenPosition) { auto pos0 = ViewportScreenToWorld(screenPosition, 0.f); auto pos1 = ViewportScreenToWorld(screenPosition, 1.f); @@ -457,6 +456,7 @@ namespace AtomToolsFramework AZ::Vector3 rayOrigin = pos0.value(); AZ::Vector3 rayDirection = pos1.value() - pos0.value(); rayDirection.Normalize(); + return AzToolsFramework::ViewportInteraction::ProjectedViewportRay{rayOrigin, rayDirection}; } From bb76bccc06249d2bb9db6863335d0ffdc81f1f73 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 17:55:09 +0100 Subject: [PATCH 11/49] remove unneeded temporary --- .../AzManipulatorTestFramework/Source/ViewportInteraction.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp index 4ab36e58f5..ebef9dea30 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ViewportInteraction.cpp @@ -68,8 +68,7 @@ namespace AzManipulatorTestFramework AzFramework::ScreenPoint ViewportInteraction::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { - auto pos = AzFramework::WorldToScreen(worldPosition, m_cameraState); - return AzFramework::ScreenPoint(pos.m_x, pos.m_y); + return AzFramework::WorldToScreen(worldPosition, m_cameraState); } void ViewportInteraction::SetCameraState(const AzFramework::CameraState& cameraState) From 524652ee177e1f241f988fb98fcb8f4a3da0e604 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Tue, 4 May 2021 18:01:34 +0100 Subject: [PATCH 12/49] fixed C18243589_Joints_BallSoftLimitsConstrained test failure --- ...243589_Joints_BallSoftLimitsConstrained.py | 35 ++++++++++++++++--- .../Gem/PythonTests/physics/JointsHelper.py | 7 ++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py index e038b33043..b7bc8439e4 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py @@ -57,6 +57,7 @@ def C18243589_Joints_BallSoftLimitsConstrained(): """ import os import sys + import math import ImportPathHelper as imports @@ -95,13 +96,38 @@ def C18243589_Joints_BallSoftLimitsConstrained(): Report.info_vector3(follower.position, "follower initial position:") leadInitialPosition = lead.position followerInitialPosition = follower.position + + followerMovedAboveJoint = False + #calculate the start vector from follower and lead positions + normalizedStartPos = JointsHelper.getRelativeVector(lead.position, follower.position) + normalizedStartPos = normalizedStartPos.GetNormalizedSafe() + #the targeted angle to reach between the initial vector and the current follower-lead vector + targetAngleDeg = 45 + targetAngle = math.radians(targetAngleDeg) - # 4) Wait for several seconds - general.idle_wait(1.0) # wait for lead and follower to move + maxTotalWaitTime = 2.0 #seconds + waitTime = 0.0 + waitStep = 0.2 + angleAchieved = 0.0 + while waitTime < maxTotalWaitTime: + waitTime = waitTime + waitStep + general.idle_wait(waitStep) # wait for lead and follower to move + + #calculate the current follower-lead vector + normalVec = JointsHelper.getRelativeVector(lead.position, follower.position) + normalVec = normalVec.GetNormalizedSafe() + #dot product + acos to get the angle + angleAchieved = math.acos(normalizedStartPos.Dot(normalVec)) + #is it above target? + if angleAchieved > targetAngle: + followerMovedAboveJoint = True + break # 5) Check to see if lead and follower behaved as expected - Report.info_vector3(lead.position, "lead position after 1 second:") - Report.info_vector3(follower.position, "follower position after 1 second:") + Report.info_vector3(lead.position, "lead position after {:.2f} second:".format(waitTime)) + Report.info_vector3(follower.position, "follower position after {:.2f} second:".format(waitTime)) + angleAchievedDeg = math.degrees(angleAchieved) + Report.info("Angle achieved {:.2f} Target {:.2f}".format(angleAchievedDeg, targetAngleDeg)) leadPositionDelta = lead.position.Subtract(leadInitialPosition) leadRemainedStill = JointsHelper.vector3SmallerThanScalar(leadPositionDelta, FLOAT_EPSILON) @@ -111,7 +137,6 @@ def C18243589_Joints_BallSoftLimitsConstrained(): followerMovedinXYZ = JointsHelper.vector3LargerThanScalar(followerPositionDelta, FLOAT_EPSILON) Report.critical_result(Tests.check_follower_position, followerMovedinXYZ) - followerMovedAboveJoint = follower.position.z > (followerInitialPosition.z + 2.5) # (followerInitialPosition.z + 2.5) is the z position past the 45 degree limit. This is to show that the follower swinged past the 45 degree cone limit, above the joint position. Report.critical_result(Tests.check_follower_above_joint, followerMovedAboveJoint) # 6) Exit Game Mode diff --git a/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py b/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py index e61118ef5b..476c1df237 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py +++ b/AutomatedTesting/Gem/PythonTests/physics/JointsHelper.py @@ -27,6 +27,13 @@ def vector3LargerThanScalar(vec3Value, scalarValue): vec3Value.y > scalarValue and vec3Value.z > scalarValue) +def getRelativeVector(vecA, vecB): + relativeVec = vecA + relativeVec.x = relativeVec.x - vecB.x + relativeVec.y = relativeVec.y - vecB.y + relativeVec.z = relativeVec.z - vecB.z + return relativeVec + # Entity class for joints tests class JointEntity: From 937d0ac726f43733b4018390d7479787055e5f72 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Tue, 4 May 2021 19:11:40 +0100 Subject: [PATCH 13/49] bump inter-test timeout by 1 sec for C5932042_PhysXForceRegion_LinearDamping --- .../physics/C5932042_PhysXForceRegion_LinearDamping.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py b/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py index 04cecd45b2..21d386954d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C5932042_PhysXForceRegion_LinearDamping.py @@ -135,7 +135,7 @@ def C5932042_PhysXForceRegion_LinearDamping(): # Constants CLOSE_ENOUGH = 0.001 - TIME_OUT = 2.0 + TIME_OUT = 3.0 INITIAL_VELOCITY = azmath.Vector3(0.0, 0.0, -10.0) # 1) Open level / Enter game mode From 593528532ff13f4050e15dce3bf23d4d06c0f626 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Tue, 4 May 2021 14:36:48 -0500 Subject: [PATCH 14/49] Move g_mainViewportEntityDebugDisplayId from AzToolsFramework to AzFramework and rename it to g_defaultSceneEntityDebugDisplayId --- .../AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h | 2 ++ .../AzToolsFramework/Viewport/ViewportTypes.cpp | 2 -- .../AzToolsFramework/Viewport/ViewportTypes.h | 4 ---- Code/Sandbox/Editor/RenderViewport.cpp | 6 +++--- .../Objects/ComponentEntityObject.cpp | 2 +- .../ComponentEntityEditorPlugin/SandboxIntegration.cpp | 2 +- 6 files changed, 7 insertions(+), 11 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h index f84f0276e1..776c7893ca 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h @@ -34,6 +34,8 @@ class ITexture; namespace AzFramework { + static constexpr const AZ::s32 g_defaultSceneEntityDebugDisplayId = AZ_CRC_CE("MainViewportEntityDebugDisplayId"); // default id to draw to all viewports in the default scene + /// DebugDisplayRequests provides a debug draw api to be used by components and viewport features. class DebugDisplayRequests : public AZ::EBusTraits diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp index 12a0d6a8ab..8d26054562 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.cpp @@ -19,8 +19,6 @@ namespace AzToolsFramework { namespace ViewportInteraction { - const AZ::s32 g_mainViewportEntityDebugDisplayId = AZ_CRC("MainViewportEntityDebugDisplayId", 0x58ae7fe8); - void ViewportInteractionReflect(AZ::ReflectContext* context) { if (auto serializeContext = azrtti_cast(context)) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h index 161ca2d79f..d59044e68f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportTypes.h @@ -256,9 +256,5 @@ namespace AzToolsFramework /// Reflect all viewport related types. void ViewportInteractionReflect(AZ::ReflectContext* context); - - /// The Id the main DebugDisplayRequestBus will be connected on. - extern const AZ::s32 g_mainViewportEntityDebugDisplayId; - } // namespace ViewportInteraction } // namespace AzToolsFramework diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index cac1840b75..29386a46b4 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -1105,7 +1105,7 @@ void CRenderViewport::Update() AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); AzFramework::DebugDisplayRequests* debugDisplay = @@ -1535,7 +1535,7 @@ void CRenderViewport::OnRender() AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); AzFramework::DebugDisplayRequests* debugDisplay = @@ -1681,7 +1681,7 @@ void CRenderViewport::RenderAll() AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); AzFramework::DebugDisplayRequests* debugDisplay = diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp index 8f695c39ab..2357ba8561 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp @@ -907,7 +907,7 @@ void CComponentEntityObject::Display(DisplayContext& dc) AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus; AzFramework::DebugDisplayRequestBus::Bind( - debugDisplayBus, AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId); AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus."); AzFramework::DebugDisplayRequests* debugDisplay = diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index ecfb155d79..79d5fadf6c 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -167,7 +167,7 @@ void SandboxIntegrationManager::Setup() { m_debugDisplayBusImplementationActive = true; AzFramework::DebugDisplayRequestBus::Handler::BusConnect( - AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); + AzFramework::g_defaultSceneEntityDebugDisplayId); } AzFramework::DisplayContextRequestBus::Handler::BusConnect(); From 9e105fb7694b4fb8722b3a826919e409baab939f Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Tue, 4 May 2021 16:52:36 -0500 Subject: [PATCH 15/49] [LYN-3347] Removed some unused references to CSelectionGroup. --- Code/Sandbox/Editor/CryEdit.cpp | 54 -------------------- Code/Sandbox/Editor/CryEdit.h | 1 - Code/Sandbox/Editor/Export/ExportManager.cpp | 35 +------------ Code/Sandbox/Editor/Export/ExportManager.h | 4 -- Code/Sandbox/Editor/Grid.cpp | 21 -------- Code/Sandbox/Editor/GridSettingsDialog.cpp | 35 ------------- Code/Sandbox/Editor/GridSettingsDialog.h | 2 - Code/Sandbox/Editor/IEditorImpl.cpp | 23 --------- Code/Sandbox/Editor/MainWindow.cpp | 3 -- Code/Sandbox/Editor/RenderViewport.cpp | 17 ------ Code/Sandbox/Editor/Resource.h | 1 - 11 files changed, 1 insertion(+), 195 deletions(-) diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index abffd1f995..aa255e185d 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -451,7 +451,6 @@ void CCryEditApp::RegisterActionHandlers() #endif ON_COMMAND(ID_DISPLAY_GOTOPOSITION, OnDisplayGotoPosition) ON_COMMAND(ID_SNAPANGLE, OnSnapangle) - ON_COMMAND(ID_EDIT_RENAMEOBJECT, OnEditRenameobject) ON_COMMAND(ID_CHANGEMOVESPEED_INCREASE, OnChangemovespeedIncrease) ON_COMMAND(ID_CHANGEMOVESPEED_DECREASE, OnChangemovespeedDecrease) ON_COMMAND(ID_CHANGEMOVESPEED_CHANGESTEP, OnChangemovespeedChangestep) @@ -3824,59 +3823,6 @@ void CCryEditApp::OnUpdateSnapangle(QAction* action) action->setChecked(gSettings.pGrid->IsAngleSnapEnabled()); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnEditRenameobject() -{ - CSelectionGroup* pSelection = GetIEditor()->GetSelection(); - if (pSelection->IsEmpty()) - { - QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("No Selected Objects!")); - return; - } - - IObjectManager* pObjMan = GetIEditor()->GetObjectManager(); - - if (!pObjMan) - { - return; - } - - StringDlg dlg(QObject::tr("Rename Object(s)")); - if (dlg.exec() == QDialog::Accepted) - { - CUndo undo("Rename Objects"); - QString newName; - QString str = dlg.GetString(); - int num = 0; - - for (int i = 0; i < pSelection->GetCount(); ++i) - { - CBaseObject* pObject = pSelection->GetObject(i); - - if (pObject) - { - if (pObjMan->IsDuplicateObjectName(str)) - { - pObjMan->ShowDuplicationMsgWarning(pObject, str, true); - return; - } - } - } - - for (int i = 0; i < pSelection->GetCount(); ++i) - { - newName = QStringLiteral("%1%2").arg(str).arg(num); - ++num; - CBaseObject* pObject = pSelection->GetObject(i); - - if (pObject) - { - pObjMan->ChangeObjectName(pObject, newName); - } - } - } -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnChangemovespeedIncrease() { diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index bce7f0c90d..6faa167146 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -413,7 +413,6 @@ private: void OnDisplayGotoPosition(); void OnSnapangle(); void OnUpdateSnapangle(QAction* action); - void OnEditRenameobject(); void OnChangemovespeedIncrease(); void OnChangemovespeedDecrease(); void OnChangemovespeedChangestep(); diff --git a/Code/Sandbox/Editor/Export/ExportManager.cpp b/Code/Sandbox/Editor/Export/ExportManager.cpp index 638977b191..ddb8a38870 100644 --- a/Code/Sandbox/Editor/Export/ExportManager.cpp +++ b/Code/Sandbox/Editor/Export/ExportManager.cpp @@ -1091,35 +1091,6 @@ bool CExportManager::AddSelectedEntityObjects() return true; } - -bool CExportManager::AddSelectedObjects() -{ - CSelectionGroup* pSelection = GetIEditor()->GetSelection(); - - int numObjects = pSelection->GetCount(); - if (numObjects > m_data.m_objects.size()) - { - m_data.m_objects.reserve(numObjects + 1); // +1 for terrain - } - // First run pipeline to precache geometry - m_isPrecaching = true; - for (int i = 0; i < numObjects; i++) - { - AddObject(pSelection->GetObject(i)); - } - - GetIEditor()->Get3DEngine()->ProposeContentPrecache(); - - // Repeat pipeline to collect geometry - m_isPrecaching = false; - for (int i = 0; i < numObjects; i++) - { - AddObject(pSelection->GetObject(i)); - } - - return true; -} - bool CExportManager::AddSelectedRegionObjects() { AABB box; @@ -1185,7 +1156,7 @@ bool CExportManager::ExportToFile(const char* filename, bool bClearDataAfterExpo } -bool CExportManager::Export(const char* defaultName, const char* defaultExt, const char* defaultPath, bool isSelectedObjects, bool isSelectedRegionObjects, bool isOccluder, bool bAnimationExport) +bool CExportManager::Export(const char* defaultName, const char* defaultExt, const char* defaultPath, [[maybe_unused]] bool isSelectedObjects, bool isSelectedRegionObjects, bool isOccluder, bool bAnimationExport) { m_bAnimationExport = bAnimationExport; @@ -1229,10 +1200,6 @@ bool CExportManager::Export(const char* defaultName, const char* defaultExt, con if (m_bAnimationExport || CFileUtil::SelectSaveFile(filters, defaultExt, defaultPath, newFilename)) { WaitCursor wait; - if (isSelectedObjects) - { - AddSelectedObjects(); - } if (isSelectedRegionObjects) { AddSelectedRegionObjects(); diff --git a/Code/Sandbox/Editor/Export/ExportManager.h b/Code/Sandbox/Editor/Export/ExportManager.h index a27e54b085..04ee5f73ca 100644 --- a/Code/Sandbox/Editor/Export/ExportManager.h +++ b/Code/Sandbox/Editor/Export/ExportManager.h @@ -128,10 +128,6 @@ public: bool Export(const char* defaultName, const char* defaultExt = "", const char* defaultPath = "", bool isSelectedObjects = true, bool isSelectedRegionObjects = false, bool isOccluder = false, bool bAnimationExport = false); - //! Add to Export Data geometry from selected objects - //! return true if succeed, otherwise false - bool AddSelectedObjects(); - bool AddSelectedEntityObjects(); //! Add to Export Data geometry from objects inside selected region volume diff --git a/Code/Sandbox/Editor/Grid.cpp b/Code/Sandbox/Editor/Grid.cpp index aa9e980069..50702f8cb2 100644 --- a/Code/Sandbox/Editor/Grid.cpp +++ b/Code/Sandbox/Editor/Grid.cpp @@ -136,31 +136,10 @@ Matrix34 CGrid::GetMatrix() const Ang3 angles = Ang3(rotationAngles.x * gf_PI / 180.0, rotationAngles.y * gf_PI / 180.0, rotationAngles.z * gf_PI / 180.0); tm = Matrix33::CreateRotationXYZ(angles); - - if (gSettings.snap.bGridGetFromSelected) - { - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - tm = obj->GetWorldTM(); - tm.OrthonormalizeFast(); - tm.SetTranslation(Vec3(0, 0, 0)); - } - } } else if (GetIEditor()->GetReferenceCoordSys() == COORDS_LOCAL) { tm.SetIdentity(); - - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - tm = obj->GetWorldTM(); - tm.OrthonormalizeFast(); - tm.SetTranslation(Vec3(0, 0, 0)); - } } else { diff --git a/Code/Sandbox/Editor/GridSettingsDialog.cpp b/Code/Sandbox/Editor/GridSettingsDialog.cpp index b16dbe4197..ecabdc4e6a 100644 --- a/Code/Sandbox/Editor/GridSettingsDialog.cpp +++ b/Code/Sandbox/Editor/GridSettingsDialog.cpp @@ -39,8 +39,6 @@ CGridSettingsDialog::CGridSettingsDialog(QWidget* pParent /*=NULL*/) connect(ui->m_userDefined, &QCheckBox::clicked, this, &CGridSettingsDialog::OnBnUserDefined); connect(ui->m_getFromObject, &QCheckBox::clicked, this, &CGridSettingsDialog::OnBnGetFromObject); - connect(ui->m_getAnglesFromObject, &QPushButton::clicked, this, &CGridSettingsDialog::OnBnGetAngles); - connect(ui->m_getTranslationFromObject, &QPushButton::clicked, this, &CGridSettingsDialog::OnBnGetTranslation); auto doubleSpinBoxValueChanged = static_cast(&QDoubleSpinBox::valueChanged); @@ -115,39 +113,6 @@ void CGridSettingsDialog::OnBnGetFromObject() EnableGridPropertyControls(ui->m_userDefined->isChecked(), ui->m_getFromObject->isChecked()); } -void CGridSettingsDialog::OnBnGetAngles() -{ - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - Matrix34 tm = obj->GetWorldTM(); - AffineParts ap; - ap.SpectralDecompose(tm); - - Vec3 rotation = Vec3(RAD2DEG(Ang3::GetAnglesXYZ(Matrix33(ap.rot)))); - - ui->m_angleX->setValue(rotation.x); - ui->m_angleY->setValue(rotation.y); - ui->m_angleZ->setValue(rotation.z); - } -} - -void CGridSettingsDialog::OnBnGetTranslation() -{ - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - Matrix34 tm = obj->GetWorldTM(); - Vec3 translation = tm.GetTranslation(); - - ui->m_translationX->setValue(translation.x); - ui->m_translationY->setValue(translation.y); - ui->m_translationZ->setValue(translation.z); - } -} - void CGridSettingsDialog::EnableGridPropertyControls(const bool isUserDefined, const bool isGetFromObject) { ui->m_getFromObject->setEnabled(isUserDefined == true); diff --git a/Code/Sandbox/Editor/GridSettingsDialog.h b/Code/Sandbox/Editor/GridSettingsDialog.h index f82278ccb7..fe5934ec7e 100644 --- a/Code/Sandbox/Editor/GridSettingsDialog.h +++ b/Code/Sandbox/Editor/GridSettingsDialog.h @@ -51,8 +51,6 @@ private slots: void accept() override; void OnBnUserDefined(); void OnBnGetFromObject(); - void OnBnGetAngles(); - void OnBnGetTranslation(); void OnValueUpdate(); private: diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index 61d24db90c..ff9ece339a 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -116,29 +116,6 @@ static CCryEditDoc * theDocument; #undef GetCommandLine -namespace -{ - bool SelectionContainsComponentEntities() - { - bool result = false; - CSelectionGroup* pSelection = GetIEditor()->GetObjectManager()->GetSelection(); - if (pSelection) - { - CBaseObject* selectedObj = nullptr; - for (int selectionCounter = 0; selectionCounter < pSelection->GetCount(); ++selectionCounter) - { - selectedObj = pSelection->GetObject(selectionCounter); - if (selectedObj->GetType() == OBJTYPE_AZENTITY) - { - result = true; - break; - } - } - } - return result; - } -} - const char* CEditorImpl::m_crashLogFileName = "SessionStatus/editor_statuses.json"; CEditorImpl::CEditorImpl() diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index c266d37282..c54c31c5d5 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -884,9 +884,6 @@ void MainWindow::InitActions() .SetStatusTip(tr("Restore saved state (Fetch)")); // Modify actions - am->AddAction(ID_EDIT_RENAMEOBJECT, tr("Rename Object(s)...")) - .SetStatusTip(tr("Rename Object")); - am->AddAction(ID_EDITMODE_MOVE, tr("Move")) .SetIcon(Style::icon("Move")) .SetApplyHoverEffect() diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index 3e726f2468..24913a7388 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -3959,18 +3959,6 @@ void CRenderViewport::RenderConstructionPlane() Ang3 angles = Ang3(pGrid->rotationAngles.x * gf_PI / 180.0, pGrid->rotationAngles.y * gf_PI / 180.0, pGrid->rotationAngles.z * gf_PI / 180.0); Matrix34 tm = Matrix33::CreateRotationXYZ(angles); - if (gSettings.snap.bGridGetFromSelected) - { - CSelectionGroup* sel = GetIEditor()->GetSelection(); - if (sel->GetCount() > 0) - { - CBaseObject* obj = sel->GetObject(0); - tm = obj->GetWorldTM(); - tm.OrthonormalizeFast(); - tm.SetTranslation(Vec3(0, 0, 0)); - } - } - u = tm * u; v = tm * v; } @@ -4025,11 +4013,6 @@ void CRenderViewport::RenderConstructionPlane() void CRenderViewport::RenderSnappingGrid() { // First, Check whether we should draw the grid or not. - CSelectionGroup* pSelGroup = GetIEditor()->GetSelection(); - if (pSelGroup == nullptr || pSelGroup->GetCount() != 1) - { - return; - } CGrid* pGrid = GetViewManager()->GetGrid(); if (pGrid->IsEnabled() == false && pGrid->IsAngleSnapEnabled() == false) { diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index 51f9b1f3e9..d9fdb42c0b 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -91,7 +91,6 @@ #define ID_EXPORT_INDOORS 32915 #define ID_VIEW_CYCLE2DVIEWPORT 32916 #define ID_SNAPANGLE 32917 -#define ID_EDIT_RENAMEOBJECT 32925 #define ID_CHANGEMOVESPEED_INCREASE 32928 #define ID_CHANGEMOVESPEED_DECREASE 32929 #define ID_CHANGEMOVESPEED_CHANGESTEP 32930 From 27472169e2c915d33f202b8fdc3adedaad8c1281 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Tue, 4 May 2021 17:06:22 -0500 Subject: [PATCH 16/49] Change global default scene debug draw id variale declare from static constexpr const to inline constexpr --- .../AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h index 776c7893ca..fb6b8d7d72 100644 --- a/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h +++ b/Code/Framework/AzFramework/AzFramework/Entity/EntityDebugDisplayBus.h @@ -34,7 +34,7 @@ class ITexture; namespace AzFramework { - static constexpr const AZ::s32 g_defaultSceneEntityDebugDisplayId = AZ_CRC_CE("MainViewportEntityDebugDisplayId"); // default id to draw to all viewports in the default scene + inline constexpr AZ::s32 g_defaultSceneEntityDebugDisplayId = AZ_CRC_CE("MainViewportEntityDebugDisplayId"); // default id to draw to all viewports in the default scene /// DebugDisplayRequests provides a debug draw api to be used by components and viewport features. class DebugDisplayRequests From 71039186ab353f32638e2baaf4c3091220e66bfb Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Tue, 4 May 2021 15:18:48 -0700 Subject: [PATCH 17/49] Removed RayTracingSceneSrg files from the .cmake file --- .../Feature/Common/Assets/atom_feature_common_asset_files.cmake | 2 -- 1 file changed, 2 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake index f14fb4f4a0..84ef494216 100644 --- a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake +++ b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake @@ -280,8 +280,6 @@ set(FILES ShaderLib/Atom/Features/Shadow/Shadow.azsli ShaderLib/Atom/Features/Shadow/ShadowmapAtlasLib.azsli ShaderLib/Atom/Features/Vertex/VertexHelper.azsli - ShaderResourceGroups/RayTracingSceneSrg.azsli - ShaderResourceGroups/RayTracingSceneSrgAll.azsli ShaderResourceGroups/SceneSrg.azsli ShaderResourceGroups/SceneSrgAll.azsli ShaderResourceGroups/SceneTimeSrg.azsli From d4f19cb0b5ebbc06d701559b53823d4d9ecda353 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Tue, 4 May 2021 15:53:40 -0700 Subject: [PATCH 18/49] Fix Mac build --- 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 e06eadcbea..e564d64fc3 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -47,5 +47,5 @@ ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-mac TARGETS mik ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-mac TARGETS googletest PACKAGE_HASH cbf020d5ef976c5db8b6e894c6c63151ade85ed98e7c502729dd20172acae5a8) ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-mac TARGETS GoogleBenchmark PACKAGE_HASH ad25de0146769c91e179953d845de2bec8ed4a691f973f47e3eb37639381f665) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev1-mac TARGETS OpenSSL PACKAGE_HASH 28adc1c0616ac0482b2a9d7b4a3a3635a1020e87b163f8aba687c501cf35f96c) -ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-mac TARGETS Qt PACKAGE_HASH 29966f22ec253dc9904e88ad48fe6b6a669302b2dc7049f2e2bbd4949e79e595) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-mac TARGETS Qt PACKAGE_HASH 4723ac43b19d4633c3fa4b9642f27c992d30cdc689f769f82869786f1c22a728) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-mac TARGETS libsamplerate PACKAGE_HASH b912af40c0ac197af9c43d85004395ba92a6a859a24b7eacd920fed5854a97fe) From e414cc151d4f941edfd4917b367eef22840f3bf8 Mon Sep 17 00:00:00 2001 From: pereslav Date: Wed, 5 May 2021 00:00:06 +0100 Subject: [PATCH 19/49] SPEC-6590 Implemented network entities instantiation by network spawnable asset ID --- .../Spawnable/SpawnableEntitiesInterface.h | 6 + .../Spawnable/SpawnableEntitiesManager.cpp | 21 +++ .../Spawnable/SpawnableEntitiesManager.h | 6 + .../NetworkEntity/NetworkEntityManager.cpp | 138 ++++++++++-------- .../NetworkEntity/NetworkEntityManager.h | 7 +- .../NetworkEntity/NetworkSpawnableLibrary.cpp | 1 - .../Pipeline/NetworkPrefabProcessor.cpp | 5 +- 7 files changed, 121 insertions(+), 63 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h index ea19b3a0be..95d0b9e3a7 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesInterface.h @@ -148,6 +148,12 @@ namespace AzFramework //! Blocks until all operations made on the provided ticket before the barrier call have completed. virtual void Barrier(EntitySpawnTicket& ticket, BarrierCallback completionCallback) = 0; + //! Register a handler for OnSpawned events. + virtual void AddOnSpawnedHandler(AZ::Event>::Handler& handler) = 0; + + //! Register a handler for OnDespawned events. + virtual void AddOnDespawnedHandler(AZ::Event>::Handler& handler) = 0; + protected: [[nodiscard]] virtual void* CreateTicket(AZ::Data::Asset&& spawnable) = 0; virtual void DestroyTicket(void* ticket) = 0; diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp index 4e98616ef1..3ab004b516 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.cpp @@ -114,6 +114,16 @@ namespace AzFramework } } + void SpawnableEntitiesManager::AddOnSpawnedHandler(AZ::Event>::Handler& handler) + { + handler.Connect(m_onSpawnedEvent); + } + + void SpawnableEntitiesManager::AddOnDespawnedHandler(AZ::Event>::Handler& handler) + { + handler.Connect(m_onDespawnedEvent); + } + auto SpawnableEntitiesManager::ProcessQueue() -> CommandQueueStatus { AZStd::queue pendingRequestQueue; @@ -223,6 +233,8 @@ namespace AzFramework ticket.m_spawnedEntities.begin() + spawnedEntitiesCount, ticket.m_spawnedEntities.end())); } + m_onSpawnedEvent.Signal(ticket.m_spawnable); + ticket.m_currentTicketId++; return true; } @@ -257,6 +269,8 @@ namespace AzFramework ticket.m_spawnedEntities.begin() + spawnedEntitiesCount, ticket.m_spawnedEntities.end())); } + m_onSpawnedEvent.Signal(ticket.m_spawnable); + ticket.m_currentTicketId++; return true; } @@ -289,6 +303,8 @@ namespace AzFramework request.m_completionCallback(*request.m_ticket); } + m_onDespawnedEvent.Signal(ticket.m_spawnable); + ticket.m_currentTicketId++; return true; } @@ -315,6 +331,8 @@ namespace AzFramework &GameEntityContextRequestBus::Events::DestroyGameEntityAndDescendants, entity->GetId()); } } + + m_onDespawnedEvent.Signal(ticket.m_spawnable); // Rebuild the list of entities. ticket.m_spawnedEntities.clear(); @@ -350,6 +368,9 @@ namespace AzFramework } ticket.m_currentTicketId++; + + m_onSpawnedEvent.Signal(ticket.m_spawnable); + return true; } else diff --git a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h index 29e9ed797b..c70b9ccaa6 100644 --- a/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h +++ b/Code/Framework/AzFramework/AzFramework/Spawnable/SpawnableEntitiesManager.h @@ -60,6 +60,9 @@ namespace AzFramework void Barrier(EntitySpawnTicket& spawnInfo, BarrierCallback completionCallback) override; + void AddOnSpawnedHandler(AZ::Event>::Handler& handler) override; + void AddOnDespawnedHandler(AZ::Event>::Handler& handler) override; + // // The following function is thread safe but intended to be run from the main thread. // @@ -156,5 +159,8 @@ namespace AzFramework AZStd::deque m_delayedQueue; //!< Requests that were processed before, but couldn't be completed. AZStd::queue m_pendingRequestQueue; AZStd::mutex m_pendingRequestQueueMutex; + + AZ::Event> m_onSpawnedEvent; + AZ::Event> m_onDespawnedEvent; }; } // namespace AzFramework diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index d1701bbb89..3764b92b25 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -34,9 +35,14 @@ namespace Multiplayer : m_networkEntityAuthorityTracker(*this) , m_removeEntitiesEvent([this] { RemoveEntities(); }, AZ::Name("NetworkEntityManager remove entities event")) , m_updateEntityDomainEvent([this] { UpdateEntityDomain(); }, AZ::Name("NetworkEntityManager update entity domain event")) + , m_onSpawnedHandler([this](AZ::Data::Asset spawnable) { this->OnSpawned(spawnable); }) + , m_onDespawnedHandler([this](AZ::Data::Asset spawnable) { this->OnDespawned(spawnable); }) { AZ::Interface::Register(this); AzFramework::RootSpawnableNotificationBus::Handler::BusConnect(); + + AzFramework::SpawnableEntitiesInterface::Get()->AddOnSpawnedHandler(m_onSpawnedHandler); + AzFramework::SpawnableEntitiesInterface::Get()->AddOnDespawnedHandler(m_onDespawnedHandler); } NetworkEntityManager::~NetworkEntityManager() @@ -365,58 +371,57 @@ namespace Multiplayer { INetworkEntityManager::EntityList returnList; - // TODO: Implement for non-root spawnables auto spawnableAssetId = m_networkPrefabLibrary.GetAssetIdByName(prefabEntryId.m_prefabName); - if (spawnableAssetId == m_rootSpawnableAsset.GetId()) + // Required for sync-instantiation. Todo: keep the reference in NetworkSpawnableLibrary + auto netSpawnableAsset = AZ::Data::AssetManager::Instance().GetAsset(spawnableAssetId, AZ::Data::AssetLoadBehavior::PreLoad); + AZ::Data::AssetManager::Instance().BlockUntilLoadComplete(netSpawnableAsset); + + AzFramework::Spawnable* netSpawnable = netSpawnableAsset.GetAs(); + if (!netSpawnable) { - AzFramework::Spawnable* netSpawnable = m_rootSpawnableAsset.GetAs(); - if (!netSpawnable) + return returnList; + } + + const uint32_t entityIndex = prefabEntryId.m_entityOffset; + + if (entityIndex == PrefabEntityId::AllIndices) + { + return CreateEntitiesImmediate(*netSpawnable, netEntityRole); + } + + const AzFramework::Spawnable::EntityList& entities = netSpawnable->GetEntities(); + size_t entitiesSize = entities.size(); + if (entityIndex >= entitiesSize) + { + return returnList; + } + + AZ::SerializeContext* serializeContext = nullptr; + AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); + + AZ::Entity* clone = serializeContext->CloneObject(entities[entityIndex].get()); + AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); + clone->SetId(AZ::Entity::MakeId()); + + NetBindComponent* netBindComponent = clone->FindComponent(); + if (netBindComponent) + { + netBindComponent->PreInit(clone, prefabEntryId, netEntityId, netEntityRole); + + auto* transformComponent = clone->FindComponent(); + if (transformComponent) { - return returnList; + transformComponent->SetWorldTM(transform); } - const uint32_t entityIndex = prefabEntryId.m_entityOffset; - - if (entityIndex == PrefabEntityId::AllIndices) + if (autoActivate == AutoActivate::DoNotActivate) { - return CreateEntitiesImmediate(*netSpawnable, netEntityRole); + clone->SetRuntimeActiveByDefault(false); } - const AzFramework::Spawnable::EntityList& entities = netSpawnable->GetEntities(); - size_t entitiesSize = entities.size(); - if (entityIndex >= entitiesSize) - { - return returnList; - } + AzFramework::GameEntityContextRequestBus::Broadcast(&AzFramework::GameEntityContextRequestBus::Events::AddGameEntity, clone); - AZ::SerializeContext* serializeContext = nullptr; - AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); - - AZ::Entity* clone = serializeContext->CloneObject(entities[entityIndex].get()); - AZ_Assert(clone != nullptr, "Failed to clone spawnable entity."); - clone->SetId(AZ::Entity::MakeId()); - - NetBindComponent* netBindComponent = clone->FindComponent(); - if (netBindComponent) - { - netBindComponent->PreInit(clone, prefabEntryId, netEntityId, netEntityRole); - - auto* transformComponent = clone->FindComponent(); - if (transformComponent) - { - transformComponent->SetWorldTM(transform); - } - - if (autoActivate == AutoActivate::DoNotActivate) - { - clone->SetRuntimeActiveByDefault(false); - } - - AzFramework::GameEntityContextRequestBus::Broadcast( - &AzFramework::GameEntityContextRequestBus::Events::AddGameEntity, clone); - - returnList.push_back(netBindComponent->GetEntityHandle()); - } + returnList.push_back(netBindComponent->GetEntityHandle()); } return returnList; @@ -429,13 +434,37 @@ namespace Multiplayer } void NetworkEntityManager::OnRootSpawnableAssigned( - AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) + [[maybe_unused]] AZ::Data::Asset rootSpawnable, [[maybe_unused]] uint32_t generation) { - AzFramework::Spawnable* rootSpawnableData = rootSpawnable.GetAs(); - const auto& entityList = rootSpawnableData->GetEntities(); + auto* multiplayer = AZ::Interface::Get(); + const auto agentType = multiplayer->GetAgentType(); + + if (agentType == MultiplayerAgentType::Client) + { + multiplayer->SendReadyForEntityUpdates(true); + } + } + + void NetworkEntityManager::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation) + { + // TODO: Do we need to clear all entities here? + auto* multiplayer = AZ::Interface::Get(); + const auto agentType = multiplayer->GetAgentType(); + + if (agentType == MultiplayerAgentType::Client) + { + multiplayer->SendReadyForEntityUpdates(false); + } + } + + void NetworkEntityManager::OnSpawned(AZ::Data::Asset spawnable) + { + AzFramework::Spawnable* spawnableData = spawnable.GetAs(); + const auto& entityList = spawnableData->GetEntities(); if (entityList.size() == 0) { - AZ_Error("NetworkEntityManager", false, "OnRootSpawnableAssigned: Root spawnable doesn't have any entities."); + AZ_Error("NetworkEntityManager", false, "OnSpawned: Spawnable %s doesn't have any entities.", + spawnable.GetHint().c_str()); return; } @@ -443,7 +472,7 @@ namespace Multiplayer auto* spawnableHolder = rootEntity->FindComponent(); if (!spawnableHolder) { - AZ_Error("NetworkEntityManager", false, "OnRootSpawnableAssigned: Root entity doesn't have NetworkSpawnableHolderComponent."); + // Root entity doesn't have NetworkSpawnableHolderComponent. It means there's no corresponding network spawnable. return; } @@ -465,8 +494,6 @@ namespace Multiplayer return; } - m_rootSpawnableAsset = netSpawnableAsset; - auto* multiplayer = AZ::Interface::Get(); const auto agentType = multiplayer->GetAgentType(); @@ -477,17 +504,10 @@ namespace Multiplayer { CreateEntitiesImmediate(*netSpawnable, NetEntityRole::Authority); } - else - { - // If we don't spawn net entities immediately (i.e. it is a client), - // tell the server/host it can start sending updates that will instantiate entities. - multiplayer->SendReadyForEntityUpdates(true); - } } - void NetworkEntityManager::OnRootSpawnableReleased([[maybe_unused]] uint32_t generation) + void NetworkEntityManager::OnDespawned([[maybe_unused]]AZ::Data::Asset spawnable) { - // TODO: Do we need to clear all entities here? - m_rootSpawnableAsset.Release(); + // TODO: Remove entities instantiated from the spawnable } } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h index 142730188b..4439503373 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.h @@ -84,6 +84,9 @@ namespace Multiplayer NetEntityId NextId(); + void OnSpawned(AZ::Data::Asset spawnable); + void OnDespawned(AZ::Data::Asset spawnable); + NetworkEntityTracker m_networkEntityTracker; NetworkEntityAuthorityTracker m_networkEntityAuthorityTracker; MultiplayerComponentRegistry m_multiplayerComponentRegistry; @@ -111,6 +114,8 @@ namespace Multiplayer DeferredRpcMessages m_localDeferredRpcMessages; NetworkSpawnableLibrary m_networkPrefabLibrary; - AZ::Data::Asset m_rootSpawnableAsset; + + AZ::Event>::Handler m_onSpawnedHandler; + AZ::Event>::Handler m_onDespawnedHandler; }; } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkSpawnableLibrary.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkSpawnableLibrary.cpp index ad2e18e222..ebf5d2609b 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkSpawnableLibrary.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkSpawnableLibrary.cpp @@ -46,7 +46,6 @@ namespace Multiplayer const AZ::Name name = AZ::Name(relativePath); m_spawnables[name] = id; m_spawnablesReverseLookup[id] = name; - } void NetworkSpawnableLibrary::OnCatalogLoaded([[maybe_unused]] const char* catalogFile) diff --git a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp index 2006272135..4962d16fb4 100644 --- a/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp +++ b/Gems/Multiplayer/Code/Source/Pipeline/NetworkPrefabProcessor.cpp @@ -104,9 +104,10 @@ namespace Multiplayer networkedEntityIds.push_back(sourceEntity->GetId()); } } - if (!PrefabDomUtils::StoreInstanceInPrefabDom(*sourceInstance, prefab)) + + if (networkedEntityIds.empty()) { - AZ_Error("NetworkPrefabProcessor", false, "Saving exported Prefab Instance within a Prefab Dom failed."); + // No networked entities in the prefab, no need to do anything in this processor. return; } From ceb7ac333a1e58941606dc401fded753522662ff Mon Sep 17 00:00:00 2001 From: balibhan Date: Wed, 5 May 2021 12:31:43 +0530 Subject: [PATCH 20/49] removed debug print --- .../scripting/OnEntityActivatedDeactivated_PrintMessage.py | 1 - 1 file changed, 1 deletion(-) diff --git a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py index cea1230348..51b63c4268 100644 --- a/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py +++ b/AutomatedTesting/Gem/PythonTests/scripting/OnEntityActivatedDeactivated_PrintMessage.py @@ -145,7 +145,6 @@ def OnEntityActivatedDeactivated_PrintMessage(): def locate_expected_lines(line_list: list): found_lines = [printInfo.message.strip() for printInfo in section_tracer.prints] - print(f"bhanu: {found_lines}") return all(line in found_lines for line in line_list) # 1) Create temp level From 24167e7c023671ba7ae2928d35c6e638c0353ff8 Mon Sep 17 00:00:00 2001 From: amzn-sean <75276488+amzn-sean@users.noreply.github.com> Date: Wed, 5 May 2021 12:36:47 +0100 Subject: [PATCH 21/49] address PR comments --- ...243589_Joints_BallSoftLimitsConstrained.py | 25 ++++++++----------- .../PythonTests/physics/TestSuite_Periodic.py | 6 +++-- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py index b7bc8439e4..16266b2da3 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C18243589_Joints_BallSoftLimitsConstrained.py @@ -102,32 +102,27 @@ def C18243589_Joints_BallSoftLimitsConstrained(): normalizedStartPos = JointsHelper.getRelativeVector(lead.position, follower.position) normalizedStartPos = normalizedStartPos.GetNormalizedSafe() #the targeted angle to reach between the initial vector and the current follower-lead vector - targetAngleDeg = 45 - targetAngle = math.radians(targetAngleDeg) - - maxTotalWaitTime = 2.0 #seconds - waitTime = 0.0 - waitStep = 0.2 + TARGET_ANGLE_DEG = 45 + targetAngle = math.radians(TARGET_ANGLE_DEG) angleAchieved = 0.0 - while waitTime < maxTotalWaitTime: - waitTime = waitTime + waitStep - general.idle_wait(waitStep) # wait for lead and follower to move + def checkAngleMet(): #calculate the current follower-lead vector normalVec = JointsHelper.getRelativeVector(lead.position, follower.position) normalVec = normalVec.GetNormalizedSafe() #dot product + acos to get the angle angleAchieved = math.acos(normalizedStartPos.Dot(normalVec)) #is it above target? - if angleAchieved > targetAngle: - followerMovedAboveJoint = True - break + return angleAchieved > targetAngle + + MAX_WAIT_TIME = 2.0 #seconds + followerMovedAboveJoint = helper.wait_for_condition(checkAngleMet, MAX_WAIT_TIME) # 5) Check to see if lead and follower behaved as expected - Report.info_vector3(lead.position, "lead position after {:.2f} second:".format(waitTime)) - Report.info_vector3(follower.position, "follower position after {:.2f} second:".format(waitTime)) + Report.info_vector3(lead.position, "lead position:") + Report.info_vector3(follower.position, "follower position:") angleAchievedDeg = math.degrees(angleAchieved) - Report.info("Angle achieved {:.2f} Target {:.2f}".format(angleAchievedDeg, targetAngleDeg)) + Report.info(f"Angle achieved {angleAchievedDeg:.2f} Target {TARGET_ANGLE_DEG:.2f}") leadPositionDelta = lead.position.Subtract(leadInitialPosition) leadRemainedStill = JointsHelper.vector3SmallerThanScalar(leadPositionDelta, FLOAT_EPSILON) diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py index 4f91f539ee..93831e9658 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py @@ -254,6 +254,8 @@ class TestAutomation(TestAutomationBase): from . import C4044697_Material_PerfaceMaterialValidation as test_module self._run_test(request, workspace, editor, test_module) + @pytest.mark.xfail( + reason="This test will sometimes fail as the ball will continue to roll before the timeout is reached.") @revert_physics_config def test_C4976202_RigidBody_StopsWhenBelowKineticThreshold(self, request, workspace, editor, launcher_platform): from . import C4976202_RigidBody_StopsWhenBelowKineticThreshold as test_module @@ -468,12 +470,12 @@ class TestAutomation(TestAutomationBase): from . import C6090547_ForceRegion_ParentChildForceRegions as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config + @revert_physics_config def test_C19578021_ShapeCollider_CanBeAdded(self, request, workspace, editor, launcher_platform): from . import C19578021_ShapeCollider_CanBeAdded as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config + @revert_physics_config def test_C15425929_Undo_Redo(self, request, workspace, editor, launcher_platform): from . import C15425929_Undo_Redo as test_module self._run_test(request, workspace, editor, test_module) From 9e2975ba3cb81a819ddd06c7704a0ce09a8cdb0e Mon Sep 17 00:00:00 2001 From: pereslav Date: Wed, 5 May 2021 14:19:23 +0100 Subject: [PATCH 22/49] Fixed unit tests when Spawnable system component was missing --- Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp b/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp index c18c2ee5e3..2e0b9c0759 100644 --- a/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp +++ b/Gems/Multiplayer/Code/Tests/MultiplayerSystemTests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -28,6 +29,7 @@ namespace UnitTest { SetupAllocator(); AZ::NameDictionary::Create(); + m_spawnableComponent = new AzFramework::SpawnableSystemComponent(); m_mpComponent = new Multiplayer::MultiplayerSystemComponent(); m_initHandler = Multiplayer::SessionInitEvent::Handler([this](AzNetworking::INetworkInterface* value) { TestInitEvent(value); }); @@ -41,6 +43,7 @@ namespace UnitTest void TearDown() override { delete m_mpComponent; + delete m_spawnableComponent; AZ::NameDictionary::Destroy(); TeardownAllocator(); } @@ -69,6 +72,7 @@ namespace UnitTest Multiplayer::ConnectionAcquiredEvent::Handler m_connAcquiredHandler; Multiplayer::MultiplayerSystemComponent* m_mpComponent = nullptr; + AzFramework::SpawnableSystemComponent* m_spawnableComponent = nullptr; }; TEST_F(MultiplayerSystemTests, TestInitEvent) From f4bd72880e00b4eae6e56285bf9489aa74f2b95d Mon Sep 17 00:00:00 2001 From: pereslav Date: Wed, 5 May 2021 14:28:45 +0100 Subject: [PATCH 23/49] Fixed tabs --- .../Code/Source/NetworkEntity/NetworkEntityManager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 3764b92b25..ce55f66caa 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -372,7 +372,7 @@ namespace Multiplayer INetworkEntityManager::EntityList returnList; auto spawnableAssetId = m_networkPrefabLibrary.GetAssetIdByName(prefabEntryId.m_prefabName); - // Required for sync-instantiation. Todo: keep the reference in NetworkSpawnableLibrary + // Required for sync-instantiation. Todo: keep the reference in NetworkSpawnableLibrary auto netSpawnableAsset = AZ::Data::AssetManager::Instance().GetAsset(spawnableAssetId, AZ::Data::AssetLoadBehavior::PreLoad); AZ::Data::AssetManager::Instance().BlockUntilLoadComplete(netSpawnableAsset); @@ -508,6 +508,6 @@ namespace Multiplayer void NetworkEntityManager::OnDespawned([[maybe_unused]]AZ::Data::Asset spawnable) { - // TODO: Remove entities instantiated from the spawnable + // TODO: Remove entities instantiated from the spawnable } } From d7b796fd73a14e4951abeb1d18e5ed075e35e6e6 Mon Sep 17 00:00:00 2001 From: bosnichd Date: Wed, 5 May 2021 09:07:28 -0600 Subject: [PATCH 24/49] Remove I3DEngine CryCommon Interface (#567) Delete: - I3DEngine - Missions - Time of day - GameEffectsSystem Gem - ImageProcessing Gem - SVOGI Gem - Various other things that don't do anything now that the legacy renderer has been removed. --- Code/CryEngine/CryCommon/CryEngineDecalInfo.h | 77 - Code/CryEngine/CryCommon/Gem.h | 98 - Code/CryEngine/CryCommon/I3DEngine.h | 3021 ----------------- Code/CryEngine/CryCommon/I3DEngine_info.h | 53 - Code/CryEngine/CryCommon/IEntityRenderState.h | 1 - Code/CryEngine/CryCommon/ILocalMemoryUsage.h | 33 - Code/CryEngine/CryCommon/IMaterial.h | 3 +- Code/CryEngine/CryCommon/IMovieSystem.h | 1 - Code/CryEngine/CryCommon/IObjManager.h | 1 - Code/CryEngine/CryCommon/ISystem.h | 22 - Code/CryEngine/CryCommon/ITimeOfDay.h | 286 -- .../CryEngine/CryCommon/Mocks/I3DEngineMock.h | 528 --- .../CryEngine/CryCommon/Mocks/IRendererMock.h | 6 +- Code/CryEngine/CryCommon/Mocks/ISystemMock.h | 8 - Code/CryEngine/CryCommon/Mocks/StubTimer.h | 2 + Code/CryEngine/CryCommon/WindowsUtils.h | 215 -- .../CryEngine/CryCommon/crycommon_files.cmake | 7 - .../CryCommon/crycommon_testing_files.cmake | 1 - .../CrySystem/CrySystem_precompiled.h | 2 - .../CrySystem/LevelSystem/LevelSystem.cpp | 55 +- .../LevelSystem/SpawnableLevelSystem.cpp | 59 +- Code/CryEngine/CrySystem/PerfHUD.cpp | 55 - .../CrySystem/Statistics/LocalMemoryUsage.cpp | 1389 -------- .../CrySystem/Statistics/LocalMemoryUsage.h | 245 -- Code/CryEngine/CrySystem/System.cpp | 103 +- Code/CryEngine/CrySystem/System.h | 16 - Code/CryEngine/CrySystem/SystemInit.cpp | 13 - Code/CryEngine/CrySystem/SystemRender.cpp | 315 -- Code/CryEngine/CrySystem/SystemWin32.cpp | 18 - Code/CryEngine/CrySystem/ViewSystem/View.cpp | 2 +- .../CrySystem/ViewSystem/ViewSystem.cpp | 10 - Code/CryEngine/CrySystem/VisRegTest.cpp | 1 - .../CryEngine/CrySystem/crysystem_files.cmake | 2 - Code/Sandbox/Editor/2DViewport.cpp | 108 - .../AzAssetBrowserRequestHandler.cpp | 14 - .../AzAssetBrowserRequestHandler.h | 11 - .../Preview/LegacyPreviewer.cpp | 409 --- .../AzAssetBrowser/Preview/LegacyPreviewer.h | 100 - .../AzAssetBrowser/Preview/LegacyPreviewer.ui | 176 - .../Preview/LegacyPreviewerFactory.cpp | 71 - .../Preview/LegacyPreviewerFactory.h | 34 - Code/Sandbox/Editor/BaseLibraryManager.cpp | 3 - .../Editor/Controls/PreviewModelCtrl.cpp | 1194 ------- .../Editor/Controls/PreviewModelCtrl.h | 198 -- .../Editor/Controls/TimeOfDaySlider.cpp | 26 - .../Sandbox/Editor/Controls/TimeOfDaySlider.h | 34 - Code/Sandbox/Editor/CryEdit.cpp | 180 - Code/Sandbox/Editor/CryEdit.h | 4 - Code/Sandbox/Editor/CryEditDoc.cpp | 275 -- Code/Sandbox/Editor/CryEditDoc.h | 24 - Code/Sandbox/Editor/DisplaySettings.cpp | 5 - Code/Sandbox/Editor/EditorDefs.h | 1 - Code/Sandbox/Editor/EditorViewportWidget.cpp | 32 +- Code/Sandbox/Editor/EditorViewportWidget.h | 4 - Code/Sandbox/Editor/EnvironmentPanel.cpp | 53 - Code/Sandbox/Editor/EnvironmentPanel.h | 53 - Code/Sandbox/Editor/EnvironmentPanel.ui | 56 - Code/Sandbox/Editor/Export/ExportManager.cpp | 59 +- Code/Sandbox/Editor/GameEngine.cpp | 185 - Code/Sandbox/Editor/GameEngine.h | 7 - Code/Sandbox/Editor/GameExporter.cpp | 175 +- Code/Sandbox/Editor/GameExporter.h | 2 - Code/Sandbox/Editor/Geometry/EdGeometry.cpp | 16 - Code/Sandbox/Editor/Geometry/EdGeometry.h | 84 - Code/Sandbox/Editor/Geometry/EdMesh.cpp | 1548 --------- Code/Sandbox/Editor/Geometry/EdMesh.h | 194 -- Code/Sandbox/Editor/IEditor.h | 9 - Code/Sandbox/Editor/IEditorImpl.cpp | 17 - Code/Sandbox/Editor/IEditorImpl.h | 2 - Code/Sandbox/Editor/IconManager.cpp | 37 +- Code/Sandbox/Editor/IconManager.h | 4 - Code/Sandbox/Editor/Include/IIconManager.h | 1 - Code/Sandbox/Editor/Lib/Tests/IEditorMock.h | 2 - Code/Sandbox/Editor/LyViewPaneNames.h | 1 - Code/Sandbox/Editor/MainWindow.cpp | 9 - Code/Sandbox/Editor/Mission.cpp | 364 -- Code/Sandbox/Editor/Mission.h | 105 - Code/Sandbox/Editor/ModelViewport.cpp | 961 ------ Code/Sandbox/Editor/ModelViewport.h | 258 -- Code/Sandbox/Editor/ModelViewportDC.cpp | 24 - Code/Sandbox/Editor/Objects/BaseObject.cpp | 5 +- Code/Sandbox/Editor/Objects/BaseObject.h | 5 - Code/Sandbox/Editor/Objects/DisplayContext.h | 2 - .../Editor/Objects/DisplayContextShared.inl | 24 +- Code/Sandbox/Editor/Objects/EntityObject.cpp | 51 +- Code/Sandbox/Editor/Objects/EntityObject.h | 4 - Code/Sandbox/Editor/Objects/ObjectManager.cpp | 13 - Code/Sandbox/Editor/Objects/ObjectManager.h | 3 - .../Sandbox/Editor/Objects/SelectionGroup.cpp | 1 + Code/Sandbox/Editor/PanelPreview.cpp | 42 - Code/Sandbox/Editor/PanelPreview.h | 40 - Code/Sandbox/Editor/RenderViewport.cpp | 70 +- Code/Sandbox/Editor/RenderViewport.h | 5 - Code/Sandbox/Editor/Resource.h | 2 - Code/Sandbox/Editor/Settings.cpp | 6 - Code/Sandbox/Editor/Settings.h | 2 - Code/Sandbox/Editor/ThumbnailGenerator.cpp | 198 -- Code/Sandbox/Editor/ThumbnailGenerator.h | 30 - Code/Sandbox/Editor/TimeOfDay.qrc | 34 - Code/Sandbox/Editor/TimeOfDayDialog.cpp | 1443 -------- Code/Sandbox/Editor/TimeOfDayDialog.h | 182 - Code/Sandbox/Editor/TimeOfDayDialog.ui | 980 ------ .../Editor/TrackView/TrackViewDialog.cpp | 6 - .../Editor/TrackView/TrackViewNodes.cpp | 64 +- Code/Sandbox/Editor/Util/CubemapUtils.cpp | 1 + Code/Sandbox/Editor/Util/FileUtil.cpp | 61 - Code/Sandbox/Editor/Util/KDTree.cpp | 2 + Code/Sandbox/Editor/Util/VariableTypeInfo.cpp | 445 --- Code/Sandbox/Editor/Util/VariableTypeInfo.h | 221 -- Code/Sandbox/Editor/editor_core_files.cmake | 2 - Code/Sandbox/Editor/editor_lib_files.cmake | 30 +- .../Plugins/EditorCommon/ManipScene.cpp | 1 - .../Plugins/EditorCommon/QViewport.cpp | 348 +- Code/Sandbox/Plugins/EditorCommon/QViewport.h | 1 - .../Code/Source/Previewer/ImagePreviewer.ui | 5 - .../Code/Source/Engine/ATLAudioObject.cpp | 2 +- .../Code/Source/Engine/ATLComponents.cpp | 2 +- Gems/CMakeLists.txt | 3 - .../Code/Tests/UI/LODSkinnedMeshTests.cpp | 1 - Gems/FastNoise/Code/Tests/FastNoiseTest.cpp | 1 - .../Assets/GameEffectsSystem_Dependencies.xml | 3 - Gems/GameEffectSystem/Assets/seedList.seed | 13 - Gems/GameEffectSystem/CMakeLists.txt | 12 - Gems/GameEffectSystem/Code/CMakeLists.txt | 37 - .../Code/gameeffectsystem_files.cmake | 27 - .../Code/gameeffectsystem_shared_files.cmake | 16 - .../GameEffects/GameEffectBase.h | 213 -- .../GameEffects/IGameEffect.h | 103 - .../GameEffectsSystemDefines.h | 179 - .../GameEffectSystem/IGameEffectSystem.h | 163 - .../GameEffectSystem/IGameRenderNode.h | 51 - .../Code/source/GameEffectSystemGem.cpp | 79 - .../Code/source/GameEffectSystemGem.h | 36 - .../source/GameEffectSystem_precompiled.cpp | 12 - .../source/GameEffectSystem_precompiled.h | 21 - .../GameEffects/GameEffectSoftCodeLibrary.cpp | 23 - .../Code/source/GameEffectsSystem.cpp | 1012 ------ .../Code/source/GameEffectsSystem.h | 137 - .../RenderElements/GameRenderElement.cpp | 79 - .../source/RenderElements/GameRenderElement.h | 78 - .../GameRenderElementSoftCodeLibrary.cpp | 24 - .../GameRenderNodeSoftCodeLibrary.cpp | 24 - .../Code/source/RenderNodes/IGameRenderNode.h | 51 - Gems/GameEffectSystem/gem.json | 12 - .../GameStateLevelRunning.inl | 5 - .../Code/Source/Gestures_precompiled.h | 1 - Gems/GradientSignal/Code/CMakeLists.txt | 2 - .../Code/Include/GradientSignal/ImageAsset.h | 4 +- .../Editor/EditorImageBuilderComponent.cpp | 12 +- .../Code/Source/GradientImageConversion.cpp | 36 +- .../GradientSignal/Code/Source/ImageAsset.cpp | 22 +- .../Code/Tests/GradientSignalImageTests.cpp | 4 +- .../Code/Tests/ImageAssetTests.cpp | 34 +- Gems/ImGui/Code/Editor/ImGuiViewport.cpp | 4 - Gems/ImGui/Code/Editor/ImGuiViewport.h | 1 + .../Include/LYImGuiUtils/ImGuiDrawHelpers.h | 2 + Gems/ImGui/Code/Source/ImGuiManager.cpp | 4 +- Gems/ImGui/Code/Source/ImGui_precompiled.h | 1 - .../LYCommonMenu/ImGuiLYAssetExplorer.cpp | 1 + .../Code/Source/InAppPurchases_precompiled.h | 1 - Gems/LmbrCentral/Code/Source/LmbrCentral.cpp | 17 - Gems/LmbrCentral/Code/Source/LmbrCentral.h | 5 - .../MaterialOwnerRequestBusHandlerImpl.h | 349 -- Gems/LmbrCentral/Code/lmbrcentral_files.cmake | 1 - .../Editor/Animation/UiAnimViewDialog.cpp | 6 - .../Code/Editor/Animation/UiAnimViewNodes.cpp | 59 +- .../Code/Source/Animation/AnimNode.cpp | 1 - .../Code/Source/Animation/AnimSequence.cpp | 1 - Gems/LyShine/Code/Tests/SpriteTest.cpp | 1 - .../Source/Cinematics/AnimEnvironmentNode.cpp | 247 -- .../Source/Cinematics/AnimEnvironmentNode.h | 61 - .../Code/Source/Cinematics/AnimNode.cpp | 1 - .../Code/Source/Cinematics/AnimPostFXNode.cpp | 10 - .../Code/Source/Cinematics/AnimSequence.cpp | 5 - .../Code/Source/Cinematics/MaterialNode.cpp | 31 +- .../Source/Cinematics/ShadowsSetupNode.cpp | 2 - .../Source/Components/SequenceComponent.cpp | 2 - Gems/Maestro/Code/maestro_static_files.cmake | 2 - .../Components/EditorSystemComponent.cpp | 25 - Gems/SVOGI/CMakeLists.txt | 12 - Gems/SVOGI/Code/CMakeLists.txt | 48 - Gems/SVOGI/Code/Include/SVOGI/SVOGIBus.h | 37 - .../Platform/Android/SVOGI_Traits_Android.h | 14 - .../Platform/Android/SVOGI_Traits_Platform.h | 14 - .../Android/platform_android_files.cmake | 15 - .../Platform/Linux/SVOGI_Traits_Linux.h | 14 - .../Platform/Linux/SVOGI_Traits_Platform.h | 14 - .../Platform/Linux/platform_linux_files.cmake | 15 - .../Source/Platform/Mac/SVOGI_Traits_Mac.h | 14 - .../Platform/Mac/SVOGI_Traits_Platform.h | 14 - .../Platform/Mac/platform_mac_files.cmake | 15 - .../Platform/Windows/SVOGI_Traits_Platform.h | 14 - .../Platform/Windows/SVOGI_Traits_Windows.h | 14 - .../Windows/platform_windows_files.cmake | 15 - .../Platform/iOS/SVOGI_Traits_Platform.h | 14 - .../Source/Platform/iOS/SVOGI_Traits_iOS.h | 14 - .../Platform/iOS/platform_ios_files.cmake | 15 - Gems/SVOGI/Code/Source/SVOGIModule.cpp | 54 - .../Code/Source/SVOGISystemComponent.cpp | 448 --- Gems/SVOGI/Code/Source/SVOGISystemComponent.h | 143 - Gems/SVOGI/Code/Source/SVOGI_precompiled.cpp | 14 - Gems/SVOGI/Code/Source/SVOGI_precompiled.h | 15 - Gems/SVOGI/Code/Source/SvoBrick.cpp | 1283 ------- Gems/SVOGI/Code/Source/SvoBrick.h | 225 -- Gems/SVOGI/Code/Source/SvoTree.cpp | 1321 ------- Gems/SVOGI/Code/Source/SvoTree.h | 233 -- Gems/SVOGI/Code/Source/TextureBlockPacker.cpp | 272 -- Gems/SVOGI/Code/Source/TextureBlockPacker.h | 118 - Gems/SVOGI/Code/svogi_files.cmake | 24 - Gems/SVOGI/Code/svogi_shared_files.cmake | 14 - Gems/SVOGI/gem.json | 23 - .../TerrainSurfaceDataSystemComponent.cpp | 1 - .../Code/Tests/SurfaceDataTest.cpp | 1 - .../Code/Source/AreaSystemComponent.cpp | 12 - .../Code/Source/Debugger/DebugComponent.cpp | 91 - .../Code/Source/Debugger/DebugComponent.h | 1 - Gems/Vegetation/Code/Source/Descriptor.cpp | 2 - .../Legacy/WhiteBoxLegacyRenderMesh.cpp | 465 --- .../Legacy/WhiteBoxLegacyRenderMesh.h | 42 - .../Code/Source/WhiteBoxSystemComponent.cpp | 1 - .../Code/whitebox_supported_files.cmake | 2 - .../ConsoleFrontendConfig.in | 1 - 222 files changed, 124 insertions(+), 26474 deletions(-) delete mode 100644 Code/CryEngine/CryCommon/CryEngineDecalInfo.h delete mode 100644 Code/CryEngine/CryCommon/Gem.h delete mode 100644 Code/CryEngine/CryCommon/I3DEngine.h delete mode 100644 Code/CryEngine/CryCommon/I3DEngine_info.h delete mode 100644 Code/CryEngine/CryCommon/ILocalMemoryUsage.h delete mode 100644 Code/CryEngine/CryCommon/ITimeOfDay.h delete mode 100644 Code/CryEngine/CryCommon/Mocks/I3DEngineMock.h delete mode 100644 Code/CryEngine/CryCommon/WindowsUtils.h delete mode 100644 Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.cpp delete mode 100644 Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.h delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.cpp delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.h delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.ui delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp delete mode 100644 Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h delete mode 100644 Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp delete mode 100644 Code/Sandbox/Editor/Controls/PreviewModelCtrl.h delete mode 100644 Code/Sandbox/Editor/Controls/TimeOfDaySlider.cpp delete mode 100644 Code/Sandbox/Editor/Controls/TimeOfDaySlider.h delete mode 100644 Code/Sandbox/Editor/EnvironmentPanel.cpp delete mode 100644 Code/Sandbox/Editor/EnvironmentPanel.h delete mode 100644 Code/Sandbox/Editor/EnvironmentPanel.ui delete mode 100644 Code/Sandbox/Editor/Geometry/EdGeometry.cpp delete mode 100644 Code/Sandbox/Editor/Geometry/EdGeometry.h delete mode 100644 Code/Sandbox/Editor/Geometry/EdMesh.cpp delete mode 100644 Code/Sandbox/Editor/Geometry/EdMesh.h delete mode 100644 Code/Sandbox/Editor/Mission.cpp delete mode 100644 Code/Sandbox/Editor/Mission.h delete mode 100644 Code/Sandbox/Editor/ModelViewport.cpp delete mode 100644 Code/Sandbox/Editor/ModelViewport.h delete mode 100644 Code/Sandbox/Editor/ModelViewportDC.cpp delete mode 100644 Code/Sandbox/Editor/PanelPreview.cpp delete mode 100644 Code/Sandbox/Editor/PanelPreview.h delete mode 100644 Code/Sandbox/Editor/ThumbnailGenerator.cpp delete mode 100644 Code/Sandbox/Editor/ThumbnailGenerator.h delete mode 100644 Code/Sandbox/Editor/TimeOfDay.qrc delete mode 100644 Code/Sandbox/Editor/TimeOfDayDialog.cpp delete mode 100644 Code/Sandbox/Editor/TimeOfDayDialog.h delete mode 100644 Code/Sandbox/Editor/TimeOfDayDialog.ui delete mode 100644 Code/Sandbox/Editor/Util/VariableTypeInfo.cpp delete mode 100644 Code/Sandbox/Editor/Util/VariableTypeInfo.h delete mode 100644 Gems/GameEffectSystem/Assets/GameEffectsSystem_Dependencies.xml delete mode 100644 Gems/GameEffectSystem/Assets/seedList.seed delete mode 100644 Gems/GameEffectSystem/CMakeLists.txt delete mode 100644 Gems/GameEffectSystem/Code/CMakeLists.txt delete mode 100644 Gems/GameEffectSystem/Code/gameeffectsystem_files.cmake delete mode 100644 Gems/GameEffectSystem/Code/gameeffectsystem_shared_files.cmake delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/GameEffectBase.h delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/IGameEffect.h delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffectsSystemDefines.h delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameEffectSystem.h delete mode 100644 Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameRenderNode.h delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectSystemGem.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectSystemGem.h delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.h delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffects/GameEffectSoftCodeLibrary.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectsSystem.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/GameEffectsSystem.h delete mode 100644 Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.h delete mode 100644 Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElementSoftCodeLibrary.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp delete mode 100644 Gems/GameEffectSystem/Code/source/RenderNodes/IGameRenderNode.h delete mode 100644 Gems/GameEffectSystem/gem.json delete mode 100644 Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/Utils/MaterialOwnerRequestBusHandlerImpl.h delete mode 100644 Gems/Maestro/Code/Source/Cinematics/AnimEnvironmentNode.cpp delete mode 100644 Gems/Maestro/Code/Source/Cinematics/AnimEnvironmentNode.h delete mode 100644 Gems/SVOGI/CMakeLists.txt delete mode 100644 Gems/SVOGI/Code/CMakeLists.txt delete mode 100644 Gems/SVOGI/Code/Include/SVOGI/SVOGIBus.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Android/SVOGI_Traits_Android.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Android/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Android/platform_android_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/Platform/Linux/SVOGI_Traits_Linux.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Linux/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Linux/platform_linux_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/Platform/Mac/SVOGI_Traits_Mac.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Mac/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Mac/platform_mac_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/Platform/Windows/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Windows/SVOGI_Traits_Windows.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/Windows/platform_windows_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/Platform/iOS/SVOGI_Traits_Platform.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/iOS/SVOGI_Traits_iOS.h delete mode 100644 Gems/SVOGI/Code/Source/Platform/iOS/platform_ios_files.cmake delete mode 100644 Gems/SVOGI/Code/Source/SVOGIModule.cpp delete mode 100644 Gems/SVOGI/Code/Source/SVOGISystemComponent.cpp delete mode 100644 Gems/SVOGI/Code/Source/SVOGISystemComponent.h delete mode 100644 Gems/SVOGI/Code/Source/SVOGI_precompiled.cpp delete mode 100644 Gems/SVOGI/Code/Source/SVOGI_precompiled.h delete mode 100644 Gems/SVOGI/Code/Source/SvoBrick.cpp delete mode 100644 Gems/SVOGI/Code/Source/SvoBrick.h delete mode 100644 Gems/SVOGI/Code/Source/SvoTree.cpp delete mode 100644 Gems/SVOGI/Code/Source/SvoTree.h delete mode 100644 Gems/SVOGI/Code/Source/TextureBlockPacker.cpp delete mode 100644 Gems/SVOGI/Code/Source/TextureBlockPacker.h delete mode 100644 Gems/SVOGI/Code/svogi_files.cmake delete mode 100644 Gems/SVOGI/Code/svogi_shared_files.cmake delete mode 100644 Gems/SVOGI/gem.json delete mode 100644 Gems/WhiteBox/Code/Source/Rendering/Legacy/WhiteBoxLegacyRenderMesh.cpp delete mode 100644 Gems/WhiteBox/Code/Source/Rendering/Legacy/WhiteBoxLegacyRenderMesh.h diff --git a/Code/CryEngine/CryCommon/CryEngineDecalInfo.h b/Code/CryEngine/CryCommon/CryEngineDecalInfo.h deleted file mode 100644 index f38533e341..0000000000 --- a/Code/CryEngine/CryCommon/CryEngineDecalInfo.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : declaration of struct CryEngineDecalInfo. - -// Note: -// 3D Engine and Character Animation subsystems (as well as perhaps -// some others) transfer data about the decals that need to be spawned -// via this structure. This is to avoid passing many parameters through -// each function call, and to save on copying these parameters when just -// simply passing the structure from one function to another. - -#ifndef CRYINCLUDE_CRYCOMMON_CRYENGINEDECALINFO_H -#define CRYINCLUDE_CRYCOMMON_CRYENGINEDECALINFO_H -#pragma once - -#include "Cry_Math.h" - -// Summary: -// Structure containing common parameters that describe a decal - -struct SDecalOwnerInfo -{ - SDecalOwnerInfo() { memset(this, 0, sizeof(*this)); nRenderNodeSlotId = nRenderNodeSlotSubObjectId = -1; } - struct IStatObj* GetOwner(Matrix34A& objMat); - - struct IRenderNode* pRenderNode; // Owner (decal will be attached to or wrapped around of this object) - PodArray* pDecalReceivers; - int nRenderNodeSlotId; // is set internally by 3dengine - int nRenderNodeSlotSubObjectId; // is set internally by 3dengine - int nMatID; -}; - -struct CryEngineDecalInfo -{ - SDecalOwnerInfo ownerInfo; - Vec3 vPos; // Decal position (world coordinates) - Vec3 vNormal; // Decal/face normal - float fSize; // Decal size - float fLifeTime; // Decal life time (in seconds) - float fAngle; // Angle of rotation - struct IStatObj* pIStatObj; // Decal geometry - Vec3 vHitDirection; // Direction from weapon/player position to decal position (bullet direction) - float fGrowTime, fGrowTimeAlpha;// Used for blood pools - unsigned int nGroupId; // Used for multi-component decals - bool bSkipOverlappingTest; // Always spawn decals even if there are a lot of other decals in same place - bool bAssemble; // Assemble to bigger decals if more than 1 decal is on the same place - bool bForceEdge; // force the decal to the nearest edge of the owner mesh and project it accordingly - bool bForceSingleOwner; // Do not attempt to cast the decal into the environment even if it's large enough - bool bDeferred; - uint8 sortPrio; - char szMaterialName[_MAX_PATH]; // name of material used for rendering the decal (in favor of szTextureName/nTid and the default decal shader) - bool preventDecalOnGround; // mainly for decal placement support - const Matrix33* pExplicitRightUpFront; // mainly for decal placement support - - void GetMemoryUsage([[maybe_unused]] ICrySizer* pSizer) const{} - - // the constructor fills in some non-obligatory fields; the other fields must be filled in by the client - CryEngineDecalInfo () - { - memset(this, 0, sizeof(*this)); - ownerInfo.nRenderNodeSlotId = ownerInfo.nRenderNodeSlotSubObjectId = -1; - sortPrio = 255; - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_CRYENGINEDECALINFO_H diff --git a/Code/CryEngine/CryCommon/Gem.h b/Code/CryEngine/CryCommon/Gem.h deleted file mode 100644 index 3097fcf304..0000000000 --- a/Code/CryEngine/CryCommon/Gem.h +++ /dev/null @@ -1,98 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include - -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(Gem_h) -#endif - -#if defined(LINUX) || defined(APPLE) || defined(ANDROID) - #define OPENGL 1 -#endif - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include <3dEngine.h> -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include diff --git a/Code/CryEngine/CryCommon/I3DEngine.h b/Code/CryEngine/CryCommon/I3DEngine.h deleted file mode 100644 index 883b0a6d3b..0000000000 --- a/Code/CryEngine/CryCommon/I3DEngine.h +++ /dev/null @@ -1,3021 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : 3dengine interface - -#ifndef CRYINCLUDE_CRYCOMMON_I3DENGINE_H -#define CRYINCLUDE_CRYCOMMON_I3DENGINE_H -#pragma once - -// The maximum number of unique surface types that can be used per node -#define MMRM_MAX_SURFACE_TYPES 16 -#define COMPILED_OCTREE_FILE_NAME "terrain/terrain.dat" - -// !!! Do not add any headers here !!! -#include "CryEngineDecalInfo.h" -#include -#include // <> required for Interfuscator -#include "IRenderer.h" -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include // <> required for Interfuscator -#include "CryArray.h" -#include // <> required for Interfuscator -#include -// !!! Do not add any headers here !!! - -class IOpticsManager; -class CContentCGF; -class ICrySizer; -class CRenderView; -struct ISystem; -struct CVars; -struct pe_params_particle; -struct IMaterial; -struct SpawnParams; -struct ForceObject; -struct IRenderNode; -struct IObjManager; -struct IDeferredPhysicsEventManager; -struct IBSPTree3D; -struct ITextureLoadHandler; -struct ITimeOfDay; -struct MacroTextureConfiguration; - -namespace LegacyProceduralVegetation -{ - class IVegetationPoolManager; -} - -namespace LegacyTerrain -{ - struct MacroTextureConfiguration; -} - -namespace ChunkFile -{ - struct IChunkFileWriter; -} - -namespace AZ -{ - class Aabb; -} - -enum E3DEngineParameter -{ - E3DPARAM_SUN_COLOR, - - E3DPARAM_SUN_SPECULAR_MULTIPLIER, - - E3DPARAM_AMBIENT_GROUND_COLOR, - E3DPARAM_AMBIENT_MIN_HEIGHT, - E3DPARAM_AMBIENT_MAX_HEIGHT, - - E3DPARAM_FOG_COLOR, - E3DPARAM_FOG_COLOR2, - E3DPARAM_FOG_RADIAL_COLOR, - - E3DPARAM_VOLFOG_HEIGHT_DENSITY, - E3DPARAM_VOLFOG_HEIGHT_DENSITY2, - - E3DPARAM_VOLFOG_GRADIENT_CTRL, - - E3DPARAM_VOLFOG_GLOBAL_DENSITY, - E3DPARAM_VOLFOG_RAMP, - - E3DPARAM_VOLFOG_SHADOW_RANGE, - E3DPARAM_VOLFOG_SHADOW_DARKENING, - E3DPARAM_VOLFOG_SHADOW_ENABLE, - - E3DPARAM_VOLFOG2_CTRL_PARAMS, - E3DPARAM_VOLFOG2_SCATTERING_PARAMS, - E3DPARAM_VOLFOG2_RAMP, - E3DPARAM_VOLFOG2_COLOR, - E3DPARAM_VOLFOG2_GLOBAL_DENSITY, - E3DPARAM_VOLFOG2_HEIGHT_DENSITY, - E3DPARAM_VOLFOG2_HEIGHT_DENSITY2, - E3DPARAM_VOLFOG2_COLOR1, - E3DPARAM_VOLFOG2_COLOR2, - - E3DPARAM_SKYLIGHT_SUN_INTENSITY, - - E3DPARAM_SKYLIGHT_KM, - E3DPARAM_SKYLIGHT_KR, - E3DPARAM_SKYLIGHT_G, - - E3DPARAM_SKYLIGHT_WAVELENGTH_R, - E3DPARAM_SKYLIGHT_WAVELENGTH_G, - E3DPARAM_SKYLIGHT_WAVELENGTH_B, - - E3DPARAM_NIGHSKY_HORIZON_COLOR, - E3DPARAM_NIGHSKY_ZENITH_COLOR, - E3DPARAM_NIGHSKY_ZENITH_SHIFT, - - E3DPARAM_NIGHSKY_STAR_INTENSITY, - - E3DPARAM_NIGHSKY_MOON_DIRECTION, - E3DPARAM_NIGHSKY_MOON_COLOR, - E3DPARAM_NIGHSKY_MOON_SIZE, - E3DPARAM_NIGHSKY_MOON_INNERCORONA_COLOR, - E3DPARAM_NIGHSKY_MOON_INNERCORONA_SCALE, - E3DPARAM_NIGHSKY_MOON_OUTERCORONA_COLOR, - E3DPARAM_NIGHSKY_MOON_OUTERCORONA_SCALE, - - E3DPARAM_CLOUDSHADING_MULTIPLIERS, - E3DPARAM_CLOUDSHADING_SUNCOLOR, - E3DPARAM_CLOUDSHADING_SKYCOLOR, - - E3DPARAM_CORONA_SIZE, - - E3DPARAM_OCEANFOG_COLOR, - E3DPARAM_OCEANFOG_DENSITY, - - // Sky highlight (ex. From Lightning) - E3DPARAM_SKY_HIGHLIGHT_COLOR, - E3DPARAM_SKY_HIGHLIGHT_SIZE, - E3DPARAM_SKY_HIGHLIGHT_POS, - - E3DPARAM_SKY_MOONROTATION, - - E3DPARAM_SKY_SKYBOX_ANGLE, - E3DPARAM_SKY_SKYBOX_STRETCHING, - - EPARAM_SUN_SHAFTS_VISIBILITY, - - E3DPARAM_SKYBOX_MULTIPLIER, - - E3DPARAM_DAY_NIGHT_INDICATOR, - - // Tone mapping tweakables - E3DPARAM_HDR_FILMCURVE_SHOULDER_SCALE, - E3DPARAM_HDR_FILMCURVE_LINEAR_SCALE, - E3DPARAM_HDR_FILMCURVE_TOE_SCALE, - E3DPARAM_HDR_FILMCURVE_WHITEPOINT, - - E3DPARAM_HDR_EYEADAPTATION_PARAMS, - E3DPARAM_HDR_EYEADAPTATION_PARAMS_LEGACY, - E3DPARAM_HDR_BLOOM_AMOUNT, - - E3DPARAM_HDR_COLORGRADING_COLOR_SATURATION, - E3DPARAM_HDR_COLORGRADING_COLOR_BALANCE, - - E3DPARAM_COLORGRADING_FILTERS_PHOTOFILTER_COLOR, - E3DPARAM_COLORGRADING_FILTERS_PHOTOFILTER_DENSITY, - E3DPARAM_COLORGRADING_FILTERS_GRAIN -}; - -enum EShadowMode -{ - ESM_NORMAL = 0, - ESM_HIGHQUALITY -}; - -struct IBSPTree3D -{ - typedef DynArray CFace; - typedef DynArray FaceList; - - virtual ~IBSPTree3D() {} - virtual bool IsInside(const Vec3& vPos) const = 0; - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - virtual size_t WriteToBuffer(void* pBuffer) const = 0; - virtual void ReadFromBuffer(const void* pBuffer) = 0; -}; - -////////////////////////////////////////////////////////////////////////// -// Description: -// This structure is filled and passed by the caller to the DebugDraw functions of the stat object or entity. -struct SGeometryDebugDrawInfo -{ - Matrix34 tm; // Transformation Matrix - ColorB color; // Optional color of the lines. - ColorB lineColor; // Optional color of the lines. - - // Optional flags controlling how to render debug draw information. - uint32 bNoCull : 1; - uint32 bNoLines : 1; - uint32 bExtrude : 1; // Extrude debug draw geometry alittle bit so it is over real geometry. - - SGeometryDebugDrawInfo() - : color(255, 0, 255, 255) - , lineColor(255, 255, 0, 255) - , bNoLines(0) - , bNoCull(0) { tm.SetIdentity(); } -}; - -struct SFrameLodInfo -{ - uint32 nID; - float fLodRatio; - float fTargetSize; - uint nMinLod; - uint nMaxLod; - - SFrameLodInfo() - { - nID = 0; - fLodRatio = 0.f; - fTargetSize = 0.f; - nMinLod = 0; - nMaxLod = 6; - } -}; -struct SMeshLodInfo -{ - static const int s_nMaxLodCount = 5; - float fGeometricMean; - uint nFaceCount; - uint32 nFrameLodID; - SMeshLodInfo() - { - Clear(); - } - void Clear() - { - fGeometricMean = 0.f; - nFaceCount = 0; - nFrameLodID = 0; - } - void Merge(const SMeshLodInfo& lodInfo) - { - uint nTotalCount = nFaceCount + lodInfo.nFaceCount; - if (nTotalCount > 0) - { - float fGeometricMeanTotal = 0.f; - if (fGeometricMean > 0.f) - { - fGeometricMeanTotal += logf(fGeometricMean) * nFaceCount; - } - if (lodInfo.fGeometricMean > 0.f) - { - fGeometricMeanTotal += logf(lodInfo.fGeometricMean) * lodInfo.nFaceCount; - } - fGeometricMean = expf(fGeometricMeanTotal / (float)nTotalCount); - nFaceCount = nTotalCount; - } - } -}; -// Summary: -// Physics material enumerator, allows for 3dengine to get material id from game code. -struct IPhysMaterialEnumerator -{ - // - virtual ~IPhysMaterialEnumerator(){} - virtual int EnumPhysMaterial(const char* szPhysMatName) = 0; - virtual bool IsCollidable(int nMatId) = 0; - virtual int GetMaterialCount() = 0; - virtual const char* GetMaterialNameByIndex(int index) = 0; - // -}; - - -// Summary: -// Physics foreign data flags. -enum EPhysForeignFlags -{ - PFF_HIDABLE = 0x1, - PFF_HIDABLE_SECONDARY = 0x2, - PFF_EXCLUDE_FROM_STATIC = 0x4, - PFF_UNIMPORTANT = 0x20, - PFF_OUTDOOR_AREA = 0x40, - PFF_MOVING_PLATFORM = 0x80, -}; - -// Summary: -// Ocean data flags. -enum EOceanRenderFlags -{ - OCR_NO_DRAW = 1 << 0, - OCR_OCEANVOLUME_VISIBLE = 1 << 1, -}; - -// Summary: -// Structure to pass vegetation group properties. -struct IStatInstGroup -{ - enum EPlayerHideable - { - ePlayerHideable_None = 0, - ePlayerHideable_High, - ePlayerHideable_Mid, - ePlayerHideable_Low, - - ePlayerHideable_COUNT, - }; - - IStatInstGroup() - { - pStatObj = 0; - szFileName[0] = 0; - bHideability = 0; - bHideabilitySecondary = 0; - fBending = 0; - nCastShadowMinSpec = 0; - bRecvShadow = 0; - bDynamicDistanceShadows = false; - bUseAlphaBlending = 0; - fSpriteDistRatio = 1.f; - fShadowDistRatio = 1.f; - fMaxViewDistRatio = 1.f; - fLodDistRatio = 1.f; - fBrightness = 1.f; - pMaterial = 0; - - fDensity = 1; - fElevationMax = 4096; - fElevationMin = 8; - fSize = 1; - fSizeVar = 0; - fSlopeMax = 255; - fSlopeMin = 0; - fStiffness = 0.5f; - fDamping = 2.5f; - fVariance = 0.6f; - fAirResistance = 1.f; - bRandomRotation = false; - nRotationRangeToTerrainNormal = 0; - nMaterialLayers = 0; - bAllowIndoor = false; - fAlignToTerrainCoefficient = 0.f; - bAutoMerged = false; - minConfigSpec = (ESystemConfigSpec)0; - nTexturesAreStreamedIn = 0; - nPlayerHideable = ePlayerHideable_None; - nID = -1; - } - - IStatObj* GetStatObj() - { - IStatObj* p = pStatObj; - return (IStatObj*)p; - } - const IStatObj* GetStatObj() const - { - const IStatObj* p = pStatObj; - return (const IStatObj*)p; - } - - _smart_ptr pStatObj; - char szFileName[256]; - bool bHideability; - bool bHideabilitySecondary; - float fBending; - uint8 nCastShadowMinSpec; - bool bRecvShadow; - bool bDynamicDistanceShadows; - bool bUseAlphaBlending; - float fSpriteDistRatio; - float fLodDistRatio; - float fShadowDistRatio; - float fMaxViewDistRatio; - float fBrightness; - bool bRandomRotation; - int32 nRotationRangeToTerrainNormal; - float fAlignToTerrainCoefficient; - bool bAllowIndoor; - bool bAutoMerged; - - float fDensity; - float fElevationMax; - float fElevationMin; - float fSize; - float fSizeVar; - float fSlopeMax; - float fSlopeMin; - float fStiffness; - float fDamping; - float fVariance; - float fAirResistance; - - float fVegRadius; - float fVegRadiusVert; - float fVegRadiusHor; - - int nPlayerHideable; - int nID; - - // Minimal configuration spec for this vegetation group. - ESystemConfigSpec minConfigSpec; - - // Override material for this instance group. - _smart_ptr pMaterial; - - // Material layers bitmask -> which layers are active. - uint8 nMaterialLayers; - - // Textures Are Streamed In. - uint8 nTexturesAreStreamedIn; - - // Flags similar to entity render flags. - int m_dwRndFlags; -}; - -// Description: -// Water volumes should usually be created by I3DEngine::CreateWaterVolume. -// Summary: -// Interface to water volumes. -struct IWaterVolume -{ - // - //DOC-IGNORE-BEGIN - virtual ~IWaterVolume(){} - virtual void UpdatePoints(const Vec3* pPoints, int nCount, float fHeight) = 0; - virtual void SetFlowSpeed(float fSpeed) = 0; - virtual void SetAffectToVolFog(bool bAffectToVolFog) = 0; - virtual void SetTriSizeLimits(float fTriMinSize, float fTriMaxSize) = 0; - // virtual void SetMaterial(const char * szShaderName) = 0; - virtual void SetMaterial(_smart_ptr pMaterial) = 0; - virtual _smart_ptr GetMaterial() = 0; - virtual const char* GetName() const = 0; - virtual void SetName(const char* szName) = 0; - //DOC-IGNORE-END - - // Description: - // Used to change the water level. Will assign a new Z value to all - // vertices of the water geometry. - // Arguments: - // vNewOffset - Position of the new water level - // Summary: - // Sets a new water level. - virtual void SetPositionOffset(const Vec3& vNewOffset) = 0; - // -}; - -struct SClipVolumeBlendInfo -{ - static const int BlendPlaneCount = 2; - - Plane_tpl blendPlanes[BlendPlaneCount]; - struct IClipVolume* blendVolumes[BlendPlaneCount]; -}; - -struct IClipVolume -{ - enum EClipVolumeFlags - { - eClipVolumeConnectedToOutdoor = BIT(0), - eClipVolumeIgnoreGI = BIT(1), - eClipVolumeAffectedBySun = BIT(2), - eClipVolumeBlend = BIT(3), - eClipVolumeIsVisArea = BIT(4), - eClipVolumeIgnoreOutdoorAO = BIT(5), - }; - - virtual ~IClipVolume() {}; - virtual void GetClipVolumeMesh(_smart_ptr& renderMesh, Matrix34& worldTM) const = 0; - virtual AABB GetClipVolumeBBox() const = 0; - virtual bool IsPointInsideClipVolume(const Vec3& point) const = 0; - - virtual uint8 GetStencilRef() const = 0; - virtual uint GetClipVolumeFlags() const = 0; -}; - -// Summary: -// Provides information about the different VisArea volumes. -struct IVisArea - : public IClipVolume -{ - // - virtual ~IVisArea(){} - // Summary: - // Gets the last rendered frame id. - // Return Value: - // An int which contains the frame id. - virtual int GetVisFrameId() = 0; - - // Description: - // Gets a list of all the VisAreas which are connected to the current one. - // Arguments: - // pAreas - Pointer to an array of IVisArea* - // nMaxConnNum - The maximum of IVisArea to write in pAreas - // bSkipDisabledPortals - Ignore portals which are disabled - // Return Value: - // An integer which hold the amount of VisArea found to be connected. If - // the return is equal to nMaxConnNum, it's possible that not all - // connected VisAreas were returned due to the restriction imposed by the - // argument. - // Summary: - // Gets all the areas which are connected to the current one. - virtual int GetVisAreaConnections(IVisArea** pAreas, int nMaxConnNum, bool bSkipDisabledPortals = false) = 0; - - // Summary: - // Determines if it's connected to an outdoor area. - // Return Value: - // True if the VisArea is connected to an outdoor area. - virtual bool IsConnectedToOutdoor() const = 0; - - // Summary: - // Determines if the visarea ignores Global Illumination inside. - // Return Value: - // True if the VisArea ignores Global Illumination inside. - virtual bool IsIgnoringGI() const = 0; - - // Summary: - // Determines if the visarea ignores Outdoor Ambient occlusion inside. - // Return Value: - // True if the VisArea ignores Outdoor Ambient Occlusion inside. - virtual bool IsIgnoringOutdoorAO() const = 0; - - // Summary: - // Gets the name. - // Notes: - // The name is always returned in lower case. - // Return Value: - // A null terminated char array containing the name of the VisArea. - virtual const char* GetName() = 0; - - // Summary: - // Determines if this VisArea is a portal. - // Return Value: - // True if the VisArea is a portal, or false in the opposite case. - virtual bool IsPortal() const = 0; - - // Description: - // Searches for a specified VisArea to see if it's connected to the current - // VisArea. - // Arguments: - // pAnotherArea - A specified VisArea to find - // nMaxRecursion - The maximum number of recursion to do while searching - // bSkipDisabledPortals - Will avoid searching disabled VisAreas - // pVisitedAreas - if not NULL - will get list of all visited areas - // Return Value: - // True if the VisArea was found. - // Summary: - // Searches for a specified VisArea. - virtual bool FindVisArea(IVisArea* pAnotherArea, int nMaxRecursion, bool bSkipDisabledPortals) = 0; - - // Description: - // Searches for the surrounding VisAreas which connected to the current - // VisArea. - // Arguments: - // nMaxRecursion - The maximum number of recursion to do while searching - // bSkipDisabledPortals - Will avoid searching disabled VisAreas - // pVisitedAreas - if not NULL - will get list of all visited areas - // Return Value: - // None. - // Summary: - // Searches for the surrounding VisAreas. - virtual void FindSurroundingVisArea(int nMaxRecursion, bool bSkipDisabledPortals, PodArray* pVisitedAreas = NULL, int nMaxVisitedAreas = 0, int nDeepness = 0) = 0; - - // Summary: - // Determines if it's affected by outdoor lighting. - // Return Value: - // Returns true if the VisArea if it's affected by outdoor lighting, else - // false will be returned. - virtual bool IsAffectedByOutLights() const = 0; - - // Summary: - // Determines if the spere can be affect the VisArea. - // Return Value: - // Returns true if the VisArea can be affected by the sphere, else - // false will be returned. - virtual bool IsSphereInsideVisArea(const Vec3& vPos, const f32 fRadius) = 0; - - // Summary: - // Clips geometry inside or outside a vis area. - // Return Value: - // Whether geom was clipped. - virtual bool ClipToVisArea(bool bInside, Sphere& sphere, Vec3 const& vNormal) = 0; - - // Summary: - // Gives back the axis aligned bounding box of VisArea. - // Return Value: - // Returns the pointer of a AABB. - virtual const AABB* GetAABBox() const = 0; - - // Summary: - // Gives back the axis aligned bounding box of all static objects in the VisArea. - // This AABB can be huger than the ViaArea AABB as some objects might not be completely inside the VisArea. - // Return Value: - // Returns the pointer to the AABB. - virtual const AABB* GetStaticObjectAABBox() const = 0; - - // Summary: - // Determines if the point can be affect the VisArea. - // Return Value: - // Returns true if the VisArea can be affected by the point, else - // false will be returned. - virtual bool IsPointInsideVisArea(const Vec3& vPos) const = 0; - - virtual void GetShapePoints(const Vec3*& pPoints, size_t& nPoints) = 0; - virtual float GetHeight() = 0; - // -}; - -#include "OceanConstants.h" - -// float m_SortId : offseted by +WATER_LEVEL_SORTID_OFFSET if the camera object line is crossing the water surface -// : otherwise offseted by -WATER_LEVEL_SORTID_OFFSET -#define WATER_LEVEL_SORTID_OFFSET 10000000 - -#define DEFAULT_SID 0 - -// Summary: -// indirect lighting quadtree definition. -namespace NQT -{ - // Forward declaration - template - class CQuadTree; -} - -#define FILEVERSION_TERRAIN_SHLIGHTING_FILE 5 - -enum EVoxelBrushShape -{ - evbsSphere = 1, - evbsBox, -}; - -enum EVoxelEditTarget -{ - evetVoxelObjects = 1, -}; - -enum EVoxelEditOperation -{ - eveoNone = 0, - eveoPaintHeightPos, - eveoPaintHeightNeg, - eveoCreate, - eveoSubstract, - eveoMaterial, - eveoBaseColor, - eveoBlurPos, - eveoBlurNeg, - eveoCopyTerrainPos, - eveoCopyTerrainNeg, - eveoPickHeight, - eveoIntegrateMeshPos, - eveoIntegrateMeshNeg, - eveoForceDepth, - eveoLimitLod, - eveoLast, -}; - -#define COMPILED_VISAREA_MAP_FILE_NAME "terrain\\indoor.dat" -#define COMPILED_MERGED_MESHES_BASE_NAME "terrain\\merged_meshes_sectors\\" -#define COMPILED_MERGED_MESHES_LIST "mmrm_used_meshes.lst" -#define LEVEL_INFO_FILE_NAME "levelinfo.xml" - -////////////////////////////////////////////////////////////////////////// - -#pragma pack(push,4) - -#define VISAREAMANAGER_CHUNK_VERSION 6 - -#define SERIALIZATION_FLAG_BIG_ENDIAN 1 -#define SERIALIZATION_FLAG_SECTOR_PALETTES 2 - -#define TCH_FLAG2_AREA_ACTIVATION_IN_USE 1 - -struct SVisAreaManChunkHeader -{ - int8 nVersion; - int8 nDummy; - int8 nFlags; - int8 nFlags2; - int nChunkSize; - int nVisAreasNum; - int nPortalsNum; - int nOcclAreasNum; - - AUTO_STRUCT_INFO -}; - -struct SOcTreeNodeChunk -{ - int16 nChunkVersion; - int16 ucChildsMask; - AABB nodeBox; - int32 nObjectsBlockSize; - - AUTO_STRUCT_INFO -}; - -struct SHotUpdateInfo -{ - SHotUpdateInfo() - { - nHeigtmap = 1; - nObjTypeMask = ~0; - pVisibleLayerMask = NULL; - pLayerIdTranslation = NULL; - areaBox.Reset(); - } - - uint32 nHeigtmap; - uint32 nObjTypeMask; - const uint8* pVisibleLayerMask; - const uint16* pLayerIdTranslation; - AABB areaBox; - - AUTO_STRUCT_INFO -}; - -#define OCTREE_CHUNK_VERSION 29 - -//============================================================================================== - -// Summary: -// Common header for binary files used by 3dengine -struct SCommonFileHeader -{ - char signature[4]; // File signature, should be "CRY " - uint8 file_type; // File type - uint8 flags; // File common flags - uint16 version; // File version - - AUTO_STRUCT_INFO -}; - -struct IVisAreaCallback -{ - // - virtual ~IVisAreaCallback(){} - virtual void OnVisAreaDeleted(IVisArea* pVisArea) = 0; - // -}; - -struct IVisAreaManager -{ - // - virtual ~IVisAreaManager(){} - // Summary: - // Loads data into VisAreaManager engine from memory block. - virtual bool SetCompiledData(uint8* pData, int nDataSize, std::vector** ppStatObjTable, std::vector<_smart_ptr >** ppMatTable, bool bHotUpdate, SHotUpdateInfo* pExportInfo) = 0; - - // Summary: - // Saves data from VisAreaManager engine into memory block. - virtual bool GetCompiledData(uint8* pData, int nDataSize, std::vector** ppStatObjTable, std::vector<_smart_ptr >** ppMatTable, std::vector** ppStatInstGroupTable, EEndian eEndian, SHotUpdateInfo* pExportInfo = NULL) = 0; - - // Summary: - // Returns VisAreaManager data memory block size. - virtual int GetCompiledDataSize(SHotUpdateInfo* pExportInfo = NULL) = 0; - - // Summary: - // Returns the accumulated number of visareas and portals. - virtual int GetNumberOfVisArea() const = 0; - - // Summary: - // Returns the visarea interface based on the id (0..GetNumberOfVisArea()) it can be a visarea or a portal. - virtual IVisArea* GetVisAreaById(int nID) const = 0; - - virtual void AddListener(IVisAreaCallback* pListener) = 0; - virtual void RemoveListener(IVisAreaCallback* pListener) = 0; - - virtual void PrepareSegmentData(const AABB& box) = 0; - virtual void ReleaseInactiveSegments() = 0; - virtual bool CreateSegment(int nSID) = 0; - virtual bool DeleteSegment(int nSID, bool bDeleteNow) = 0; - virtual bool StreamCompiledData(uint8* pData, int nDataSize, int nSID, std::vector* pStatObjTable, std::vector<_smart_ptr >* pMatTable, std::vector* pStatInstGroupTable, const Vec2& vIndexOffset) = 0; - virtual void OffsetPosition(const Vec3& delta) = 0; - virtual void UpdateConnections() = 0; - // Summary: - // Clones all vis areas in a region of the level, offsetting and rotating them based - // on the values passed in. - // Arguments: - // offset - Offset amount, relative to the center of the region passed in. - // zRotation - Rotation around the z axis, in radians. - virtual void CloneRegion(const AABB& region, const Vec3& offset, float zRotation) = 0; - - // Summary: - // Removes all vis areas in a region of the level. - virtual void ClearRegion(const AABB& region) = 0; - - virtual void GetObjectsByType(PodArray& lstObjects, EERType objType, const AABB* pBBox, ObjectTreeQueryFilterCallback filterCallback = nullptr) = 0; - virtual void GetObjectsByFlags(uint dwFlags, PodArray& lstObjects) = 0; - - virtual void GetObjects(PodArray& lstObjects, const AABB* pBBox) = 0; - - virtual bool IsOutdoorAreasVisible() = 0; -}; - -struct SSkyLightRenderParams -{ - static const int skyDomeTextureWidth = 64; - static const int skyDomeTextureHeight = 32; - static const int skyDomeTextureSize = 64 * 32; - - static const int skyDomeTextureWidthBy8 = 8; - static const int skyDomeTextureWidthBy4Log = 4; // = log2(64/4) - static const int skyDomeTextureHeightBy2Log = 4; // = log2(32/2) - - SSkyLightRenderParams() - : m_pSkyDomeMesh(0) - , m_pSkyDomeTextureDataMie(0) - , m_pSkyDomeTextureDataRayleigh(0) - , m_skyDomeTexturePitch(0) - , m_skyDomeTextureTimeStamp(-1) - , m_partialMieInScatteringConst(0.0f, 0.0f, 0.0f, 0.0f) - , m_partialRayleighInScatteringConst(0.0f, 0.0f, 0.0f, 0.0f) - , m_sunDirection(0.0f, 0.0f, 0.0f, 0.0f) - , m_phaseFunctionConsts(0.0f, 0.0f, 0.0f, 0.0f) - , m_hazeColor(0.0f, 0.0f, 0.0f, 0.0f) - , m_hazeColorMieNoPremul(0.0f, 0.0f, 0.0f, 0.0f) - , m_hazeColorRayleighNoPremul(0.0f, 0.0f, 0.0f, 0.0f) - , m_skyColorTop(0.0f, 0.0f, 0.0f) - , m_skyColorNorth(0.0f, 0.0f, 0.0f) - , m_skyColorEast(0.0f, 0.0f, 0.0f) - , m_skyColorSouth(0.0f, 0.0f, 0.0f) - , m_skyColorWest(0.0f, 0.0f, 0.0f) - { - } - - // Sky dome mesh - _smart_ptr m_pSkyDomeMesh; - - // temporarily add padding bytes to prevent fetching Vec4 constants below from wrong offset - uint32 dummy0; - uint32 dummy1; - - // Sky dome texture data - const void* m_pSkyDomeTextureDataMie; - const void* m_pSkyDomeTextureDataRayleigh; - size_t m_skyDomeTexturePitch; - int m_skyDomeTextureTimeStamp; - - int pad;//Enable 16 byte alignment for Vec4s - - // Sky dome shader constants - Vec4 m_partialMieInScatteringConst; - Vec4 m_partialRayleighInScatteringConst; - Vec4 m_sunDirection; - Vec4 m_phaseFunctionConsts; - Vec4 m_hazeColor; - Vec4 m_hazeColorMieNoPremul; - Vec4 m_hazeColorRayleighNoPremul; - - // Sky hemisphere colors - Vec3 m_skyColorTop; - Vec3 m_skyColorNorth; - Vec3 m_skyColorEast; - Vec3 m_skyColorSouth; - Vec3 m_skyColorWest; -}; - -struct SVisAreaInfo -{ - float fHeight; - Vec3 vAmbientColor; - bool bAffectedByOutLights; - bool bIgnoreSkyColor; - bool bSkyOnly; - float fViewDistRatio; - bool bDoubleSide; - bool bUseDeepness; - bool bUseInIndoors; - bool bOceanIsVisible; - bool bIgnoreGI; - bool bIgnoreOutdoorAO; - float fPortalBlending; -}; - -struct SDebugFPSInfo -{ - SDebugFPSInfo() - : fAverageFPS(0.0f) - , fMaxFPS(0.0f) - , fMinFPS(0.0f) - { - } - float fAverageFPS; - float fMinFPS; - float fMaxFPS; -}; - -struct SRainParams -{ - SRainParams() - : fAmount(0.f) - , fCurrentAmount(0.f) - , fRadius(0.f) - , nUpdateFrameID(-1) - , bIgnoreVisareas(false) - , bDisableOcclusion(false) - , matOccTrans(IDENTITY) - , matOccTransRender(IDENTITY) - , qRainRotation(IDENTITY) - , areaAABB(AABB::RESET) - , bApplySkyColor(false) - , fSkyColorWeight(0.5f) - { - } - - Matrix44 matOccTrans; // Transformation matrix for rendering into a new occ map - Matrix44 matOccTransRender; // Transformation matrix for rendering occluded rain using current occ map - Quat qRainRotation; // Quaternion for the scene's rain entity rotation - AABB areaAABB; - - Vec3 vWorldPos; - Vec3 vColor; - - float fAmount; - float fCurrentAmount; - float fRadius; - - // Deferred rain params - float fFakeGlossiness; // unused - float fFakeReflectionAmount; // unused - float fDiffuseDarkening; - float fRainDropsAmount; - float fRainDropsSpeed; - float fRainDropsLighting; - float fMistAmount; - float fMistHeight; - float fPuddlesAmount; - float fPuddlesMaskAmount; - float fPuddlesRippleAmount; - float fSplashesAmount; - - int nUpdateFrameID; - - bool bApplyOcclusion; - bool bIgnoreVisareas; - bool bDisableOcclusion; - -// Summary: -// Common scene rain parameters shared across engine and editor - bool bApplySkyColor; - float fSkyColorWeight; - - // Bus ID to listen to -}; - -struct SSnowParams -{ - SSnowParams() - : m_vWorldPos(0, 0, 0) - , m_fRadius(0.0) - , m_fSnowAmount(0.0) - , m_fFrostAmount(0.0) - , m_fSurfaceFreezing(0.0) - , m_nSnowFlakeCount(0) - , m_fSnowFlakeSize(0.0) - , m_fSnowFallBrightness(0.0) - , m_fSnowFallGravityScale(0.0) - , m_fSnowFallWindScale(0.0) - , m_fSnowFallTurbulence(0.0) - , m_fSnowFallTurbulenceFreq(0.0) - { - } - - Vec3 m_vWorldPos; - float m_fRadius; - - // Surface params. - float m_fSnowAmount; - float m_fFrostAmount; - float m_fSurfaceFreezing; - - - // Snowfall params. - int m_nSnowFlakeCount; - float m_fSnowFlakeSize; - float m_fSnowFallBrightness; - float m_fSnowFallGravityScale; - float m_fSnowFallWindScale; - float m_fSnowFallTurbulence; - float m_fSnowFallTurbulenceFreq; -}; - - -struct IScreenshotCallback -{ - // - virtual ~IScreenshotCallback(){} - virtual void SendParameters(void* data, uint32 width, uint32 height, f32 minx, f32 miny, f32 maxx, f32 maxy) = 0; - // -}; - -class IStreamedObjectListener -{ -public: - // - virtual void OnCreatedStreamedObject(const char* filename, void* pHandle) = 0; - virtual void OnRequestedStreamedObject(void* pHandle) = 0; - virtual void OnReceivedStreamedObject(void* pHandle) = 0; - virtual void OnUnloadedStreamedObject(void* pHandle) = 0; - virtual void OnBegunUsingStreamedObjects(void** pHandles, size_t numHandles) = 0; - virtual void OnEndedUsingStreamedObjects(void** pHandles, size_t numHandles) = 0; - virtual void OnDestroyedStreamedObject(void* pHandle) = 0; - // -protected: - virtual ~IStreamedObjectListener() {} -}; - -#pragma pack(push, 16) - -struct SFogVolumeData -{ - AABB avgAABBox; - ColorF fogColor; - int m_volumeType; - Vec3 m_heightFallOffBasePoint; - float m_densityOffset; - Vec3 m_heightFallOffDirScaled; - float m_globalDensity; - - SFogVolumeData() : - avgAABBox(AABB::RESET), - m_globalDensity(0.0f), - m_densityOffset(0.0f), - m_volumeType(0), - m_heightFallOffBasePoint(Vec3(0, 0, 0)), - m_heightFallOffDirScaled(Vec3(0, 0, 0)), - fogColor(ColorF(1.0f, 1.0f, 1.0f, 1.0f)) - { - } - -}; - -// Summary: -// Light volumes data - -#define LIGHTVOLUME_MAXLIGHTS 16 - -struct SLightVolume -{ - struct SLightData - { - SLightData() - : vPos(0, 0, 0, 0) - , vColor(0, 0, 0, 0) - , vParams(0, 0, 0, 0) {} - SLightData(const Vec4& vInPos, const Vec4& vInColor, const Vec4& vInParams) - : vPos(vInPos) - , vColor(vInColor) - , vParams(vInParams) {} - - Vec4 vPos; - Vec4 vColor; - Vec4 vParams; - }; - - SLightVolume() - { - pData.reserve(LIGHTVOLUME_MAXLIGHTS); - } - - typedef DynArray LightDataVector; - - DEFINE_ALIGNED_DATA(LightDataVector, pData, 16); -}; - -#pragma pack(pop) - -struct CRNTmpData -{ - struct SRNUserData - { - int m_narrDrawFrames[MAX_RECURSION_LEVELS]; - SLodDistDissolveTransitionState lodDistDissolveTransitionState; - Matrix34 objMat; - OcclusionTestClient m_OcclState; - struct IClipVolume* m_pClipVolume; - SBending m_Bending; - SBending m_BendingPrev; - Vec3 vCurrentWind; - uint32 nBendingLastFrame : 29; - uint32 bWindCurrent : 1; - uint32 bBendingSet : 1; - uint16 nCubeMapId; - uint16 nCubeMapIdCacheClearCounter; - uint8 nWantedLod; - CRenderObject* m_pRenderObject[MAX_STATOBJ_LODS_NUM]; - CRenderObject* m_arrPermanentRenderObjects[MAX_STATOBJ_LODS_NUM]; - } userData; - - CRNTmpData() { memset(this, 0, sizeof(*this)); assert((void*)this == (void*)&this->userData); nPhysAreaChangedProxyId = ~0; } - CRNTmpData* pNext, * pPrev; - CRNTmpData** pOwnerRef; - uint32 nFrameInfoId; - uint32 nPhysAreaChangedProxyId; - - void Unlink() - { - if (!pNext || !pPrev) - { - return; - } - pNext->pPrev = pPrev; - pPrev->pNext = pNext; - pNext = pPrev = NULL; - } - - void Link(CRNTmpData* Before) - { - if (pNext || pPrev) - { - return; - } - pNext = Before->pNext; - Before->pNext->pPrev = this; - Before->pNext = this; - pPrev = Before; - } - - int Count() - { - int nCounter = 0; - for (CRNTmpData* pElem = pNext; pElem != this; pElem = pElem->pNext) - { - nCounter++; - } - return nCounter; - } - - void OffsetPosition(const Vec3& delta) - { - userData.objMat.SetTranslation(userData.objMat.GetTranslation() + delta); - } -}; - - -// Summary: -// Interface to the 3d Engine. -struct I3DEngine - : public IProcess -{ - struct SObjectsStreamingStatus - { - int nReady; - int nInProgress; - int nTotal; - int nActive; - int nAllocatedBytes; - int nMemRequired; - int nMeshPoolSize; // in MB - - }; - - struct OceanAnimationData - { - float fWindDirection; - float fWindSpeed; - float fWavesSpeed; - float fWavesAmount; - float fWavesSize; - float fWindDirectionU; - float fWindDirectionV; - }; - - struct SStremaingBandwidthData - { - SStremaingBandwidthData() - { - memset(this, 0, sizeof(SStremaingBandwidthData)); - } - float fBandwidthActual; - float fBandwidthRequested; - }; - - enum eStreamingSubsystem - { - eStreamingSubsystem_Textures, - eStreamingSubsystem_Objects, - eStreamingSubsystem_Audio, - }; - - using LoadStaticObjectAsyncResult = AZStd::function)>; - - struct StaticObjectAsyncLoadRequest - { - StaticObjectAsyncLoadRequest() = default; - - LoadStaticObjectAsyncResult m_callback; - string m_filename; - string m_geomName; - bool m_useStreaming; - unsigned long m_loadingFlags; - }; - - struct CausticsParams - { - float tiling = 0.0f; - float distanceAttenuation = 0.0f; - float height = 0.0f; - float depth = 0.0f; - float intensity = 0.0f; - }; - - - // - // Summary: - // Initializes the 3D Engine. - // See Also: - // ShutDown - // Notes: - // Only call once, after creating the instance. - virtual bool Init() = 0; - - - // Summary: - // Sets the path used to load levels. - // See Also: - // LoadLevel - // Arguments: - // szFolderName - Should contains the folder to be used - virtual void SetLevelPath(const char* szFolderName) = 0; - - virtual bool CheckMinSpec(uint32 nMinSpec) = 0; - - virtual void PrepareOcclusion(const CCamera& rCamera) = 0; - virtual void EndOcclusion() = 0; - // Description: - // Will load a level from the folder specified with SetLevelPath. If a - // level is already loaded, the resources will be deleted before. - // See Also: - // SetLevelPath - // Arguments: - // szFolderName - Name of the subfolder to load - // szMissionName - Name of the mission - // Return Value: - // A boolean which indicate the result of the function; true is - // succeed, or false if failed. - // Summary: - // Load a level. - virtual bool LoadLevel(const char* szFolderName, const char* szMissionName) = 0; - virtual bool InitLevelForEditor(const char* szFolderName, const char* szMissionName) = 0; - virtual bool LevelLoadingInProgress() = 0; - // Summary: - // Handles any work needed at start of new frame. - // Notes: - // Should be called for every frame. - virtual void OnFrameStart() = 0; - - // Description: - // Must be called after the game completely finishes loading the level. - // 3D engine uses it to pre-cache some resources needed for rendering. - // See Also: - // LoadLevel - // Summary: - // Pre-caches some resources need for rendering. - virtual void PostLoadLevel() = 0; - - // Description: - // Loads the required assets for a null level. - virtual void LoadEmptyLevel() = 0; - - // Summary: - // Clears all rendering resources, all objects, characters and materials, voxels and terrain. - // Notes: - // Should always be called before LoadLevel, and also before loading textures from a script. - virtual void UnloadLevel() = 0; - - - // Summary: - // Updates the 3D Engine. - // Notes: - // Should be called for every frame. - virtual void Update() = 0; - - // Summary: - // Returns the Camera used for Rendering on 3DEngine Side, normaly equal to the view camera, except if frozen with e_camerafreeze - // Notes: - // Only valid during RenderWorld(else the camera of the last frame is used) - // This is the camera which should be used for all Engine side culling (since e_camerafreeze allows easy debugging then) - virtual const CCamera& GetRenderingCamera() const = 0; - virtual float GetZoomFactor() const = 0; - - // Summary: - // clear all per frame temp data used in SRenderingPass - virtual void Tick() = 0; - - // Summary: - // Update all ShaderItems flags, only required after shaders were reloaded at runtime - virtual void UpdateShaderItems() = 0; - - // Summary: - // Deletes the 3D Engine instance. - virtual void Release() = 0; - - // Summary: - // Draws the world. - // See Also: - // SetCamera - // Arguments: - // szDebugName - name that can be visualized for debugging purpose, must not be 0 - virtual void RenderWorld(int nRenderFlags, const SRenderingPassInfo& passInfo, const char* szDebugName) = 0; - - virtual void RenderSceneReflection(int nRenderFlags, const SRenderingPassInfo& passInfo) = 0; - - // Summary: - // Prepares for the world stream update, should be called before rendering - virtual void PreWorldStreamUpdate(const CCamera& cam) = 0; - - // Summary: - // Performs the actual world streaming update. PreWorldStreamUpdate must be called before - virtual void WorldStreamUpdate() = 0; - - // Summary: - // Shuts down the 3D Engine. - virtual void ShutDown() = 0; - - // Summary: - // Loads a static object from a CGF file. Does not increment the static object's reference counter. The reference returned is not guaranteed to be valid when run outside the main thread. Best used for priming the cache - // See Also: - // IStatObj - // Arguments: - // fileName - CGF Filename - should not be 0 or "" - // geomName - Optional name of geometry inside CGF. - // subObject - [Out]Optional Out parameter,Pointer to the - // loadingFlags - Zero or a bitwise combination of the flags from ELoadingFlags, defined in IMaterial.h, under the interface IMaterialManager. - // data - Raw buffer contain CGF data. - // dataSize - Size of the raw data buffer. - // Return Value: - // A pointer to an object derived from IStatObj. - virtual IStatObj* LoadStatObjUnsafeManualRef(const char* fileName, const char* geomName = nullptr, /*[Out]*/ IStatObj::SSubObject** subObject = nullptr, - bool useStreaming = true, unsigned long loadingFlags = 0, const void* data = nullptr, int dataSize = 0) = 0; - - // Summary: - // Loads a static object from a CGF file. Increments the static object's reference counter. This method is threadsafe. Not suitable for preloading - // See Also: - // IStatObj - // Arguments: - // fileName - CGF Filename - should not be 0 or "", even if data is provided. - // geomName - Optional name of geometry inside CGF. - // subObject - [Out]Optional Out parameter,Pointer to the - // loadingFlags - Zero or a bitwise combination of the flags from ELoadingFlags, defined in IMaterial.h, under the interface IMaterialManager. - // data - Raw buffer contain CGF data. - // dataSize - Size of the raw data buffer. - // Return Value: - // A smart pointer to an object derived from IStatObj. - virtual _smart_ptr LoadStatObjAutoRef(const char* fileName, const char* geomName = nullptr, /*[Out]*/ IStatObj::SSubObject** subObject = nullptr, - bool useStreaming = true, unsigned long loadingFlags = 0, const void* data = nullptr, int dataSize = 0) = 0; - - // Summary: - // Flushes queued async mesh loads. - virtual void ProcessAsyncStaticObjectLoadRequests() = 0; - - // Summary: - // Loads a static object from a CGF file asynchronously and invokes a callback on completion. - // Actual load will occur on the main thread. - // See Also: - // IStatObj - // Arguments: - // callback - The user callback to invoke on completion. - // szFileName - CGF Filename - should not be 0 or "" - // szGeomName - Optional name of geometry inside CGF. - // ppSubObject - [Out]Optional Out parameter,Pointer to the - // nLoadingFlags - Zero or a bitwise combination of the flags from ELoadingFlags, - // defined in IMaterial.h, under the interface IMaterialManager. - // Return Value: - // None - virtual void LoadStatObjAsync(LoadStaticObjectAsyncResult resultCallback, const char* szFileName, const char* szGeomName = nullptr, bool bUseStreaming = true, unsigned long nLoadingFlags = 0) = 0; - - // Summary: - // Finds a static object created from the given filename - // See Also: - // IStatObj - // Arguments: - // szFileName - CGF Filename - should not be 0 or "" - // Return Value: - // A pointer to an object derived from IStatObj. - virtual IStatObj* FindStatObjectByFilename(const char* filename) = 0; - - // Summary: - // Gets gsm range - // Return Value: - // An integer representing the gsm range. - virtual const float GetGSMRange() = 0; - - // Summary: - // Gets gsm range step - // Return Value: - // An integer representing the gsm range step - virtual const float GetGSMRangeStep() = 0; - - // Summary: - // Gets the amount of loaded objects. - // Return Value: - // An integer representing the amount of loaded objects. - virtual int GetLoadedObjectCount() { return 0; } - - // Summary: - // Fills pObjectsArray with pointers to loaded static objects - // if pObjectsArray is NULL only fills nCount parameter with amount of loaded objects. - virtual void GetLoadedStatObjArray(IStatObj** pObjectsArray, int& nCount) = 0; - - // Summary: - // Gets stats on streamed objects - virtual void GetObjectsStreamingStatus(SObjectsStreamingStatus& outStatus) = 0; - - // Summary: - // Gets stats on the streaming bandwidth requests from subsystems - // Arguments: - // subsystem - the streaming subsystem we want bandwidth data for - // outData - structure containing the bandwidth data for the subsystem requested - virtual void GetStreamingSubsystemData(int subsystem, SStremaingBandwidthData& outData) = 0; - - // Summary: - // Registers an entity to be rendered. - // Arguments: - // pEntity - The entity to render - virtual void RegisterEntity(IRenderNode* pEntity, int nSID = -1, int nSIDConsideredSafe = -1) = 0; - - // Summary: - // Selects an entity for debugging. - // Arguments: - // pEntity - The entity to render - virtual void SelectEntity(IRenderNode* pEntity) = 0; - - ////////////////////////////////////////////// - // Start Confetti ////////////////////////// - // Summary: - // Return the setting for sun shadows. Return false for sub classes without sun shadows settings. - virtual bool IsSunShadows(){ return false; }; - // End Confetti////////////////////////////// - ////////////////////////////////////////////// - - // Summary: - // Offers same functionality as Cry3DEngineBase::MakeSystemMaterialFromShader - virtual _smart_ptr MakeSystemMaterialFromShaderHelper(const char* sShaderName, SInputShaderResources* Res = NULL) = 0; - - virtual bool CheckMinSpecHelper(uint32 nMinSpec) = 0; - - virtual void OnCasterDeleted(IShadowCaster* pCaster) = 0; - - virtual void GetStatObjAndMatTables(DynArray* pStatObjTable, DynArray<_smart_ptr>* pMatTable, DynArray* pStatInstGroupTable, uint32 nObjTypeMask) = 0; - -#ifndef _RELEASE - enum EDebugDrawListAssetTypes - { - DLOT_ALL = 0, - DLOT_CHARACTER = BIT(2), - DLOT_STATOBJ = BIT(3) - }; - - struct SObjectInfoToAddToDebugDrawList - { - const char* pName; - const char* pClassName; - const char* pFileName; - IRenderNode* pRenderNode; - uint32 numTris; - uint32 numVerts; - uint32 texMemory; - uint32 meshMemory; - EDebugDrawListAssetTypes type; - const AABB* pBox; - const Matrix34* pMat; - }; - - virtual void AddObjToDebugDrawList(SObjectInfoToAddToDebugDrawList& objInfo) = 0; - virtual bool IsDebugDrawListEnabled() const = 0; -#endif - - - // Summary: - // Notices the 3D Engine to stop rendering a specified entity. - // Arguments: - // pEntity - The entity to stop render - virtual void UnRegisterEntityDirect(IRenderNode* pEntity) = 0; - virtual void UnRegisterEntityAsJob(IRenderNode* pEnt) = 0; - // Summary: - // Returns whether a world pos is under water. - virtual bool IsUnderWater(const Vec3& vPos) const = 0; - - // Summary: - // Returns whether ocean volume is visible or not. - virtual void SetOceanRenderFlags(uint8 nFlags) = 0; - virtual uint8 GetOceanRenderFlags() const = 0; - virtual uint32 GetOceanVisiblePixelsCount() const = 0; - - // Summary: - // Gets the closest walkable bottom z straight beneath the given reference position. - // Notes: - // This function will take into account both the global terrain elevation and local voxel (or other solid walkable object). - // Arguments: - // referencePos - Position from where to start searching downwards. - // maxRelevantDepth - Max depth caller is interested in relative to referencePos (for ray casting performance reasons). - // objtypes - expects physics entity flags. Use this to specify what object types make a valid bottom for you. - // Return Value: - // A float value which indicate the global world z of the bottom level beneath the referencePos. - // If the referencePos is below terrain but not inside any voxel area BOTTOM_LEVEL_UNKNOWN is returned. - virtual float GetBottomLevel(const Vec3& referencePos, float maxRelevantDepth, int objtypes) = 0; - // A set of overloads for enabling users to use different sets of input params. Basically, only - // referencePos is mandatory. The overloads as such don't need to be virtual but this seems to be - // a purely virtual interface. - virtual float GetBottomLevel(const Vec3& referencePos, float maxRelevantDepth = 10.0f) = 0; - virtual float GetBottomLevel(const Vec3& referencePos, int objflags) = 0; - - // Summary: - // Gets the ocean water level. Fastest option, always prefer is only ocean height required. - // Notes: - // This function will take into account just the global water level. - // Return Value: - // A float value which indicate the water level. In case no water was - // found at the specified location, the value WATER_LEVEL_UNKNOWN will - // be returned. - virtual float GetWaterLevel() = 0; - - // Summary: - // Gets the closest walkable bottom z straight beneath the given reference position. - // - Use with caution the accurate query - SLOW - // Notes: - // This function will take into account both the global water level and any water volume present. - // Function is provided twice for performance with diff. arguments. - // Arguments: - // pvPos - Desired position to inspect the water level - // pent - Pointer to return the physical entity to test against (optional) - // Return Value: - // A float value which indicate the water level. In case no water was - // found at the specified location, the value WATER_LEVEL_UNKNOWN will - // be returned. - virtual float GetWaterLevel(const Vec3* pvPos, IPhysicalEntity* pent = NULL, bool bAccurate = false) = 0; - - // Summary: - // Gets the ocean water level for a specified position. - // - Use with caution the accurate query - SLOW - // Notes: - // This function only takes into account ocean water. - // Arguments: - // pCurrPos - Position to check water level - // Return Value: - // A float value which indicate the water level. - virtual float GetAccurateOceanHeight(const Vec3& pCurrPos) const = 0; - - // Summary: - // Gets caustics parameters. - virtual CausticsParams GetCausticsParams() const = 0; - - // Summary: - // Gets ocean animation parameters. - virtual OceanAnimationData GetOceanAnimationParams() const = 0; - - // Summary: - // Gets HDR setup parameters. - // Return Value: - virtual void GetHDRSetupParams (Vec4 pParams[5]) const = 0; - - // Summary: - // Removes all particles and decals from the world. - virtual void ResetParticlesAndDecals() = 0; - - // Summary: - // Creates new decals on the walls, static objects, terrain and entities. - // Arguments: - // Decal - Structure describing the decal effect to be applied - virtual void CreateDecal(const CryEngineDecalInfo& Decal) = 0; - - // Summary: - // Removes decals in a specified range. - // Arguments: - // vAreaBox - Specify the area in which the decals will be removed - // pEntity - if not NULL will only delete decals attached to this entity - virtual void DeleteDecalsInRange(AABB* pAreaBox, IRenderNode* pEntity) = 0; - - // Summary: - // Sets the current sun base color. - virtual void SetSunColor(Vec3 vColor) = 0; - - // Summary: - // Gets the current sun animated color. - virtual Vec3 GetSunAnimColor() = 0; - - // Summary: - // Sets the current sky brightening multiplier. - virtual void SetSunAnimColor(const Vec3& color) = 0; - - // Summary: - // Sets the current sun animation speed. - virtual float GetSunAnimSpeed() = 0; - - // Summary: - virtual void SetSunAnimSpeed(float sunAnimSpeed) = 0; - - // Summary: - // Gets the current sun animation phase. - virtual AZ::u8 GetSunAnimPhase() = 0; - // Summary: - // Sets the current sun animation phase. - virtual void SetSunAnimPhase(AZ::u8 sunAnimPhase) = 0; - - // Summary: - // Gets the current sun animation index. - virtual AZ::u8 GetSunAnimIndex() = 0; - - // Summary: - // Sets the current sun animation index. - virtual void SetSunAnimIndex(AZ::u8 sunAnimIndex) = 0; - - // Summary: - // Sets current rain parameters. - virtual void SetRainParams(const SRainParams& rainParams) = 0; - - // Summary: - // Gets the validity and fills current rain parameters. - virtual bool GetRainParams(SRainParams& rainParams) = 0; - - // Summary: - // Sets current snow surface parameters. - virtual void SetSnowSurfaceParams(const Vec3& vCenter, float fRadius, float fSnowAmount, float fFrostAmount, float fSurfaceFreezing) = 0; - - // Summary: - // Gets current snow surface parameters. - virtual bool GetSnowSurfaceParams(Vec3& vCenter, float& fRadius, float& fSnowAmount, float& fFrostAmount, float& fSurfaceFreezing) = 0; - - // Summary: - // Sets current snow parameters. - virtual void SetSnowFallParams(int nSnowFlakeCount, float fSnowFlakeSize, float fSnowFallBrightness, float fSnowFallGravityScale, float fSnowFallWindScale, float fSnowFallTurbulence, float fSnowFallTurbulenceFreq) = 0; - - // Summary: - // Gets current snow parameters. - virtual bool GetSnowFallParams(int& nSnowFlakeCount, float& fSnowFlakeSize, float& fSnowFallBrightness, float& fSnowFallGravityScale, float& fSnowFallWindScale, float& fSnowFallTurbulence, float& fSnowFallTurbulenceFreq) = 0; - - // Summary: - // Sets the view distance scale. - // Arguments: - // fScale - may be between 0 and 1, 1.f = Unmodified view distance set by level designer, value of 0.5 will reduce it twice - // Notes: - // This value will be reset automatically to 1 on next level loading. - virtual void SetMaxViewDistanceScale(float fScale) = 0; - - // Summary: - // Gets the view distance. - // Return Value: - // A float value representing the maximum view distance. - virtual float GetMaxViewDistance(bool bScaled = true) = 0; - - virtual const SFrameLodInfo& GetFrameLodInfo() const = 0; - virtual void SetFrameLodInfo(const SFrameLodInfo& frameLodInfo) = 0; - - // Summary: - // Sets the fog color. - virtual void SetFogColor(const Vec3& vFogColor) = 0; - - // Summary: - // Gets the fog color. - virtual Vec3 GetFogColor() = 0; - - // Summary: - // Gets various sky light parameters. - virtual void GetSkyLightParameters(Vec3& sunDir, Vec3& sunIntensity, float& Km, float& Kr, float& g, Vec3& rgbWaveLengths) = 0; - - // Summary: - // Sets various sky light parameters. - virtual void SetSkyLightParameters(const Vec3& sunDir, const Vec3& sunIntensity, float Km, float Kr, float g, const Vec3& rgbWaveLengths, bool forceImmediateUpdate = false) = 0; - - // Return Value: - // In logarithmic scale -4.0 .. 4.0 - virtual float GetLightsHDRDynamicPowerFactor() const = 0; - - // Return true if tessellation is allowed for given render object - virtual bool IsTessellationAllowed(const CRenderObject* pObj, const SRenderingPassInfo& passInfo, bool bIgnoreShadowPass = false) const = 0; - - // allows to modify material on render nodes at run-time (make sure it is properly restored back) - virtual void SetRenderNodeMaterialAtPosition(EERType eNodeType, const Vec3& vPos, _smart_ptr pMat) = 0; - - // override the camera precache point with the requested position for the current round - virtual void OverrideCameraPrecachePoint(const Vec3& vPos) = 0; - - // begin streaming of meshes and textures for specified position, pre-cache stops after fTimeOut seconds - virtual int AddPrecachePoint(const Vec3& vPos, const Vec3& vDir, float fTimeOut = 3.f, float fImportanceFactor = 1.0f) = 0; - virtual void ClearPrecachePoint(int id) = 0; - virtual void ClearAllPrecachePoints() = 0; - - virtual void GetPrecacheRoundIds(int pRoundIds[MAX_STREAM_PREDICTION_ZONES]) = 0; - - virtual void TraceFogVolumes(const Vec3& vPos, const AABB& objBBox, SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo, bool fogVolumeShadingQuality) = 0; - - //DOC-IGNORE-BEGIN - - // Internal functions, mostly used by the editor, which won't be documented for now - - // Summary: - // Removes all static objects on the map (for editor) - virtual void RemoveAllStaticObjects(int nSID = DEFAULT_SID) = 0; - - // Summary: - // Sets group parameters - virtual bool SetStatInstGroup(int nGroupId, const IStatInstGroup& siGroup, int nSID = 0) = 0; - - // Summary: - // Gets group parameters - virtual bool GetStatInstGroup(int nGroupId, IStatInstGroup& siGroup, int nSID = 0) = 0; - - //DOC-IGNORE-END - - // Summary: - // Notifies of an explosion, and maybe creates an hole in the terrain - // Description: - // This function should usually make sure that no static objects are near before making the hole. - // Arguments: - // vPos - Position of the explosion - // fRadius - Radius of the explosion - // bDeformTerrain - Allow to deform the terrain - virtual void OnExplosion(Vec3 vPos, float fRadius, bool bDeformTerrain = true) = 0; - - // Summary: - // Sets the physics material enumerator - // Arguments: - // pPhysMaterialEnumerator - The physics material enumarator to set - virtual void SetPhysMaterialEnumerator(IPhysMaterialEnumerator* pPhysMaterialEnumerator) = 0; - - // Summary: - // Gets the physics material enumerator - // Return Value: - // A pointer to an IPhysMaterialEnumerator derived object. - virtual IPhysMaterialEnumerator* GetPhysMaterialEnumerator() = 0; - - //DOC-IGNORE-BEGIN - //Internal functions - - // Summary: - // Allows to enable fog in editor - virtual void SetupDistanceFog() = 0; - - // Summary: - // Loads environment settings for specified mission - virtual void LoadMissionDataFromXMLNode(const char* szMissionName) = 0; - - virtual void LoadEnvironmentSettingsFromXML(XmlNodeRef pInputNode, int nSID = DEFAULT_SID) = 0; - - // Summary: - // This one is called by the editor when the terrain editing tools are not being built. - // This is the case when the game developers are using external tools to author terrain. - // The Octree data and the terrain heightmap data are stored in the same file. - // This method makes sure only the non-terrain data of the Octree is loaded. - virtual bool LoadCompiledOctreeForEditor() = 0; - - //DOC-IGNORE-END - - //DOC-IGNORE-BEGIN - // Set direction to the sun - // virtual void SetSunDir( const Vec3& vNewSunDir ) = 0; - - // Summary: - // Return non-normalized direction to the sun - virtual Vec3 GetSunDir() const = 0; - - // Summary: - // Return normalized direction to the sun - virtual Vec3 GetSunDirNormalized() const = 0; - - // Summary: - // Return realtime (updated every frame with real sun position) normalized direction to the scene - virtual Vec3 GetRealtimeSunDirNormalized() const = 0; - - //Internal function used by 3d engine and renderer - // Summary: - // Gets distance to the sector containig ocean water - virtual float GetDistanceToSectorWithWater() = 0; - //DOC-IGNORE-END - - // Summary: - // Gets the sun color - // Notes: - // Should have been specified in the editor. - // Return Value: - // An rgb value contained in a Vec3 object. - virtual Vec3 GetSunColor() const = 0; - - // Summary: - // Retrieves the current SSAO multiplier - // Notes: - // Return Value: - // scalar value - virtual float GetSSAOAmount() const = 0; - - // Summary: - // Retrieves the current SSAO contrast multiplier - // Notes: - // Return Value: - // scalar value - virtual float GetSSAOContrast() const = 0; - // Summary: - // Frees entity render info. - virtual void FreeRenderNodeState(IRenderNode* pEntity) = 0; - - // Summary: - // Adds the level's path to a specified filename. - // Arguments: - // szFileName - The filename for which we need to add the path - // Return Value: - // Full path for the filename; including the level path and the filename appended after. - virtual const char* GetLevelFilePath(const char* szFileName) = 0; - - // Summary: - // Displays statistic on the 3d Engine. - // Arguments: - // fTextPosX - X position for the text - // fTextPosY - Y position for the text - // fTextStepY - Amount of pixels to distance each line - // bEnhanced - false=normal, true=more interesting information - virtual void DisplayInfo(float& fTextPosX, float& fTextPosY, float& fTextStepY, bool bEnhanced) = 0; - - // Summary: - // Displays CPU and GPU memory usage statistics on screen - virtual void DisplayMemoryStatistics() = 0; - - // Summary: - // Draws text right aligned at the y pixel precision. - virtual void DrawTextRightAligned(const float x, const float y, const char* format, ...) PRINTF_PARAMS(4, 5) = 0; - virtual void DrawTextRightAligned(const float x, const float y, const float scale, const ColorF& color, const char* format, ...) PRINTF_PARAMS(6, 7) = 0; - - virtual void DrawBBoxHelper(const Vec3& vMin, const Vec3& vMax, ColorB col = Col_White) = 0; - virtual void DrawBBoxHelper(const AABB& box, ColorB col = Col_White) = 0; - - // Summary: - // Enables or disables portal at a specified position. - // Arguments: - // vPos - Position to place the portal - // bActivate - Set to true in order to enable the portal, or to false to disable - // szEntityName - - virtual void ActivatePortal(const Vec3& vPos, bool bActivate, const char* szEntityName) = 0; - - //DOC-IGNORE-BEGIN - // Summary: - // Counts memory usage - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - // Summary: - // Counts resource memory usage - // Arguments: - // cstAABB - Use the whole level AABB if you want to grab the resources - // from the whole level. For height level, use something BIG - // (ie: +-FLT_MAX) - virtual void GetResourceMemoryUsage(ICrySizer* pSizer, const AABB& cstAABB) = 0; - //DOC-IGNORE-END - - // Summary: - // Creates a new VisArea. - // Return Value: - // A pointer to a newly created VisArea object - virtual IVisArea* CreateVisArea(uint64 visGUID) = 0; - - // Summary: - // Deletes a VisArea. - // Arguments: - // pVisArea - A pointer to the VisArea to delete - virtual void DeleteVisArea(IVisArea* pVisArea) = 0; - - //mat: todo - - // Summary: - // Updates the VisArea - // Arguments: - // pArea - - // pPoints - - // nCount - - // szName - - // info - - // bReregisterObjects - - virtual void UpdateVisArea(IVisArea* pArea, const Vec3* pPoints, int nCount, const char* szName, const SVisAreaInfo& info, bool bReregisterObjects) = 0; - - // Summary: - // Determines if two VisAreas are connected. - // Description: - // Used to determine if a sound is potentially hearable between two VisAreas. - // Arguments: - // pArea1 - A pointer to a VisArea - // pArea2 - A pointer to a VisArea - // nMaxRecursion - Maximum number of recursions to be done - // bSkipDisabledPortals - Indicate if disabled portals should be skipped - // Return Value: - // A boolean value set to true if the two VisAreas are connected, else false will be returned. - virtual bool IsVisAreasConnected(IVisArea* pArea1, IVisArea* pArea2, int nMaxRecursion = 1, bool bSkipDisabledPortals = true) = 0; - - // Summary: - // Creates a ClipVolume. - // Return Value: - // A pointer to a newly created ClipVolume object - virtual IClipVolume* CreateClipVolume() = 0; - - // Summary: - // Deletes a ClipVolume. - // Arguments: - // pClipVolume - A pointer to the ClipVolume to delete - virtual void DeleteClipVolume(IClipVolume* pClipVolume) = 0; - - // Summary: - // Updates a ClipVolume - // Arguments: - // pClipVolume - Pointer to volume that needs updating - // pRenderMesh - Pointer to new render mesh - // worldTM - Updated world transform - // szName - Updated ClipVolume name - virtual void UpdateClipVolume(IClipVolume* pClipVolume, _smart_ptr pRenderMesh, IBSPTree3D* pBspTree, const Matrix34& worldTM, bool bActive, uint32 flags, const char* szName) = 0; - - //mat: todo - - // Summary: - // Creates instance of IRenderNode object with specified type. - virtual IRenderNode* CreateRenderNode(EERType type) = 0; - - // Summary: - // Delete RenderNode object. - virtual void DeleteRenderNode(IRenderNode* pRenderNode) = 0; - - - // Summary: - // Gets wind direction and force, averaged within a box. - virtual Vec3 GetWind(const AABB& box, bool bIndoors) const = 0; - - // Summary: - // Gets the global wind vector. - virtual Vec3 GetGlobalWind(bool bIndoors) const = 0; - - // Summary: - // Gets wind direction and forace at the sample points provided. - // Note: the positions defining the samples will be overwritten - // with the accumulated wind influences. - virtual bool SampleWind(Vec3* pSamples, int nSamples, const AABB& volume, bool bIndoors) const = 0; - - // Description: - // Gets the VisArea which is present at a specified point. - // Arguments: - // vPos: - // Return Value: - // VisArea containing point, if any. 0 otherwise. - virtual IVisArea* GetVisAreaFromPos(const Vec3& vPos) = 0; - - // Description: - // Tests for intersection against Vis Areas. - // Arguments: - // box: Volume to test for intersection. - // pNodeCache (out, optional): Set to a cached pointer, for quicker calls to ClipToVisAreas. - // Return Value: - // Whether box intersects any vis areas. - virtual bool IntersectsVisAreas(const AABB& box, void** pNodeCache = 0) = 0; - - // Description: - // Clips geometry against the boundaries of VisAreas. - // Arguments: - // pInside: Vis Area to clip inside of. If 0, clip outside all Vis Areas. - // sphere - - // vNormal - - // pNodeChache - - // Return Value: - // Whether it was clipped - virtual bool ClipToVisAreas(IVisArea* pInside, Sphere& sphere, Vec3 const& vNormal, void* pNodeCache = 0) = 0; - - // Summary: - // Enables or disables ocean rendering. - // Arguments: - // bOcean - Will enable or disable the rendering of ocean - virtual void EnableOceanRendering(bool bOcean) = 0; - - // Description: - // Register a texture load handler - virtual void AddTextureLoadHandler(ITextureLoadHandler* pHandler) = 0; - - // Description - // Unregister a texture load handler - virtual void RemoveTextureLoadHandler(ITextureLoadHandler* pHandler) = 0; - - // Description: - // Get a texture load handler for a given extension - virtual ITextureLoadHandler* GetTextureLoadHandlerForImage(const char* ext) = 0; - // Summary: - // Creates a new light source. - // Return Value: - // Pointer to newly created light or -1 if it fails. - virtual struct ILightSource* CreateLightSource() = 0; - - // Summary: - // Deletes a light. - // Arguments: - // Pointer to the light - virtual void DeleteLightSource(ILightSource* pLightSource) = 0; - - // Summary: - // Gives access to the list holding all static light sources - // Return Value: - // An array holding all the CDLight pointers. - virtual const PodArray* GetLightEntities() = 0; - - // Summary: - // Gives access to list holding all lighting volumes - // Return Value: - // An array holding all the SLightVolume pointers. - virtual void GetLightVolumes(threadID nThreadID, SLightVolume*& pLightVols, uint32& nNumVols) = 0; - - // Summary: - // Registers a volume for lighting - // Return Value: - // The index of the registered volume. - virtual uint16 RegisterVolumeForLighting(const Vec3& vPos, f32 fRadius, uint8 nClipVolumeRef, const SRenderingPassInfo& passInfo) = 0; - - // Summary: - // Reload the heightmap. - // Description: - // Reloading the heightmap will resets all decals and particles. - // Notes: - // In future will restore deleted vegetations - // Returns: - // success - virtual bool RestoreTerrainFromDisk(int nSID = 0) = 0; - - //DOC-IGNORE-BEGIN - // tmp - virtual const char* GetFilePath(const char* szFileName) { return GetLevelFilePath(szFileName); } - //DOC-IGNORE-END - - // Summary: - // Post processing effects interfaces. - virtual class IPostEffectGroupManager* GetPostEffectGroups() const = 0; - virtual class IPostEffectGroup* GetPostEffectBaseGroup() const = 0; - - // Most code should use either GetPostEffectGroups() or GetPostEffectBaseGroup() instead of these - virtual void SetPostEffectParam(const char* pParam, float fValue, bool bForceValue = false) const = 0; - virtual void SetPostEffectParamVec4(const char* pParam, const Vec4& pValue, bool bForceValue = false) const = 0; - virtual void SetPostEffectParamString(const char* pParam, const char* pszArg) const = 0; - - virtual void GetPostEffectParam(const char* pParam, float& fValue) const = 0; - virtual void GetPostEffectParamVec4(const char* pParam, Vec4& pValue) const = 0; - virtual void GetPostEffectParamString(const char* pParam, const char*& pszArg) const = 0; - - virtual int32 GetPostEffectID(const char* pPostEffectName) = 0; - - virtual void ResetPostEffects(bool bOnSpecChange = false) = 0; - //Disable post effect groups other than default and base. - virtual void DisablePostEffects() = 0; - - virtual void SetShadowsGSMCache(bool bCache) = 0; - virtual void SetCachedShadowBounds(const AABB& shadowBounds, float fAdditionalCascadesScale) = 0; - virtual void SetRecomputeCachedShadows(uint nUpdateStrategy = 0) = 0; - - // Summary: - // In debug mode check memory heap and makes assert, do nothing in release - virtual void CheckMemoryHeap() = 0; - - // Summary: - // Removes all decals attached to specified entity. - virtual void DeleteEntityDecals(IRenderNode* pEntity) = 0; - - // Summary: - // Disables CGFs unloading. - virtual void LockCGFResources() = 0; - - // Summary: - // Enables CGFs unloading (this is default state), this function will also release all not used CGF's. - virtual void UnlockCGFResources() = 0; - - // Summary: - // Release all unused CGFs. - virtual void FreeUnusedCGFResources() = 0; - - - // Summary: - // Creates static object containing empty IndexedMesh. - virtual IStatObj* CreateStatObj() = 0; - virtual IStatObj* CreateStatObjOptionalIndexedMesh(bool createIndexedMesh) = 0; - - // Summary: - // Creates the instance of the indexed mesh. - virtual IIndexedMesh* CreateIndexedMesh() = 0; - - // Summary: - // Saves/loads state of engine objects. - virtual void SerializeState(TSerialize ser) = 0; - - // Summary: - // Cleanups after save/load. - virtual void PostSerialize(bool bReading) = 0; - - // Description: - // Retrieve pointer to the material i/o interface. - virtual IMaterialHelpers& GetMaterialHelpers() = 0; - - // Description: - // Retrieve pointer to the material manager interface. - virtual IMaterialManager* GetMaterialManager() = 0; - - // Description: - // Retrieve pointer to the object manager interface. - virtual IObjManager* GetObjManager() = 0; - - ////////////////////////////////////////////////////////////////////////// - // CGF Loader. - ////////////////////////////////////////////////////////////////////////// - // Description: - // Creates a chunkfile content instance - // Returns 'NULL' if the memory for the instance could not be allocated - virtual CContentCGF* CreateChunkfileContent(const char* filename) = 0; - - // Description: - // Deletes the chunkfile content instance - virtual void ReleaseChunkfileContent(CContentCGF*) = 0; - - // Description: - // Loads the contents of a chunkfile into the given CContentCGF. - // Returns 'false' on error. - virtual bool LoadChunkFileContent(CContentCGF* pCGF, const char* filename, bool bNoWarningMode = false, bool bCopyChunkFile = true) = 0; - - // Description: - // Loads the contents of a chunkfile into the given CContentCGF. - // Returns 'false' on error. - virtual bool LoadChunkFileContentFromMem(CContentCGF* pCGF, const void* pData, size_t nDataLen, uint32 nLoadingFlags, bool bNoWarningMode = false, bool bCopyChunkFile = true) = 0; - - // Description: - // Creates ChunkFile. - virtual IChunkFile* CreateChunkFile(bool bReadOnly = false) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Chunk file writer. - ////////////////////////////////////////////////////////////////////////// - enum EChunkFileFormat - { - eChunkFileFormat_0x745, - eChunkFileFormat_0x746, - }; - virtual ChunkFile::IChunkFileWriter* CreateChunkFileWriter(EChunkFileFormat eFormat, AZ::IO::IArchive* pPak, const char* filename) const = 0; - virtual void ReleaseChunkFileWriter(ChunkFile::IChunkFileWriter* p) const = 0; - - // Description: - // Returns true if the ocean was created successfully. - virtual bool CreateOcean(_smart_ptr pTerrainWaterMat, float waterLevel) = 0; - - // Description: - // Deletes the ocean if it exists, otherwise does nothing. - virtual void DeleteOcean() = 0; - - // Description: - // Changes ocean material if the ocean exists. - virtual void ChangeOceanMaterial(_smart_ptr pMat) = 0; - - // Description: - // Changes ocean water level if the ocean exists. - virtual void ChangeOceanWaterLevel(float fWaterLevel) = 0; - - virtual void InitMaterialDefautMappingAxis(_smart_ptr pMat) = 0; - - // Description: - // Returns interface to visarea manager. - virtual IVisAreaManager* GetIVisAreaManager() = 0; - - // Description: - // Places camera into every visarea or every manually set pre-cache points and render the scenes. - virtual void PrecacheLevel(bool bPrecacheAllVisAreas, Vec3* pPrecachePoints, int nPrecachePointsNum) = 0; - - // Description: - // Proposes 3dengine to load on next frame all shaders and textures synchronously. - virtual void ProposeContentPrecache() = 0; - - - - // Description: - // Returns TOD interface. - virtual ITimeOfDay* GetTimeOfDay() = 0; - - // Description: - // Updates the sky material paths. LoadSkyMaterial will handle loading these materials. - virtual void SetSkyMaterialPath(const string& skyMaterialPath) = 0; - virtual void SetSkyLowSpecMaterialPath(const string& skyMaterialPath) = 0; - - // Description: - // Loads the sky material for the level. e_SkyType will determine if we load the low spec sky material or the regular sky material. - virtual void LoadSkyMaterial() = 0; - - // Description: - // Returns SkyBox material. - virtual _smart_ptr GetSkyMaterial() = 0; - - // Description: - // Sets SkyBox Material. - virtual void SetSkyMaterial(_smart_ptr pSkyMat) = 0; - - // Description: - // Sets global 3d engine parameter. - virtual void SetGlobalParameter(E3DEngineParameter param, const Vec3& v) = 0; - void SetGlobalParameter(E3DEngineParameter param, float val) { SetGlobalParameter(param, Vec3(val, 0, 0)); }; - - // Description: - // Retrieves global 3d engine parameter. - virtual void GetGlobalParameter(E3DEngineParameter param, Vec3& v) = 0; - float GetGlobalParameter(E3DEngineParameter param) { Vec3 v(0, 0, 0); GetGlobalParameter(param, v); return v.x; }; - - virtual void SetShadowMode(EShadowMode shadowMode) = 0; - virtual EShadowMode GetShadowMode() const = 0; - virtual void AddPerObjectShadow(IShadowCaster* pCaster, float fConstBias, float fSlopeBias, float fJitter, const Vec3& vBBoxScale, uint nTexSize) = 0; - virtual void RemovePerObjectShadow(IShadowCaster* pCaster) = 0; - virtual struct SPerObjectShadow* GetPerObjectShadow(IShadowCaster* pCaster) = 0; - virtual void GetCustomShadowMapFrustums(struct ShadowMapFrustum*& arrFrustums, int& nFrustumCount) = 0; - - // Description: - // Saves pStatObj to a stream. - // Notes: - // Full mesh for generated ones, path/geom otherwise - virtual int SaveStatObj(IStatObj* pStatObj, TSerialize ser) = 0; - // Description: - // Loads statobj from a stream - virtual IStatObj* LoadStatObj(TSerialize ser) = 0; - - // Description: - // Returns true if input line segment intersect clouds sprites. - virtual bool CheckIntersectClouds(const Vec3& p1, const Vec3& p2) = 0; - - // Description: - // Removes references to RenderMesh - virtual void OnRenderMeshDeleted(IRenderMesh* pRenderMesh) = 0; - - // Used to highlight an object under the reticule - virtual void DebugDraw_UpdateDebugNode() = 0; - - // Description: - // Used by editor during AO computations - virtual bool RayObjectsIntersection2D(Vec3 vStart, Vec3 vEnd, Vec3& vHitPoint, EERType eERType) = 0; - - - // Description: - // Used by editor during object alignment - virtual bool RenderMeshRayIntersection(IRenderMesh* pRenderMesh, SRayHitInfo& hitInfo, _smart_ptr pCustomMtl = 0) = 0; - - virtual void CheckCreateRNTmpData(CRNTmpData** ppInfo, IRenderNode* pRNode, const SRenderingPassInfo& passInfo) = 0; - - // Description: - // Frees lod transition state - virtual void FreeRNTmpData(CRNTmpData** ppInfo) = 0; - - // Description: - // Returns true if the Octree is ready. - virtual bool IsObjectTreeReady() = 0; - - virtual IOctreeNode* GetIObjectTree() = 0; - - // Description: - // Call function 2 times (first to get the size then to fill in the data) - // Arguments: - // pObjects - 0 if only the count is required - // Return Value: - // Count returned - virtual uint32 GetObjectsByType(EERType objType, IRenderNode** pObjects = 0) = 0; - virtual uint32 GetObjectsByTypeInBox(EERType objType, const AABB& bbox, IRenderNode** pObjects = 0, ObjectTreeQueryFilterCallback filterCallback = nullptr) = 0; - virtual uint32 GetObjectsInBox(const AABB& bbox, IRenderNode** pObjects = 0) = 0; - virtual uint32 GetObjectsByFlags(uint dwFlag, IRenderNode** pObjects = 0) = 0; - - // variant which takes a POD array which is resized in the function itself - virtual void GetObjectsByTypeInBox(EERType objType, const AABB& bbox, PodArray* pLstObjects, ObjectTreeQueryFilterCallback filterCallback = nullptr) = 0; - - // Called from editor whenever an object is modified by the user - virtual void OnObjectModified(IRenderNode* pRenderNode, uint dwFlags) = 0; - - virtual void FillDebugFPSInfo(SDebugFPSInfo&) = 0; - - virtual const char* GetLevelFolder() = 0; - - virtual bool IsAreaActivationInUse() = 0; - - virtual void RenderRenderNode_ShadowPass(IShadowCaster* pRNode, const SRenderingPassInfo& passInfo, AZ::LegacyJobExecutor* pJobExecutor) = 0; - - virtual IOpticsManager* GetOpticsManager() = 0; - - // Description: - // Syncs and performs outstanding operations for the Asyncrhon ProcessStreaming Update - virtual void SyncProcessStreamingUpdate() = 0; - - // Set Callback for Editor to store additional information in Minimap tool - virtual void SetScreenshotCallback(IScreenshotCallback* pCallback) = 0; - - // Show/Hide objects by layer (useful for streaming and performance) - virtual void ActivateObjectsLayer(uint16 nLayerId, bool bActivate, bool bPhys, bool bObjects, bool bStaticLights, const char* pLayerName, IGeneralMemoryHeap* pHeap = NULL, bool bCheckLayerActivation = true) = 0; - - // Get object layer memory usage - virtual void GetLayerMemoryUsage(uint16 nLayerId, ICrySizer* pSizer, int* pNumBrushes, int* pNumDecals) const = 0; - - // Collect layer ID's to skip loading objects from these layers, e.g. to skip console specific layers - virtual void SkipLayerLoading(uint16 nLayerId, bool bClearList) = 0; - - // Activate streaming of render node and all sub-components - virtual void PrecacheRenderNode(IRenderNode* pObj, float fEntDistanceReal) = 0; - - virtual IDeferredPhysicsEventManager* GetDeferredPhysicsEventManager() = 0; - - virtual void SetStreamableListener(IStreamedObjectListener* pListener) = 0; - - // following functions are used by SRenderingPassInfo - virtual CCamera* GetRenderingPassCamera(const CCamera& rCamera) = 0; - - struct SSvoStaticTexInfo - { - SSvoStaticTexInfo() - { - ZeroStruct(*this); - } - - // SVO data pools - ITexture* pTexTree; - ITexture* pTexOpac; - ITexture* pTexRgb0; - ITexture* pTexRgb1; - ITexture* pTexDynl; - ITexture* pTexRgb2; - ITexture* pTexRgb3; - ITexture* pTexNorm; - ITexture* pTexAldi; - - ITexture* pGlobalSpecCM; - - float fGlobalSpecCM_Mult; - int nTexDimXY; - int nTexDimZ; - int nBrickSize; - bool bSvoReady; - bool bSvoFreeze; - }; - - struct SLightTI - { - Vec4 vPosR; - Vec4 vDirF; - Vec4 vCol; - float fSortVal; - class ITexture* pCM; - }; - - virtual void GetSvoStaticTextures(I3DEngine::SSvoStaticTexInfo& svoInfo, PodArray* pLightsTI_S, PodArray* pLightsTI_D) = 0; - - struct SSvoNodeInfo - { - AABB wsBox; - AABB tcBox; - int nAtlasOffset; - }; - - virtual void GetSvoBricksForUpdate(PodArray& arrNodeInfo, bool getDynamic) = 0; - -#if defined(USE_GEOM_CACHES) - // Summary: - // Loads a geometry cache from a CAX file. - // See Also: - // IGeomCache - // Arguments: - // szFileName - CAX Filename - should not be 0 or "" - // Return Value: - // A pointer to an object derived from IGeomCache. - virtual IGeomCache* LoadGeomCache(const char* szFileName) = 0; - - // Finds a geom cache created from the given filename - // See Also: - // IGeomCache - // Arguments: - // szFileName - CAX Filename - should not be 0 or "" - // Return Value: - // A pointer to an object derived from IGeomCache. - virtual IGeomCache* FindGeomCacheByFilename(const char* szFileName) = 0; -#endif - - // Summary: - // Loads a designer object from a stream of _decoded_ binary node. (Base64Decode) - // Arguments: - // szBinaryStream - decoded stream + size - virtual IStatObj* LoadDesignerObject(int nVersion, const char* szBinaryStream, int size) = 0; - - // Summary: - // Makes sure all queued culling jobs are completely finished. - // This is useful when adding or removing Components that trigger AZ::Job creation - // like the terrain system. It is important to complete those jobs before removing - // such type of components. - virtual void WaitForCullingJobsCompletion() = 0; - - // -}; - -#pragma pack(pop) - -#include - -// state of 3dengine during rendering -// used to prevent global state -struct SRenderingPassInfo -{ - enum EShadowMapType - { - SHADOW_MAP_NONE = 0, - SHADOW_MAP_GSM, - SHADOW_MAP_LOCAL, - SHADOW_MAP_CACHED, - SHADOW_MAP_CACHED_MGPU_COPY - }; - - // enum flags to identify which objects to skip for this pass - enum ESkipRenderingFlags - { - SHADOWS = BIT(0), - ENTITIES = BIT(3), - WATEROCEAN = BIT(5), - DECALS = BIT(7), - MERGED_MESHES = BIT(10), - ROADS = BIT(13), - WATER_VOLUMES = BIT(14), - CLOUDS = BIT(15), - CUBEMAP_GEN = BIT(16), - GEOM_CACHES = BIT(17), - DISABLE_RENDER_CHUNK_MERGE = BIT(18), - - // below are precombined flags - STATIC_OBJECTS = ENTITIES, - DEFAULT_FLAGS = SHADOWS | ENTITIES | WATEROCEAN | DECALS | MERGED_MESHES | ROADS | WATER_VOLUMES | CLOUDS | GEOM_CACHES, - DEFAULT_RECURSIVE_FLAGS = ENTITIES | WATEROCEAN | DECALS | MERGED_MESHES | ROADS | WATER_VOLUMES | CLOUDS | GEOM_CACHES - }; - - // creating function for RenderingPassInfo, the create functions will fetch all other necessary - // information like thread id/frame id, etc - static SRenderingPassInfo CreateGeneralPassRenderingInfo(const CCamera& rCamera, uint32 nRenderingFlags = DEFAULT_FLAGS, bool bAuxWindow = false); - static SRenderingPassInfo CreateRecursivePassRenderingInfo(const CCamera& rCamera, uint32 nRenderingFlags = DEFAULT_RECURSIVE_FLAGS); - static SRenderingPassInfo CreateShadowPassRenderingInfo(const CCamera& rCamera, int nLightFlags, int nShadowMapLod, bool bExtendedLod, bool bIsMGPUCopy, uint32* pShadowGenMask, uint32 nSide, uint32 nShadowFrustumID, uint32 nRenderingFlags = DEFAULT_FLAGS); - static SRenderingPassInfo CreateTempRenderingInfo(const CCamera& rCamera, const SRenderingPassInfo& rPassInfo); - static SRenderingPassInfo CreateTempRenderingInfo(uint32 nRenderingFlags, const SRenderingPassInfo& rPassInfo); - - // state getter - bool IsGeneralPass() const; - - bool IsRecursivePass() const; - uint32 GetRecursiveLevel() const; - - bool IsShadowPass() const; - bool IsCachedShadowPass() const; - EShadowMapType GetShadowMapType() const; - bool IsDisableRenderChunkMerge() const; - - bool IsAuxWindow() const; - - threadID ThreadID() const; - void SetThreadID(threadID id) { m_nThreadID = static_cast(id); } - - int GetFrameID() const; - uint32 GetMainFrameID() const; - - const CCamera& GetCamera() const; - bool IsCameraUnderWater() const; - - float GetZoomFactor() const; - float GetInverseZoomFactor() const; - bool RenderShadows() const; - bool RenderEntities() const; - bool RenderWaterOcean() const; - bool RenderDecals() const; - bool RenderWaterVolumes() const; - bool RenderClouds() const; - bool RenderGeomCaches() const; - - bool IsRenderingCubemap() const; - - uint32* ShadowGenMaskAddress() const; - uint32 ShadowFrustumID() const; - uint8 ShadowFrustumSide() const; - uint8 ShadowFrustumLod() const; - - CRenderView* GetRenderView() const; - - SRenderingPassInfo(threadID id) - { - SRenderingPassInfo(); - SetThreadID(id); - m_pRenderView = gEnv->pRenderer->GetRenderViewForThread(id); - } - -private: - - // private constructor, creation is only allowed with create functions - SRenderingPassInfo() - : pShadowGenMask(NULL) - , nShadowSide(0) - , nShadowLod(0) - , nShadowFrustumId(0) - , m_bAuxWindow(0) - , m_nRenderStackLevel(0) - , m_eShadowMapRendering(static_cast(SHADOW_MAP_NONE)) - , m_bCameraUnderWater(0) - , m_nRenderingFlags(0) - , m_fZoomFactor(0.0f) - , m_pCamera(NULL) - { - threadID nThreadID = 0; - gEnv->pRenderer->EF_Query(EFQ_MainThreadList, nThreadID); - m_nThreadID = aznumeric_caster(nThreadID); - m_nRenderFrameID = gEnv->pRenderer->GetFrameID(); - m_nRenderMainFrameID = gEnv->pRenderer->GetFrameID(false); - m_pRenderView = gEnv->pRenderer->GetRenderViewForThread(m_nThreadID); - } - - void InitRenderingFlags(uint32 nRenderingFlags); - void SetCamera(const CCamera& cam); - - uint8 m_nThreadID; - uint8 m_nRenderStackLevel; - uint8 m_eShadowMapRendering; // State flag denoting what type of shadow map is being currently rendered into - uint8 m_bCameraUnderWater; - - uint32 m_nRenderingFlags; - - float m_fZoomFactor; - - int m_nRenderFrameID; - uint32 m_nRenderMainFrameID; - - const CCamera* m_pCamera; - - // Render view used for this rendering pass - CRenderView* m_pRenderView; - - // members used only in shadow pass - uint32* pShadowGenMask; - uint32 nShadowFrustumId; - uint8 nShadowSide : 4; - uint8 nShadowLod : 4; - uint8 m_bAuxWindow; -}; - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsGeneralPass() const -{ - return m_nRenderStackLevel == 0 && m_bAuxWindow == 0 && static_cast(m_eShadowMapRendering) == SHADOW_MAP_NONE; -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsRecursivePass() const -{ - return m_nRenderStackLevel > 0; -} - -/////////////////////////////////////////////////////////////////////////////// -inline uint32 SRenderingPassInfo::GetRecursiveLevel() const -{ - return m_nRenderStackLevel; -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsShadowPass() const -{ - return static_cast(m_eShadowMapRendering) != SHADOW_MAP_NONE; -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsCachedShadowPass() const -{ - return IsShadowPass() && - (GetShadowMapType() == SRenderingPassInfo::SHADOW_MAP_CACHED || - GetShadowMapType() == SRenderingPassInfo::SHADOW_MAP_CACHED_MGPU_COPY); -} -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo::EShadowMapType SRenderingPassInfo::GetShadowMapType() const -{ - assert(IsShadowPass()); - return static_cast(m_eShadowMapRendering); -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsAuxWindow() const -{ - return m_bAuxWindow != 0; -} - -/////////////////////////////////////////////////////////////////////////////// -inline threadID SRenderingPassInfo::ThreadID() const -{ - return m_nThreadID; -} - -/////////////////////////////////////////////////////////////////////////////// -inline int SRenderingPassInfo::GetFrameID() const -{ - return m_nRenderFrameID; -} - -/////////////////////////////////////////////////////////////////////////////// -inline uint32 SRenderingPassInfo::GetMainFrameID() const -{ - return m_nRenderMainFrameID; -} - -/////////////////////////////////////////////////////////////////////////////// -inline const CCamera& SRenderingPassInfo::GetCamera() const -{ - assert(m_pCamera != NULL); - return *m_pCamera; -} - -/////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsCameraUnderWater() const -{ - return m_bCameraUnderWater != 0; -} - -/////////////////////////////////////////////////////////////////////////////// -inline float SRenderingPassInfo::GetZoomFactor() const -{ - return m_fZoomFactor; -} - -/////////////////////////////////////////////////////////////////////////////// -inline float SRenderingPassInfo::GetInverseZoomFactor() const -{ - return 1.0f / m_fZoomFactor; -} - - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderShadows() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::SHADOWS) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderEntities() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::ENTITIES) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderWaterOcean() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::WATEROCEAN) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderDecals() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::DECALS) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderWaterVolumes() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::WATER_VOLUMES) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderClouds() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::CLOUDS) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::RenderGeomCaches() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::GEOM_CACHES) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsRenderingCubemap() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::CUBEMAP_GEN) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline bool SRenderingPassInfo::IsDisableRenderChunkMerge() const -{ - return (m_nRenderingFlags& SRenderingPassInfo::DISABLE_RENDER_CHUNK_MERGE) != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -inline uint32* SRenderingPassInfo::ShadowGenMaskAddress() const -{ - assert(pShadowGenMask); - return pShadowGenMask; -} - -//////////////////////////////////////////////////////////////////////////////// -inline uint32 SRenderingPassInfo::ShadowFrustumID() const -{ - return nShadowFrustumId; -} - -//////////////////////////////////////////////////////////////////////////////// -inline uint8 SRenderingPassInfo::ShadowFrustumSide() const -{ - return nShadowSide; -} - -//////////////////////////////////////////////////////////////////////////////// -inline uint8 SRenderingPassInfo::ShadowFrustumLod() const -{ - return nShadowLod; -} -//////////////////////////////////////////////////////////////////////////////// -inline CRenderView* SRenderingPassInfo::GetRenderView() const -{ - return m_pRenderView; -} -//////////////////////////////////////////////////////////////////////////////// -inline void SRenderingPassInfo::SetCamera(const CCamera& cam) -{ - m_pCamera = gEnv->p3DEngine->GetRenderingPassCamera(cam); - m_bCameraUnderWater = gEnv->p3DEngine->IsUnderWater(cam.GetPosition()); - m_fZoomFactor = 0.2f + 0.8f * (RAD2DEG(cam.GetFov()) / 60.f); -} - -//////////////////////////////////////////////////////////////////////////////// -inline void SRenderingPassInfo::InitRenderingFlags(uint32 nRenderingFlags) -{ - m_nRenderingFlags = nRenderingFlags; -#if (ALLOW_CONST_CVAR_MODIFICATIONS) - static ICVar* pDefaultMaterial = gEnv->pConsole->GetCVar("e_DefaultMaterial"); - static ICVar* pShadows = gEnv->pConsole->GetCVar("e_Shadows"); - static ICVar* pEntities = gEnv->pConsole->GetCVar("e_Entities"); - static ICVar* pWaterOcean = gEnv->pConsole->GetCVar("e_WaterOcean"); - static ICVar* pDecals = gEnv->pConsole->GetCVar("e_Decals"); - static ICVar* pWaterVolumes = gEnv->pConsole->GetCVar("e_WaterVolumes"); - static ICVar* pClouds = gEnv->pConsole->GetCVar("e_Clouds"); - static ICVar* pGeomCaches = gEnv->pConsole->GetCVar("e_GeomCaches"); - - if (pShadows->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::SHADOWS; - } - if (pEntities->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::ENTITIES; - } - if (pWaterOcean->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::WATEROCEAN; - } - if (pDecals->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::DECALS; - } - if (pWaterVolumes->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::WATER_VOLUMES; - } - if (pClouds->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::CLOUDS; - } - if (pGeomCaches->GetIVal() == 0) - { - m_nRenderingFlags &= ~SRenderingPassInfo::GEOM_CACHES; - } - - // on dedicated server, never render any object at all - if (gEnv->IsDedicated()) - { - m_nRenderingFlags = 0; - } -#endif // (ALLOW_CONST_CVAR_MODIFICATIONS) -} - -//////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateGeneralPassRenderingInfo(const CCamera& rCamera, uint32 nRenderingFlags, bool bAuxWindow) -{ - static ICVar* pCameraFreeze = gEnv->pConsole->GetCVar("e_CameraFreeze"); - - // Update Camera only if e_camerafreeze is not set - const CCamera& rCameraToSet = (pCameraFreeze && pCameraFreeze->GetIVal() != 0) ? gEnv->p3DEngine->GetRenderingCamera() : rCamera; - - SRenderingPassInfo passInfo; - passInfo.SetCamera(rCameraToSet); - passInfo.InitRenderingFlags(nRenderingFlags); - passInfo.m_bAuxWindow = bAuxWindow; - - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateRecursivePassRenderingInfo(const CCamera& rCamera, uint32 nRenderingFlags) -{ - static ICVar* pRecursionViewDistRatio = gEnv->pConsole->GetCVar("e_RecursionViewDistRatio"); - - SRenderingPassInfo passInfo; - passInfo.m_nRenderStackLevel = 1; - passInfo.SetCamera(rCamera); - - // adjust view distance in recursive mode by adjusting the ZoomFactor - passInfo.m_fZoomFactor /= pRecursionViewDistRatio->GetFVal(); - - passInfo.InitRenderingFlags(nRenderingFlags); - - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateShadowPassRenderingInfo(const CCamera& rCamera, int nLightFlags, int nShadowMapLod, bool bExtendedLod, bool bIsMGPUCopy, uint32* pShadowGenMask, uint32 nSide, uint32 nShadowFrustumID, uint32 nRenderingFlags) -{ - SRenderingPassInfo passInfo; - passInfo.SetCamera(rCamera); - passInfo.InitRenderingFlags(nRenderingFlags); - - // set correct shadow map type - if (nLightFlags & DLF_SUN) - { - assert(nShadowMapLod >= 0 && nShadowMapLod < 8); - if (bExtendedLod) - { - passInfo.m_eShadowMapRendering = bIsMGPUCopy ? static_cast(SHADOW_MAP_CACHED_MGPU_COPY) : static_cast(SHADOW_MAP_CACHED); - } - else - { - passInfo.m_eShadowMapRendering = static_cast(SHADOW_MAP_GSM); - } - } - else if (nLightFlags & (DLF_POINT | DLF_PROJECT | DLF_AREA_LIGHT)) - { - passInfo.m_eShadowMapRendering = static_cast(SHADOW_MAP_LOCAL); - } - else - { - passInfo.m_eShadowMapRendering = static_cast(SHADOW_MAP_NONE); - } - - passInfo.pShadowGenMask = pShadowGenMask; - passInfo.nShadowSide = nSide; - passInfo.nShadowLod = nShadowMapLod; - passInfo.nShadowFrustumId = nShadowFrustumID; - - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateTempRenderingInfo(const CCamera& rCamera, const SRenderingPassInfo& rPassInfo) -{ - SRenderingPassInfo passInfo = rPassInfo; - passInfo.SetCamera(rCamera); - - passInfo.pShadowGenMask = NULL; - passInfo.nShadowSide = 0; - passInfo.nShadowFrustumId = 0; - - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRenderingPassInfo SRenderingPassInfo::CreateTempRenderingInfo(uint32 nRenderingFlags, const SRenderingPassInfo& rPassInfo) -{ - SRenderingPassInfo passInfo = rPassInfo; - passInfo.m_nRenderingFlags = nRenderingFlags; - return passInfo; -} - -/////////////////////////////////////////////////////////////////////////////// -// class to wrap a special counter used to presort SRendItems -// this is used to fix random ordering introduced by parallelization -// of parts of the 3DEngine -struct SRendItemSorter -{ - // Deferred PreProcess needs a special ordering, use these to prefix the values - // to ensure the deferred shading pass is after all LPV objects - enum EDeferredPreprocess - { - eLPVPass = 0, - eDeferredShadingPass = BIT(30) - }; - - static SRendItemSorter CreateRendItemSorter(const SRenderingPassInfo& passInfo); - static SRendItemSorter CreateShadowPassRendItemSorter(const SRenderingPassInfo& passInfo); - static SRendItemSorter CreateParticleRendItemSorter(const SRenderingPassInfo& passInfo); - static SRendItemSorter CreateDeferredPreProcessRendItemSorter(const SRenderingPassInfo& passInfo, EDeferredPreprocess deferredPrerocessType); - static SRendItemSorter CreateDefaultRendItemSorter(); - - void IncreaseOctreeCounter() { nValue += eOctreeNodeCounter; } - void IncreaseObjectCounter() { nValue += eObjectCounter; } - void IncreaseGroupCounter() { nValue += eGroupCounter; } - - void IncreaseParticleCounter() { nValue += eParticleCounter; } - uint32 ParticleCounter() const { return nValue & ~eRecursivePassMask; } - - uint32 ShadowFrustumID() const { return nValue & ~eRecursivePassMask; } - - uint32 GetValue() const { return nValue; } - - bool operator<(const SRendItemSorter& rOther) const - { - return nValue < rOther.nValue; - } - - bool IsRecursivePass() const { return (nValue & eRecursivePassMask) != 0; } - - SRendItemSorter() - : nValue(0) {} - explicit SRendItemSorter(uint32 _nValue) - : nValue(_nValue) {} - -private: - // encode various counter in a single value - enum - { - eRecursivePassMask = BIT(31) - }; // present in all combinations - - // flags used for regular SRendItems - enum - { - eObjectCounter = BIT(0) - }; // bits 0-14 used - enum - { - eOctreeNodeCounter = BIT(14) - }; // bits 15-27 used - enum - { - eGroupCounter = BIT(27) - }; // bits 28-31 used - - // flags used for Particles - enum - { - eParticleCounter = BIT(0) - }; - - uint32 nValue; -}; - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateRendItemSorter(const SRenderingPassInfo& passInfo) -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = 0; - rendItemSorter.nValue |= passInfo.IsRecursivePass() ? eRecursivePassMask : 0; - return rendItemSorter; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateShadowPassRendItemSorter(const SRenderingPassInfo& passInfo) -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = passInfo.ShadowFrustumID(); - rendItemSorter.nValue |= passInfo.IsRecursivePass() ? eRecursivePassMask : 0; - return rendItemSorter; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateParticleRendItemSorter(const SRenderingPassInfo& passInfo) -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = 0; - rendItemSorter.nValue |= passInfo.IsRecursivePass() ? eRecursivePassMask : 0; - return rendItemSorter; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateDeferredPreProcessRendItemSorter(const SRenderingPassInfo& passInfo, EDeferredPreprocess deferredPrerocessType) -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = 0; - rendItemSorter.nValue |= passInfo.IsRecursivePass() ? eRecursivePassMask : 0; - rendItemSorter.nValue |= deferredPrerocessType; - return rendItemSorter; -} - -/////////////////////////////////////////////////////////////////////////////// -inline SRendItemSorter SRendItemSorter::CreateDefaultRendItemSorter() -{ - SRendItemSorter rendItemSorter; - rendItemSorter.nValue = 0; - return rendItemSorter; -} - -//Legacy Bus for communicating with SVOGI from the legacy engine code. -class SVOGILegacyRequests - : public AZ::EBusTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - using MutexType = AZStd::recursive_mutex; -// static const bool LocklessDispatch = true; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // Triggers an update of voxel data. - virtual void UpdateVoxelData() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Triggers an update of voxel data to GPU. - virtual void UpdateRenderData() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Called at framestart - virtual void OnFrameStart(const SRenderingPassInfo& passInfo) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Gets the textures bound for GI plus lighting data. - virtual void GetSvoStaticTextures(I3DEngine::SSvoStaticTexInfo& svoInfo, PodArray* pLightsTI_S, PodArray* pLightsTI_D) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Generates a list of bricks that need to be updated in compute shaders. - virtual void GetSvoBricksForUpdate(PodArray& arrNodeInfo, bool getDynamic) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Causes the GI system to free all voxel data. - virtual void ReleaseData() = 0; - - ////////////////////////////////////////////////////////////////////////// - // Register and unregister a mutex to protect assets during rendering. - virtual void RegisterMutex(AZStd::mutex* mutex) = 0; - virtual void UnregisterMutex() = 0; - -}; -using SVOGILegacyRequestBus = AZ::EBus; - - -#endif // CRYINCLUDE_CRYCOMMON_I3DENGINE_H - diff --git a/Code/CryEngine/CryCommon/I3DEngine_info.h b/Code/CryEngine/CryCommon/I3DEngine_info.h deleted file mode 100644 index f1c601fcc6..0000000000 --- a/Code/CryEngine/CryCommon/I3DEngine_info.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_I3DENGINE_INFO_H -#define CRYINCLUDE_CRYCOMMON_I3DENGINE_INFO_H -#pragma once - -#include "TypeInfo_impl.h" -#include "IShader_info.h" -#include // <> required for Interfuscator - -STRUCT_INFO_BEGIN(SVisAreaManChunkHeader) -STRUCT_VAR_INFO(nVersion, TYPE_INFO(int8)) -STRUCT_VAR_INFO(nDummy, TYPE_INFO(int8)) -STRUCT_VAR_INFO(nFlags, TYPE_INFO(int8)) -STRUCT_VAR_INFO(nFlags2, TYPE_INFO(int8)) -STRUCT_VAR_INFO(nChunkSize, TYPE_INFO(int)) -STRUCT_VAR_INFO(nVisAreasNum, TYPE_INFO(int)) -STRUCT_VAR_INFO(nPortalsNum, TYPE_INFO(int)) -STRUCT_VAR_INFO(nOcclAreasNum, TYPE_INFO(int)) -STRUCT_INFO_END(SVisAreaManChunkHeader) - -STRUCT_INFO_BEGIN(SOcTreeNodeChunk) -STRUCT_VAR_INFO(nChunkVersion, TYPE_INFO(int16)) -STRUCT_VAR_INFO(ucChildsMask, TYPE_INFO(int16)) -STRUCT_VAR_INFO(nodeBox, TYPE_INFO(AABB)) -STRUCT_VAR_INFO(nObjectsBlockSize, TYPE_INFO(int32)) -STRUCT_INFO_END(SOcTreeNodeChunk) - -STRUCT_INFO_BEGIN(SHotUpdateInfo) -STRUCT_VAR_INFO(nHeigtmap, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(nObjTypeMask, TYPE_INFO(uint32)) -STRUCT_VAR_INFO(areaBox, TYPE_INFO(AABB)) -STRUCT_INFO_END(SHotUpdateInfo) - -STRUCT_INFO_BEGIN(SCommonFileHeader) -STRUCT_VAR_INFO(signature, TYPE_ARRAY(4, TYPE_INFO(char))) -STRUCT_VAR_INFO(file_type, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(flags, TYPE_INFO(uint8)) -STRUCT_VAR_INFO(version, TYPE_INFO(uint16)) -STRUCT_INFO_END(SCommonFileHeader) - -#endif // CRYINCLUDE_CRYCOMMON_I3DENGINE_INFO_H diff --git a/Code/CryEngine/CryCommon/IEntityRenderState.h b/Code/CryEngine/CryCommon/IEntityRenderState.h index 92ff354eff..29b1bdc463 100644 --- a/Code/CryEngine/CryCommon/IEntityRenderState.h +++ b/Code/CryEngine/CryCommon/IEntityRenderState.h @@ -286,7 +286,6 @@ struct IRenderNode // Physicalizes node. virtual void Physicalize([[maybe_unused]] bool bInstant = false) {} - // Make sure I3DEngine::FreeRenderNodeState(this) is called in destructor of derived class. virtual ~IRenderNode() { assert(!m_pRNTmpData); }; // Summary: diff --git a/Code/CryEngine/CryCommon/ILocalMemoryUsage.h b/Code/CryEngine/CryCommon/ILocalMemoryUsage.h deleted file mode 100644 index fd1e7e3693..0000000000 --- a/Code/CryEngine/CryCommon/ILocalMemoryUsage.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Interface for LocalMemoryUsage - - -#ifndef CRYINCLUDE_CRYCOMMON_ILOCALMEMORYUSAGE_H -#define CRYINCLUDE_CRYCOMMON_ILOCALMEMORYUSAGE_H -#pragma once - - -class CCamera; -struct IRenderer; - -struct ILocalMemoryUsage -{ - virtual ~ILocalMemoryUsage(){} - virtual void OnRender(IRenderer* pRenderer, const CCamera* camera) = 0; - virtual void OnUpdate() = 0; - virtual void DeleteGlobalData() = 0; -}; - -#endif // CRYINCLUDE_CRYCOMMON_ILOCALMEMORYUSAGE_H diff --git a/Code/CryEngine/CryCommon/IMaterial.h b/Code/CryEngine/CryCommon/IMaterial.h index 81d612397f..020ddcc871 100644 --- a/Code/CryEngine/CryCommon/IMaterial.h +++ b/Code/CryEngine/CryCommon/IMaterial.h @@ -273,7 +273,7 @@ struct IMaterial ////////////////////////////////////////////////////////////////////////// // material name ////////////////////////////////////////////////////////////////////////// - //! Set material name, (Do not use this directly, to change material name use I3DEngine::RenameMatInfo method). + //! Set material name, (Do not use this directly virtual void SetName(const char* pName) = 0; //! Returns material name. virtual const char* GetName() const = 0; @@ -404,7 +404,6 @@ struct IMaterial ////////////////////////////////////////////////////////////////////////// // Makes this specific material enter sketch mode. - // Se also: I3DEngine::LoadCGF, in I3DEngine.h. // Current supported sketch modes: // - 0, no sketch. // - 1, normal sketch mode. diff --git a/Code/CryEngine/CryCommon/IMovieSystem.h b/Code/CryEngine/CryCommon/IMovieSystem.h index c22394e1b3..ce4e59d43c 100644 --- a/Code/CryEngine/CryCommon/IMovieSystem.h +++ b/Code/CryEngine/CryCommon/IMovieSystem.h @@ -26,7 +26,6 @@ #include #include #include -#include #include #include diff --git a/Code/CryEngine/CryCommon/IObjManager.h b/Code/CryEngine/CryCommon/IObjManager.h index acbd5c5d18..a63a252976 100644 --- a/Code/CryEngine/CryCommon/IObjManager.h +++ b/Code/CryEngine/CryCommon/IObjManager.h @@ -202,7 +202,6 @@ struct IObjManager // time counters virtual bool IsAfterWater(const Vec3& vPos, const SRenderingPassInfo& passInfo) = 0; - virtual void GetObjectsStreamingStatus(I3DEngine::SObjectsStreamingStatus& outStatus) = 0; virtual void FreeNotUsedCGFs() = 0; virtual void MakeUnitCube() = 0; diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index 9b1e817602..96d9a6ad10 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -66,7 +66,6 @@ struct IConsole; struct IRemoteConsole; struct IRenderer; struct IProcess; -struct I3DEngine; struct ITimer; struct ICryFont; struct IMovieSystem; @@ -123,8 +122,6 @@ namespace Serialization { struct IArchiveHost; } -struct ILocalMemoryUsage; - typedef void* WIN_HWND; class CCamera; @@ -793,7 +790,6 @@ struct SSystemUpdateStats // ISystem struct SSystemGlobalEnvironment { - I3DEngine* p3DEngine; AZ::IO::IArchive* pCryPak; AZ::IO::FileIOBase* pFileIO; IFileChangeMonitor* pFileChangeMonitor; @@ -801,7 +797,6 @@ struct SSystemGlobalEnvironment IOpticsManager* pOpticsManager; ITimer* pTimer; ICryFont* pCryFont; - ILocalMemoryUsage* pLocalMemoryUsage; ::IConsole* pConsole; ISystem* pSystem = nullptr; ILog* pLog; @@ -1113,25 +1108,9 @@ struct ISystem virtual void DoWorkDuringOcclusionChecks() = 0; virtual bool NeedDoWorkDuringOcclusionChecks() = 0; - // Summary: - // Renders subsystems. - virtual void Render() = 0; - // Summary: - // Begins rendering frame. - virtual void RenderBegin() = 0; - // Summary: - // Ends rendering frame and swap back buffer. - virtual void RenderEnd(bool bRenderStats = true, bool bMainWindow = true) = 0; - //! Update screen and call some important tick functions during loading. virtual void SynchronousLoadingTick(const char* pFunc, int line) = 0; - // Description: - // Renders the statistics; this is called from RenderEnd, but if the - // Host application (Editor) doesn't employ the Render cycle in ISystem, - // it may call this method to render the essential statistics. - virtual void RenderStatistics() = 0; - // Summary: // Returns the current used memory. virtual uint32 GetUsedMemory() = 0; @@ -1229,7 +1208,6 @@ struct ISystem virtual ICryFont* GetICryFont() = 0; virtual IMemoryManager* GetIMemoryManager() = 0; virtual IMovieSystem* GetIMovieSystem() = 0; - virtual I3DEngine* GetI3DEngine() = 0; virtual ::IConsole* GetIConsole() = 0; virtual IRemoteConsole* GetIRemoteConsole() = 0; // Returns: diff --git a/Code/CryEngine/CryCommon/ITimeOfDay.h b/Code/CryEngine/CryCommon/ITimeOfDay.h deleted file mode 100644 index b491ea9359..0000000000 --- a/Code/CryEngine/CryCommon/ITimeOfDay.h +++ /dev/null @@ -1,286 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. -#pragma once - -struct SBezierKey; -struct ITimeOfDayUpdateCallback; -struct ISplineInterpolator; - - -//! Interface to the Time Of Day functionality. -struct ITimeOfDay -{ - enum ETimeOfDayParamID - { - PARAM_SUN_COLOR, - PARAM_SUN_INTENSITY, - PARAM_SUN_SPECULAR_MULTIPLIER, - - PARAM_FOG_COLOR, - PARAM_FOG_COLOR_MULTIPLIER, - PARAM_VOLFOG_HEIGHT, - PARAM_VOLFOG_DENSITY, - PARAM_FOG_COLOR2, - PARAM_FOG_COLOR2_MULTIPLIER, - PARAM_VOLFOG_HEIGHT2, - PARAM_VOLFOG_DENSITY2, - PARAM_VOLFOG_HEIGHT_OFFSET, - - PARAM_FOG_RADIAL_COLOR, - PARAM_FOG_RADIAL_COLOR_MULTIPLIER, - PARAM_VOLFOG_RADIAL_SIZE, - PARAM_VOLFOG_RADIAL_LOBE, - - PARAM_VOLFOG_FINAL_DENSITY_CLAMP, - - PARAM_VOLFOG_GLOBAL_DENSITY, - PARAM_VOLFOG_RAMP_START, - PARAM_VOLFOG_RAMP_END, - PARAM_VOLFOG_RAMP_INFLUENCE, - - PARAM_VOLFOG_SHADOW_DARKENING, - PARAM_VOLFOG_SHADOW_DARKENING_SUN, - PARAM_VOLFOG_SHADOW_DARKENING_AMBIENT, - PARAM_VOLFOG_SHADOW_RANGE, - - PARAM_VOLFOG2_HEIGHT, - PARAM_VOLFOG2_DENSITY, - PARAM_VOLFOG2_HEIGHT2, - PARAM_VOLFOG2_DENSITY2, - PARAM_VOLFOG2_GLOBAL_DENSITY, - PARAM_VOLFOG2_RAMP_START, - PARAM_VOLFOG2_RAMP_END, - PARAM_VOLFOG2_COLOR1, - PARAM_VOLFOG2_ANISOTROPIC1, - PARAM_VOLFOG2_COLOR2, - PARAM_VOLFOG2_ANISOTROPIC2, - PARAM_VOLFOG2_BLEND_FACTOR, - PARAM_VOLFOG2_BLEND_MODE, - PARAM_VOLFOG2_COLOR, - PARAM_VOLFOG2_ANISOTROPIC, - PARAM_VOLFOG2_RANGE, - PARAM_VOLFOG2_INSCATTER, - PARAM_VOLFOG2_EXTINCTION, - PARAM_VOLFOG2_GLOBAL_FOG_VISIBILITY, - PARAM_VOLFOG2_FINAL_DENSITY_CLAMP, - - PARAM_SKYLIGHT_SUN_INTENSITY, - PARAM_SKYLIGHT_SUN_INTENSITY_MULTIPLIER, - - PARAM_SKYLIGHT_KM, - PARAM_SKYLIGHT_KR, - PARAM_SKYLIGHT_G, - - PARAM_SKYLIGHT_WAVELENGTH_R, - PARAM_SKYLIGHT_WAVELENGTH_G, - PARAM_SKYLIGHT_WAVELENGTH_B, - - PARAM_NIGHSKY_HORIZON_COLOR, - PARAM_NIGHSKY_HORIZON_COLOR_MULTIPLIER, - PARAM_NIGHSKY_ZENITH_COLOR, - PARAM_NIGHSKY_ZENITH_COLOR_MULTIPLIER, - PARAM_NIGHSKY_ZENITH_SHIFT, - - PARAM_NIGHSKY_START_INTENSITY, - - PARAM_NIGHSKY_MOON_COLOR, - PARAM_NIGHSKY_MOON_COLOR_MULTIPLIER, - PARAM_NIGHSKY_MOON_INNERCORONA_COLOR, - PARAM_NIGHSKY_MOON_INNERCORONA_COLOR_MULTIPLIER, - PARAM_NIGHSKY_MOON_INNERCORONA_SCALE, - PARAM_NIGHSKY_MOON_OUTERCORONA_COLOR, - PARAM_NIGHSKY_MOON_OUTERCORONA_COLOR_MULTIPLIER, - PARAM_NIGHSKY_MOON_OUTERCORONA_SCALE, - - PARAM_CLOUDSHADING_SUNLIGHT_MULTIPLIER, - PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR, - PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR_MULTIPLIER, - PARAM_CLOUDSHADING_SUNLIGHT_CUSTOM_COLOR_INFLUENCE, - - PARAM_SUN_SHAFTS_VISIBILITY, - PARAM_SUN_RAYS_VISIBILITY, - PARAM_SUN_RAYS_ATTENUATION, - PARAM_SUN_RAYS_SUNCOLORINFLUENCE, - PARAM_SUN_RAYS_CUSTOMCOLOR, - - PARAM_OCEANFOG_COLOR, // Remove when ocean related feature toggle is removed. - PARAM_OCEANFOG_COLOR_MULTIPLIER, // Remove when ocean related feature toggle is removed. - PARAM_OCEANFOG_DENSITY, // Remove when ocean related feature toggle is removed. - - PARAM_SKYBOX_MULTIPLIER, - - PARAM_HDR_FILMCURVE_SHOULDER_SCALE, - PARAM_HDR_FILMCURVE_LINEAR_SCALE, - PARAM_HDR_FILMCURVE_TOE_SCALE, - PARAM_HDR_FILMCURVE_WHITEPOINT, - - PARAM_HDR_COLORGRADING_COLOR_SATURATION, - PARAM_HDR_COLORGRADING_COLOR_BALANCE, - - PARAM_HDR_EYEADAPTATION_SCENEKEY, - PARAM_HDR_EYEADAPTATION_MIN_EXPOSURE, - PARAM_HDR_EYEADAPTATION_MAX_EXPOSURE, - PARAM_HDR_EYEADAPTATION_EV_MIN, - PARAM_HDR_EYEADAPTATION_EV_MAX, - PARAM_HDR_EYEADAPTATION_EV_AUTO_COMPENSATION, - PARAM_HDR_BLOOM_AMOUNT, - - PARAM_COLORGRADING_FILTERS_GRAIN, - PARAM_COLORGRADING_FILTERS_PHOTOFILTER_COLOR, - PARAM_COLORGRADING_FILTERS_PHOTOFILTER_DENSITY, - - PARAM_COLORGRADING_DOF_FOCUSRANGE, - PARAM_COLORGRADING_DOF_BLURAMOUNT, - - PARAM_SHADOWSC0_BIAS, - PARAM_SHADOWSC0_SLOPE_BIAS, - PARAM_SHADOWSC1_BIAS, - PARAM_SHADOWSC1_SLOPE_BIAS, - PARAM_SHADOWSC2_BIAS, - PARAM_SHADOWSC2_SLOPE_BIAS, - PARAM_SHADOWSC3_BIAS, - PARAM_SHADOWSC3_SLOPE_BIAS, - PARAM_SHADOWSC4_BIAS, - PARAM_SHADOWSC4_SLOPE_BIAS, - PARAM_SHADOWSC5_BIAS, - PARAM_SHADOWSC5_SLOPE_BIAS, - PARAM_SHADOWSC6_BIAS, - PARAM_SHADOWSC6_SLOPE_BIAS, - PARAM_SHADOWSC7_BIAS, - PARAM_SHADOWSC7_SLOPE_BIAS, - - PARAM_SHADOW_JITTERING, - - PARAM_HDR_DYNAMIC_POWER_FACTOR, - PARAM_TERRAIN_OCCL_MULTIPLIER, - PARAM_SUN_COLOR_MULTIPLIER, - - PARAM_TOTAL - }; - - struct SPresetInfo - { - const char* m_pName; - bool m_bCurrent; - }; - - enum EVariableType - { - TYPE_FLOAT, - TYPE_COLOR - }; - struct SVariableInfo - { - const char* name; //!< Variable name. - const char* displayName; //!< Variable user readable name. - const char* group; //!< Group name. - int nParamId; - EVariableType type; - float fValue[3]; //!< Value of the variable (3 needed for color type). - ISplineInterpolator* pInterpolator; //!< Splines that control variable value. - }; - struct SAdvancedInfo - { - float fStartTime; - float fEndTime; - float fAnimSpeed; - }; - struct SEnvironmentInfo - { - SEnvironmentInfo() - : bSunLinkedToTOD(true) - , sunRotationLatitude(0) - , sunRotationLongitude(0){} - bool bSunLinkedToTOD; - float sunRotationLatitude; - float sunRotationLongitude; - }; - - // - virtual ~ITimeOfDay(){} - - virtual int GetPresetCount() const = 0; - virtual bool GetPresetsInfos(SPresetInfo* resultArray, unsigned int arraySize) const = 0; - virtual bool SetCurrentPreset(const char* szPresetName) = 0; - virtual bool AddNewPreset(const char* szPresetName) = 0; - virtual bool RemovePreset(const char* szPresetName) = 0; - virtual bool SavePreset(const char* szPresetName) const = 0; - virtual bool LoadPreset(const char* szFilePath) = 0; - virtual void ResetPreset(const char* szPresetName) = 0; - - virtual bool ImportPreset(const char* szPresetName, const char* szFilePath) = 0; - virtual bool ExportPreset(const char* szPresetName, const char* szFilePath) const = 0; - - //! Access to variables that control time of the day appearance. - virtual int GetVariableCount() const = 0; - virtual bool GetVariableInfo(int nIndex, SVariableInfo& varInfo) const = 0; - virtual void SetVariableValue(int nIndex, float fValue[3]) = 0; - - //! Editor interface. - virtual bool InterpolateVarInRange(int nIndex, float fMin, float fMax, unsigned int nCount, Vec3* resultArray) const = 0; - virtual uint GetSplineKeysCount(int nIndex, int nSpline) const = 0; - virtual bool GetSplineKeysForVar(int nIndex, int nSpline, SBezierKey* keysArray, unsigned int keysArraySize) const = 0; - virtual bool SetSplineKeysForVar(int nIndex, int nSpline, const SBezierKey* keysArray, unsigned int keysArraySize) = 0; - virtual bool UpdateSplineKeyForVar(int nIndex, int nSpline, float fTime, float newValue) = 0; - - virtual void ResetVariables() = 0; - - //! Sets the time of the day specified in hours. - virtual void SetTime(float fHour, bool bForceUpdate = false, bool bForceEnvUpdate = true) = 0; - virtual float GetTime() = 0; - - //! Sun position. - virtual void SetSunPos(float longitude, float latitude) = 0; - virtual float GetSunLatitude() = 0; - virtual float GetSunLongitude() = 0; - - //! Updates the current ToD. - virtual void Tick() = 0; - - - virtual void SetPaused(bool paused) = 0; - - virtual void SetAdvancedInfo(const SAdvancedInfo& advInfo) = 0; - virtual void GetAdvancedInfo(SAdvancedInfo& advInfo) = 0; - - //! Updates engine parameters after variable values have been changed. - virtual void Update(bool bInterpolate = true, bool bForceUpdate = false, bool bForceEnvUpdate = true) = 0; - virtual void SetUpdateCallback(ITimeOfDayUpdateCallback* pCallback) = 0; - - virtual void BeginEditMode() = 0; - virtual void EndEditMode() = 0; - - virtual void Serialize(XmlNodeRef& node, bool bLoading) = 0; - virtual void Serialize(TSerialize ser) = 0; - - virtual void SetTimer(ITimer* pTimer) = 0; - virtual void SetEnvironmentSettings(const SEnvironmentInfo& envInfo) = 0; - virtual void LerpWith(const ITimeOfDay& other, float lerpValue, ITimeOfDay& output) const = 0; - - //! Multiplayer serialization. - static const int NETSER_FORCESET = BIT(0); - static const int NETSER_COMPENSATELAG = BIT(1); - static const int NETSER_STATICPROPS = BIT(2); - virtual void NetSerialize(TSerialize ser, float lag, uint32 flags) = 0; -}; - -struct ITimeOfDayUpdateCallback -{ - // - virtual ~ITimeOfDayUpdateCallback(){} - virtual void BeginUpdate() = 0; - virtual bool GetCustomValue(ITimeOfDay::ETimeOfDayParamID paramID, int dim, float* pValues, float& blendWeight) = 0; - virtual void EndUpdate() = 0; - // -}; - diff --git a/Code/CryEngine/CryCommon/Mocks/I3DEngineMock.h b/Code/CryEngine/CryCommon/Mocks/I3DEngineMock.h deleted file mode 100644 index b0936ddbdd..0000000000 --- a/Code/CryEngine/CryCommon/Mocks/I3DEngineMock.h +++ /dev/null @@ -1,528 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include - -#include -#include -#include - -// the following was generated using google's python script to autogenerate mocks. -// however, it needed some hand-editing to make it work, so if you add functions to I3DEngine, -// it will probably be better to just manually add them here than try to run the script again. - -class I3DEngineMock - : public I3DEngine -{ -public: - // From IProcess - MOCK_METHOD1(SetFlags, - void(int)); - MOCK_METHOD0(GetFlags, - int(void)); - - // From I3DEngine - MOCK_METHOD0(Init, - bool()); - MOCK_METHOD1(SetLevelPath, - void(const char* szFolderName)); - MOCK_METHOD1(CheckMinSpec, - bool(uint32 nMinSpec)); - MOCK_METHOD1(PrepareOcclusion, - void(const CCamera& rCamera)); - MOCK_METHOD0(EndOcclusion, - void()); - MOCK_METHOD2(LoadLevel, - bool(const char* szFolderName, const char* szMissionName)); - MOCK_METHOD2(InitLevelForEditor, - bool(const char* szFolderName, const char* szMissionName)); - MOCK_METHOD0(LevelLoadingInProgress, - bool()); - MOCK_METHOD0(OnFrameStart, - void()); - MOCK_METHOD0(PostLoadLevel, - void()); - MOCK_METHOD0(LoadEmptyLevel, - void()); - MOCK_METHOD0(UnloadLevel, - void()); - MOCK_METHOD0(Update, - void()); - MOCK_CONST_METHOD0(GetRenderingCamera, - const CCamera&()); - MOCK_CONST_METHOD0(GetZoomFactor, - float()); - MOCK_METHOD0(Tick, - void()); - MOCK_METHOD0(UpdateShaderItems, - void()); - MOCK_METHOD0(Release, - void()); - MOCK_METHOD3(RenderWorld, - void(int nRenderFlags, const SRenderingPassInfo& passInfo, const char* szDebugName)); - MOCK_METHOD2(RenderSceneReflection, - void(int nRenderFlags, const SRenderingPassInfo& passInfo)); - MOCK_METHOD1(PreWorldStreamUpdate, - void(const CCamera& cam)); - MOCK_METHOD0(WorldStreamUpdate, - void()); - MOCK_METHOD0(ShutDown, - void()); - MOCK_METHOD7(LoadStatObjUnsafeManualRef, - IStatObj*(const char* fileName, const char* geomName, IStatObj::SSubObject** subObject, - bool useStreaming, unsigned long loadingFlags, const void* data, int dataSize)); - MOCK_METHOD7(LoadStatObjAutoRef, - _smart_ptr(const char* fileName, const char* geomName, IStatObj::SSubObject** subObject, - bool useStreaming, unsigned long loadingFlags, const void* data, int dataSize)); - MOCK_METHOD0(ProcessAsyncStaticObjectLoadRequests, - void()); - MOCK_METHOD5(LoadStatObjAsync, - void(LoadStaticObjectAsyncResult resultCallback, const char* szFileName, const char* szGeomName, bool bUseStreaming, unsigned long nLoadingFlags)); - MOCK_METHOD1(FindStatObjectByFilename, - IStatObj*(const char* filename)); - MOCK_METHOD0(GetGSMRange, - const float()); - MOCK_METHOD0(GetGSMRangeStep, - const float()); - MOCK_METHOD0(GetLoadedObjectCount, - int()); - MOCK_METHOD2(GetLoadedStatObjArray, - void(IStatObj** pObjectsArray, int& nCount)); - MOCK_METHOD1(GetObjectsStreamingStatus, - void(SObjectsStreamingStatus& outStatus)); - MOCK_METHOD2(GetStreamingSubsystemData, - void(int subsystem, SStremaingBandwidthData& outData)); - MOCK_METHOD3(RegisterEntity, - void(IRenderNode* pEntity, int nSID, int nSIDConsideredSafe)); - MOCK_METHOD1(SelectEntity, - void(IRenderNode* pEntity)); - MOCK_METHOD0(IsSunShadows, - bool()); - MOCK_METHOD2(MakeSystemMaterialFromShaderHelper - , _smart_ptr(const char* sShaderName, SInputShaderResources* Res)); - MOCK_METHOD1(CheckMinSpecHelper - , bool(uint32 nMinSpec)); - MOCK_METHOD1(OnCasterDeleted - , void(IShadowCaster* pCaster)); - MOCK_METHOD4(GetStatObjAndMatTables, - void(DynArray* pStatObjTable, DynArray<_smart_ptr>* pMatTable, DynArray* pStatInstGroupTable, uint32 nObjTypeMask)); -#ifndef _RELEASE - MOCK_METHOD1(AddObjToDebugDrawList, - void(SObjectInfoToAddToDebugDrawList& objInfo)); - MOCK_CONST_METHOD0(IsDebugDrawListEnabled, - bool()); -#endif - MOCK_METHOD1(UnRegisterEntityDirect, - void(IRenderNode* pEntity)); - MOCK_METHOD1(UnRegisterEntityAsJob, - void(IRenderNode* pEnt)); - MOCK_CONST_METHOD1(IsUnderWater, - bool(const Vec3& vPos)); - MOCK_METHOD1(SetOceanRenderFlags, - void(uint8 nFlags)); - MOCK_CONST_METHOD0(GetOceanRenderFlags, - uint8()); - MOCK_CONST_METHOD0(GetOceanVisiblePixelsCount, - uint32()); - MOCK_METHOD3(GetBottomLevel, - float(const Vec3& referencePos, float maxRelevantDepth, int objtypes)); - MOCK_METHOD2(GetBottomLevel, - float(const Vec3& referencePos, float maxRelevantDepth)); - MOCK_METHOD2(GetBottomLevel, - float(const Vec3& referencePos, int objflags)); - MOCK_METHOD0(GetWaterLevel, - float()); - MOCK_METHOD3(GetWaterLevel, - float(const Vec3* pvPos, IPhysicalEntity* pent, bool bAccurate)); - MOCK_CONST_METHOD1(GetAccurateOceanHeight, - float(const Vec3& pCurrPos)); - MOCK_CONST_METHOD0(GetCausticsParams, - CausticsParams()); - MOCK_CONST_METHOD0(GetOceanAnimationParams, - OceanAnimationData()); - MOCK_CONST_METHOD1(GetHDRSetupParams, - void(Vec4 pParams[5])); - MOCK_METHOD0(ResetParticlesAndDecals, - void()); - MOCK_METHOD1(CreateDecal, - void(const CryEngineDecalInfo& Decal)); - MOCK_METHOD2(DeleteDecalsInRange, - void(AABB* pAreaBox, IRenderNode* pEntity)); - MOCK_METHOD1(SetSunColor, - void(Vec3 vColor)); - MOCK_METHOD0(GetSunAnimColor, - Vec3()); - MOCK_METHOD1(SetSunAnimColor, - void(const Vec3& color)); - MOCK_METHOD0(GetSunAnimSpeed, - float()); - MOCK_METHOD1(SetSunAnimSpeed, - void(float sunAnimSpeed)); - MOCK_METHOD0(GetSunAnimPhase, - AZ::u8()); - MOCK_METHOD1(SetSunAnimPhase, - void(AZ::u8 sunAnimPhase)); - MOCK_METHOD0(GetSunAnimIndex, - AZ::u8()); - MOCK_METHOD1(SetSunAnimIndex, - void(AZ::u8 sunAnimIndex)); - MOCK_METHOD1(SetRainParams, - void(const SRainParams& rainParams)); - MOCK_METHOD1(GetRainParams, - bool(SRainParams& rainParams)); - MOCK_METHOD5(SetSnowSurfaceParams, - void(const Vec3& vCenter, float fRadius, float fSnowAmount, float fFrostAmount, float fSurfaceFreezing)); - MOCK_METHOD5(GetSnowSurfaceParams, - bool(Vec3& vCenter, float& fRadius, float& fSnowAmount, float& fFrostAmount, float& fSurfaceFreezing)); - MOCK_METHOD7(SetSnowFallParams, - void(int nSnowFlakeCount, float fSnowFlakeSize, float fSnowFallBrightness, float fSnowFallGravityScale, float fSnowFallWindScale, float fSnowFallTurbulence, float fSnowFallTurbulenceFreq)); - MOCK_METHOD7(GetSnowFallParams, - bool(int& nSnowFlakeCount, float& fSnowFlakeSize, float& fSnowFallBrightness, float& fSnowFallGravityScale, float& fSnowFallWindScale, float& fSnowFallTurbulence, float& fSnowFallTurbulenceFreq)); - MOCK_METHOD1(SetMaxViewDistanceScale, - void(float fScale)); - MOCK_METHOD1(GetMaxViewDistance, - float(bool)); - MOCK_CONST_METHOD0(GetFrameLodInfo, - const SFrameLodInfo&()); - MOCK_METHOD1(SetFrameLodInfo, - void(const SFrameLodInfo& frameLodInfo)); - MOCK_METHOD1(SetFogColor, - void(const Vec3& vFogColor)); - MOCK_METHOD0(GetFogColor, - Vec3()); - MOCK_METHOD6(GetSkyLightParameters, - void(Vec3& sunDir, Vec3& sunIntensity, float& Km, float& Kr, float& g, Vec3& rgbWaveLengths)); - MOCK_METHOD7(SetSkyLightParameters, - void(const Vec3& sunDir, const Vec3& sunIntensity, float Km, float Kr, float g, const Vec3& rgbWaveLengths, bool forceImmediateUpdate)); - MOCK_CONST_METHOD0(GetLightsHDRDynamicPowerFactor, - float()); - MOCK_CONST_METHOD3(IsTessellationAllowed, - bool(const CRenderObject* pObj, const SRenderingPassInfo& passInfo, bool bIgnoreShadowPass)); - MOCK_METHOD3(SetRenderNodeMaterialAtPosition, - void(EERType eNodeType, const Vec3& vPos, _smart_ptr pMat)); - MOCK_METHOD1(OverrideCameraPrecachePoint, - void(const Vec3& vPos)); - MOCK_METHOD4(AddPrecachePoint, - int(const Vec3& vPos, const Vec3& vDir, float fTimeOut, float fImportanceFactor)); - MOCK_METHOD1(ClearPrecachePoint, - void(int id)); - MOCK_METHOD0(ClearAllPrecachePoints, - void()); - MOCK_METHOD1(GetPrecacheRoundIds, - void(int pRoundIds[MAX_STREAM_PREDICTION_ZONES])); - MOCK_METHOD5(TraceFogVolumes, - void(const Vec3& vPos, const AABB& objBBox, SFogVolumeData& fogVolData, const SRenderingPassInfo& passInfo, bool fogVolumeShadingQuality)); - - MOCK_METHOD1(RemoveAllStaticObjects, - void(int)); - MOCK_METHOD3(SetStatInstGroup, - bool(int nGroupId, const IStatInstGroup& siGroup, int nSID)); - MOCK_METHOD3(GetStatInstGroup, - bool(int, IStatInstGroup&, int)); - MOCK_METHOD3(OnExplosion, - void(Vec3, float, bool)); - MOCK_METHOD1(SetPhysMaterialEnumerator, - void(IPhysMaterialEnumerator* pPhysMaterialEnumerator)); - MOCK_METHOD0(GetPhysMaterialEnumerator, - IPhysMaterialEnumerator*()); - MOCK_METHOD0(SetupDistanceFog, - void()); - MOCK_METHOD1(LoadMissionDataFromXMLNode, - void(const char* szMissionName)); - MOCK_METHOD2(LoadEnvironmentSettingsFromXML, - void(XmlNodeRef, int)); - MOCK_METHOD0(LoadCompiledOctreeForEditor, - bool()); - MOCK_CONST_METHOD0(GetSunDir, - Vec3()); - MOCK_CONST_METHOD0(GetSunDirNormalized, - Vec3()); - MOCK_CONST_METHOD0(GetRealtimeSunDirNormalized, - Vec3()); - MOCK_METHOD0(GetDistanceToSectorWithWater, - float()); - MOCK_CONST_METHOD0(GetSunColor, - Vec3()); - MOCK_CONST_METHOD0(GetSSAOAmount, - float()); - MOCK_CONST_METHOD0(GetSSAOContrast, - float()); - MOCK_METHOD1(FreeRenderNodeState, - void(IRenderNode* pEntity)); - MOCK_METHOD1(GetLevelFilePath, - const char*(const char* szFileName)); - MOCK_METHOD4(DisplayInfo, - void(float& fTextPosX, float& fTextPosY, float& fTextStepY, bool bEnhanced)); - MOCK_METHOD0(DisplayMemoryStatistics, - void()); - - // Can't mock methods with variable parameters so just create empty bodies for them. - void DrawTextRightAligned([[maybe_unused]] const float x, [[maybe_unused]] const float y, [[maybe_unused]] const char* format, ...) override {} - void DrawTextRightAligned([[maybe_unused]] const float x, [[maybe_unused]] const float y, [[maybe_unused]] const float scale, [[maybe_unused]] const ColorF& color, [[maybe_unused]] const char* format, ...) override {} - - MOCK_METHOD3(DrawBBoxHelper - , void (const Vec3& vMin, const Vec3& vMax, ColorB col)); - MOCK_METHOD2(DrawBBoxHelper - , void (const AABB& box, ColorB col)); - - MOCK_METHOD3(ActivatePortal, - void(const Vec3& vPos, bool bActivate, const char* szEntityName)); - MOCK_CONST_METHOD1(GetMemoryUsage, - void(ICrySizer* pSizer)); - MOCK_METHOD2(GetResourceMemoryUsage, - void(ICrySizer* pSizer, const AABB& cstAABB)); - MOCK_METHOD1(CreateVisArea, - IVisArea*(uint64 visGUID)); - MOCK_METHOD1(DeleteVisArea, - void(IVisArea* pVisArea)); - MOCK_METHOD6(UpdateVisArea, - void(IVisArea* pArea, const Vec3* pPoints, int nCount, const char* szName, const SVisAreaInfo& info, bool bReregisterObjects)); - MOCK_METHOD4(IsVisAreasConnected, - bool(IVisArea* pArea1, IVisArea* pArea2, int nMaxRecursion, bool bSkipDisabledPortals)); - MOCK_METHOD0(CreateClipVolume, - IClipVolume*()); - MOCK_METHOD1(DeleteClipVolume, - void(IClipVolume* pClipVolume)); - MOCK_METHOD7(UpdateClipVolume, - void(IClipVolume* pClipVolume, _smart_ptr pRenderMesh, IBSPTree3D* pBspTree, const Matrix34& worldTM, bool bActive, uint32 flags, const char* szName)); - MOCK_METHOD1(CreateRenderNode, - IRenderNode*(EERType type)); - MOCK_METHOD1(DeleteRenderNode, - void(IRenderNode* pRenderNode)); - MOCK_METHOD1(SetWind, - void(const Vec3& vWind)); - MOCK_CONST_METHOD2(GetWind, - Vec3(const AABB& box, bool bIndoors)); - MOCK_CONST_METHOD1(GetGlobalWind, - Vec3(bool bIndoors)); - MOCK_CONST_METHOD4(SampleWind, - bool(Vec3* pSamples, int nSamples, const AABB& volume, bool bIndoors)); - MOCK_METHOD1(GetVisAreaFromPos, - IVisArea*(const Vec3& vPos)); - MOCK_METHOD2(IntersectsVisAreas, - bool(const AABB& box, void** pNodeCache)); - MOCK_METHOD4(ClipToVisAreas, - bool(IVisArea* pInside, Sphere& sphere, Vec3 const& vNormal, void* pNodeCache)); - MOCK_METHOD1(EnableOceanRendering, - void(bool bOcean)); - MOCK_METHOD1(AddTextureLoadHandler, - void(ITextureLoadHandler* pHandler)); - MOCK_METHOD1(RemoveTextureLoadHandler, - void(ITextureLoadHandler* pHandler)); - MOCK_METHOD1(GetTextureLoadHandlerForImage, - ITextureLoadHandler*(const char* ext)); - MOCK_METHOD0(CreateLightSource, - struct ILightSource*()); - MOCK_METHOD1(DeleteLightSource, - void(ILightSource* pLightSource)); - MOCK_METHOD0(GetLightEntities, - const PodArray* ()); - MOCK_METHOD3(GetLightVolumes, - void(threadID nThreadID, SLightVolume*& pLightVols, uint32& nNumVols)); - MOCK_METHOD4(RegisterVolumeForLighting, - uint16(const Vec3& vPos, f32 fRadius, uint8 nClipVolumeRef, const SRenderingPassInfo& passInfo)); - MOCK_METHOD1(RestoreTerrainFromDisk, - bool(int)); - MOCK_METHOD1(GetFilePath, - const char*(const char* szFileName)); - MOCK_CONST_METHOD0(GetPostEffectGroups, - class IPostEffectGroupManager*()); - MOCK_CONST_METHOD0(GetPostEffectBaseGroup, - class IPostEffectGroup*()); - MOCK_CONST_METHOD3(SetPostEffectParam, - void(const char* pParam, float fValue, bool bForceValue)); - MOCK_CONST_METHOD3(SetPostEffectParamVec4, - void(const char* pParam, const Vec4& pValue, bool bForceValue)); - MOCK_CONST_METHOD2(SetPostEffectParamString, - void(const char* pParam, const char* pszArg)); - MOCK_CONST_METHOD2(GetPostEffectParam, - void(const char* pParam, float& fValue)); - MOCK_CONST_METHOD2(GetPostEffectParamVec4, - void(const char* pParam, Vec4& pValue)); - MOCK_CONST_METHOD2(GetPostEffectParamString, - void(const char* pParam, const char*& pszArg)); - MOCK_METHOD1(GetPostEffectID, - int32(const char* pPostEffectName)); - MOCK_METHOD1(ResetPostEffects, - void(bool)); - MOCK_METHOD0(DisablePostEffects, - void()); - MOCK_METHOD1(SetShadowsGSMCache, - void(bool bCache)); - MOCK_METHOD2(SetCachedShadowBounds, - void(const AABB& shadowBounds, float fAdditionalCascadesScale)); - MOCK_METHOD1(SetRecomputeCachedShadows, - void(uint)); - MOCK_METHOD0(CheckMemoryHeap, - void()); - MOCK_METHOD1(DeleteEntityDecals, - void(IRenderNode* pEntity)); - MOCK_METHOD0(LockCGFResources, - void()); - MOCK_METHOD0(UnlockCGFResources, - void()); - MOCK_METHOD0(FreeUnusedCGFResources, - void()); - MOCK_METHOD0(CreateStatObj, - IStatObj*()); - MOCK_METHOD1(CreateStatObjOptionalIndexedMesh, - IStatObj*(bool createIndexedMesh)); - MOCK_METHOD0(CreateIndexedMesh, - IIndexedMesh*()); - MOCK_METHOD1(SerializeState, - void(TSerialize ser)); - MOCK_METHOD1(PostSerialize, - void(bool bReading)); - MOCK_METHOD0(GetMaterialHelpers, - IMaterialHelpers&()); - MOCK_METHOD0(GetMaterialManager, - IMaterialManager*()); - MOCK_METHOD0(GetObjManager, - IObjManager*()); - MOCK_METHOD1(CreateChunkfileContent, - CContentCGF*(const char* filename)); - MOCK_METHOD1(ReleaseChunkfileContent, - void(CContentCGF*)); - MOCK_METHOD4(LoadChunkFileContent, - bool(CContentCGF* pCGF, const char* filename, bool bNoWarningMode, bool bCopyChunkFile)); - MOCK_METHOD6(LoadChunkFileContentFromMem, - bool(CContentCGF* pCGF, const void* pData, size_t nDataLen, uint32 nLoadingFlags, bool bNoWarningMode, bool bCopyChunkFile)); - MOCK_METHOD1(CreateChunkFile, - IChunkFile*(bool)); - MOCK_CONST_METHOD3(CreateChunkFileWriter, - ChunkFile::IChunkFileWriter*(EChunkFileFormat eFormat, AZ::IO::IArchive* pPak, const char* filename)); - MOCK_CONST_METHOD1(ReleaseChunkFileWriter, - void(ChunkFile::IChunkFileWriter* p)); - MOCK_METHOD2(CreateOcean, - bool(_smart_ptr pTerrainWaterMat, float waterLevel)); - MOCK_METHOD0(DeleteOcean, - void()); - MOCK_METHOD1(ChangeOceanMaterial, - void(_smart_ptr pMat)); - MOCK_METHOD1(ChangeOceanWaterLevel, - void(float fWaterLevel)); - MOCK_METHOD1(InitMaterialDefautMappingAxis - , void(_smart_ptr pMat)); - MOCK_METHOD0(GetIVisAreaManager, - IVisAreaManager*()); - MOCK_METHOD3(PrecacheLevel, - void(bool bPrecacheAllVisAreas, Vec3* pPrecachePoints, int nPrecachePointsNum)); - MOCK_METHOD0(ProposeContentPrecache, - void()); - MOCK_METHOD0(GetTimeOfDay, - ITimeOfDay*()); - MOCK_METHOD1(SetSkyMaterialPath, - void(const string& skyMaterialPath)); - MOCK_METHOD1(SetSkyLowSpecMaterialPath, - void(const string& skyMaterialPath)); - MOCK_METHOD0(LoadSkyMaterial, - void()); - MOCK_METHOD0(GetSkyMaterial, - _smart_ptr()); - MOCK_METHOD1(SetSkyMaterial, - void(_smart_ptr pSkyMat)); - MOCK_METHOD2(SetGlobalParameter, - void(E3DEngineParameter param, const Vec3& v)); - MOCK_METHOD2(GetGlobalParameter, - void(E3DEngineParameter param, Vec3& v)); - MOCK_METHOD1(SetShadowMode, - void(EShadowMode shadowMode)); - MOCK_CONST_METHOD0(GetShadowMode, - EShadowMode()); - MOCK_METHOD6(AddPerObjectShadow, - void(IShadowCaster* pCaster, float fConstBias, float fSlopeBias, float fJitter, const Vec3& vBBoxScale, uint nTexSize)); - MOCK_METHOD1(RemovePerObjectShadow, - void(IShadowCaster* pCaster)); - MOCK_METHOD1(GetPerObjectShadow, - struct SPerObjectShadow*(IShadowCaster* pCaster)); - MOCK_METHOD2(GetCustomShadowMapFrustums, - void(struct ShadowMapFrustum*& arrFrustums, int& nFrustumCount)); - MOCK_METHOD2(SaveStatObj, - int(IStatObj* pStatObj, TSerialize ser)); - MOCK_METHOD1(LoadStatObj, - IStatObj*(TSerialize ser)); - MOCK_METHOD2(CheckIntersectClouds, - bool(const Vec3& p1, const Vec3& p2)); - MOCK_METHOD1(OnRenderMeshDeleted, - void(IRenderMesh* pRenderMesh)); - MOCK_METHOD0(DebugDraw_UpdateDebugNode, - void()); - MOCK_METHOD4(RayObjectsIntersection2D, - bool(Vec3 vStart, Vec3 vEnd, Vec3& vHitPoint, EERType eERType)); - MOCK_METHOD3(RenderMeshRayIntersection, - bool(IRenderMesh* pRenderMesh, SRayHitInfo& hitInfo, _smart_ptr pCustomMtl)); - MOCK_METHOD3(CheckCreateRNTmpData - , void(CRNTmpData** ppInfo, IRenderNode* pRNode, const SRenderingPassInfo& passInfo)); - MOCK_METHOD1(FreeRNTmpData, - void(CRNTmpData** ppInfo)); - MOCK_METHOD0(IsObjectTreeReady - , bool()); - MOCK_METHOD0(GetIObjectTree - , IOctreeNode*()); - MOCK_METHOD2(GetObjectsByType, - uint32(EERType, IRenderNode**)); - MOCK_METHOD4(GetObjectsByTypeInBox, - uint32(EERType objType, const AABB& bbox, IRenderNode** pObjects, ObjectTreeQueryFilterCallback filterCallback)); - MOCK_METHOD2(GetObjectsInBox, - uint32(const AABB& bbox, IRenderNode** pObjects)); - MOCK_METHOD2(GetObjectsByFlags, - uint32(uint, IRenderNode**)); - MOCK_METHOD4(GetObjectsByTypeInBox, - void(EERType objType, const AABB& bbox, PodArray* pLstObjects, ObjectTreeQueryFilterCallback filterCallback)); - MOCK_METHOD2(OnObjectModified, - void(IRenderNode* pRenderNode, uint dwFlags)); - MOCK_METHOD1(FillDebugFPSInfo, - void(SDebugFPSInfo&)); - MOCK_METHOD0(GetLevelFolder, - const char*()); - MOCK_METHOD0(IsAreaActivationInUse, - bool()); - MOCK_METHOD3(RenderRenderNode_ShadowPass, - void(IShadowCaster* pRNode, const SRenderingPassInfo& passInfo, AZ::LegacyJobExecutor* pJobExecutor)); - MOCK_METHOD0(GetOpticsManager, - IOpticsManager*()); - MOCK_METHOD0(SyncProcessStreamingUpdate, - void()); - MOCK_METHOD1(SetScreenshotCallback, - void(IScreenshotCallback* pCallback)); - MOCK_METHOD8(ActivateObjectsLayer, - void(uint16 nLayerId, bool bActivate, bool bPhys, bool bObjects, bool bStaticLights, const char* pLayerName, IGeneralMemoryHeap* pHeap, bool bCheckLayerActivation)); - MOCK_CONST_METHOD4(GetLayerMemoryUsage, - void(uint16 nLayerId, ICrySizer* pSizer, int* pNumBrushes, int* pNumDecals)); - MOCK_METHOD2(SkipLayerLoading, - void(uint16 nLayerId, bool bClearList)); - MOCK_METHOD2(PrecacheRenderNode, - void(IRenderNode* pObj, float fEntDistanceReal)); - MOCK_METHOD0(GetDeferredPhysicsEventManager, - IDeferredPhysicsEventManager*()); - MOCK_METHOD1(SetStreamableListener, - void(IStreamedObjectListener* pListener)); - MOCK_METHOD1(GetRenderingPassCamera, - CCamera*(const CCamera& rCamera)); - MOCK_METHOD3(GetSvoStaticTextures, - void(I3DEngine::SSvoStaticTexInfo& svoInfo, PodArray* pLightsTI_S, PodArray* pLightsTI_D)); - MOCK_METHOD2(GetSvoBricksForUpdate, - void(PodArray& arrNodeInfo, bool getDynamic)); -#if defined(USE_GEOM_CACHES) - MOCK_METHOD1(LoadGeomCache, - IGeomCache*(const char* szFileName)); - MOCK_METHOD1(FindGeomCacheByFilename, - IGeomCache*(const char* szFileName)); -#endif - MOCK_METHOD3(LoadDesignerObject, - IStatObj*(int nVersion, const char* szBinaryStream, int size)); - - MOCK_METHOD0(WaitForCullingJobsCompletion, - void()); -}; - diff --git a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h index 2021e96172..757c586261 100644 --- a/Code/CryEngine/CryCommon/Mocks/IRendererMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IRendererMock.h @@ -12,11 +12,15 @@ #pragma once #include -#include // needed for SRenderingPassInfo definition #include #include #include +struct SRendItemSorter {}; +struct SRenderingPassInfo {}; +struct SClipVolumeBlendInfo {}; +struct SFogVolumeData {}; + // the following was generated using google's python script to autogenerate mocks. // however, it needed some hand-editing to make it work, so if you add functions to IRenderer, // it will probably be better to just manually add them here than try to run the script again diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h index 5edd84fd75..4d2e80a2f3 100644 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h @@ -37,12 +37,6 @@ public: void()); MOCK_METHOD0(NeedDoWorkDuringOcclusionChecks, bool()); - MOCK_METHOD0(Render, - void()); - MOCK_METHOD0(RenderBegin, - void()); - MOCK_METHOD2(RenderEnd, - void(bool, bool)); MOCK_METHOD2(SynchronousLoadingTick, void(const char* pFunc, int line)); MOCK_METHOD0(RenderStatistics, @@ -124,8 +118,6 @@ public: IMovieSystem * ()); MOCK_METHOD0(GetIAudioSystem, Audio::IAudioSystem * ()); - MOCK_METHOD0(GetI3DEngine, - I3DEngine * ()); MOCK_METHOD0(GetIConsole, ::IConsole * ()); MOCK_METHOD0(GetIRemoteConsole, diff --git a/Code/CryEngine/CryCommon/Mocks/StubTimer.h b/Code/CryEngine/CryCommon/Mocks/StubTimer.h index fe3a11fb42..cd275ac17b 100644 --- a/Code/CryEngine/CryCommon/Mocks/StubTimer.h +++ b/Code/CryEngine/CryCommon/Mocks/StubTimer.h @@ -11,6 +11,8 @@ */ #pragma once +#include + //! Simple stub timer that exposes a single simple interface for setting the current time. class StubTimer : public ITimer diff --git a/Code/CryEngine/CryCommon/WindowsUtils.h b/Code/CryEngine/CryCommon/WindowsUtils.h deleted file mode 100644 index 96b3a86606..0000000000 --- a/Code/CryEngine/CryCommon/WindowsUtils.h +++ /dev/null @@ -1,215 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#if defined(WIN32) -#include "CryWindows.h" -#include "IRenderer.h" -#include "IImage.h" -#include "smartptr.h" -#include "ImageExtensionHelper.h" - -// Types supported by CreateResourceFromTexture -enum EResourceType -{ - eResourceType_IconBig, - eResourceType_IconSmall, - eResourceType_Cursor, -}; - -// Loads a (DDS) texture resource from the renderer into a Win32 GDI resource. -// Returns a HICON that must be closed with DestroyIcon(), or NULL on failure. -static HICON CreateResourceFromTexture(IRenderer* pRenderer, const char* path, EResourceType type) -{ - if (!pRenderer || !path || !*path) - { - // Invalid parameter passed - return NULL; - } - - // Find the target dimensions of the GDI resource - const int nRequestedWidth = GetSystemMetrics(type == eResourceType_IconBig ? SM_CXICON : type == eResourceType_IconSmall ? SM_CXSMICON : SM_CXCURSOR); - const int nRequestedHeight = GetSystemMetrics(type == eResourceType_IconBig ? SM_CYICON : type == eResourceType_IconSmall ? SM_CYSMICON : SM_CYCURSOR); - if (nRequestedWidth != nRequestedHeight || nRequestedHeight <= 0 || nRequestedWidth <= 0) - { - // Don't support non-squares icons or cursors - return NULL; - } - - // Load texture. - // in this case, we want to fall back on a null, not substiture the missing texture. - _smart_ptr pImage = pRenderer->EF_LoadImage(path, FIM_NOFALLBACKS); - if (!pImage || pImage->mfGet_depth() != 1 || pImage->mfGet_NumSides() != 1 || pImage->mfGetTileMode() != eTM_None) - { - // Can't load texture, or texture is a cube-map or volume texture, or uses tiling of some kind - return NULL; - } - byte* pImgRaw = pImage->mfGet_image(0); - const ETEX_Format texFormat = pImage->mfGetFormat(); - - // Pick first mip level smaller than the GDI resource - int nMip = 0; - size_t offset = 0; - int nMipWidth = pImage->mfGet_width(); - int nMipHeight = pImage->mfGet_height(); - while (nMipWidth > nRequestedWidth) - { - ++nMip; - offset += pRenderer->GetTextureFormatDataSize(nMipWidth, nMipHeight, 1, 1, texFormat); - nMipWidth = max(nMipWidth / 2, 1); - nMipHeight = max(nMipHeight / 2, 1); - } - pImgRaw += offset; - if (nMip >= pImage->mfGet_numMips()) - { - // No appropriate mip in the texture - // Note: Consider creating a full mip-chain on the texture so this can't happen - return NULL; - } - const size_t nRawSize = pRenderer->GetTextureFormatDataSize(nMipWidth, nMipHeight, 1, 1, texFormat); - -#if 0 - // Check that DDS indexing is correct here - offset += nRawSize; - for (int nIdx = nMip + 1; nIdx < pImage->mfGet_numMips(); ++nIdx) - { - const int w = max(nMipWidth >> (nIdx - nMip), 1); - const int h = max(nMipHeight >> (nIdx - nMip), 1); - offset += pRenderer->GetTextureFormatDataSize(w, h, 1, 1, texFormat); - } - assert(offset == pImage->mfGet_ImageSize()); -#endif - - // Type of bitmap to create - BITMAPV5HEADER bi = { 0 }; - bi.bV5Size = sizeof(BITMAPV5HEADER); - bi.bV5Width = nRequestedWidth; - bi.bV5Height = -nRequestedHeight; - bi.bV5Planes = 1; - bi.bV5BitCount = 32; - bi.bV5Compression = BI_BITFIELDS; - // The following mask specification specifies a supported 32 BPP alpha format for Windows XP+ - bi.bV5AlphaMask = 0xFF000000; - bi.bV5RedMask = 0x00FF0000; - bi.bV5GreenMask = 0x0000FF00; - bi.bV5BlueMask = 0x000000FF; - - // Create the DIB section with an alpha channel - const HDC hdc = GetDC(NULL); - void* lpBits; - const HBITMAP hBitmap = CreateDIBSection(hdc, (BITMAPINFO*)&bi, DIB_RGB_COLORS, &lpBits, NULL, 0); - ReleaseDC(NULL, hdc); - if (!hBitmap || !lpBits) - { - // Can't allocate OS bitmap - return NULL; - } - GdiFlush(); - - // Decompress texture - const bool bTryDecompress = texFormat != eTF_R8G8B8A8 && texFormat != eTF_B8G8R8A8 && texFormat != eTF_B8G8R8X8; - byte* const pImgDecomp = bTryDecompress ? new byte[nMipWidth * nMipHeight * sizeof(int32)] : pImgRaw; - const bool bImgDecompressed = bTryDecompress && pRenderer->DXTDecompress(pImgRaw, nRawSize, pImgDecomp, nMipWidth, nMipHeight, 1, texFormat, false, sizeof(int32)); - - // Check which conversions need to be performed - const bool bSRGB = (pImage->mfGet_Flags() & CImageExtensionHelper::EIF_SRGBRead) != 0; - const bool bSwap = (texFormat == eTF_R8G8B8A8) || bTryDecompress; - - HICON result = NULL; - if (!bTryDecompress || bImgDecompressed) - { - // Assign texture data with mismatching sizes - // Note: Any pixels not in the selected mip will become 100% transparent black, no resizing is performed - const size_t sourceRowStride = nMipWidth; - const size_t targetRowStride = nRequestedWidth; - const uint32* pSourceRow = (uint32*)pImgDecomp; - uint32* pTargetRow = (uint32*)lpBits; - - assert(sourceRowStride <= targetRowStride); - assert(nMipHeight <= nRequestedHeight); - assert(pSourceRow != pTargetRow); - assert(pSourceRow && pTargetRow); - - uint8 gammaTable[256]; - if (!bSRGB) - { - // Linear to sRGB table - const float gamma = 1.0f / 2.2f; - const float gammaMultiplier = 255.0f / powf(255.0f, gamma); - for (int i = 0; i < 256; ++i) - { - gammaTable[i] = uint8(powf(float(i), gamma) * gammaMultiplier); - } - } - else if (bSwap) - { - // sRGB to sRGB table (no change) - for (int i = 0; i < 256; ++i) - { - gammaTable[i] = uint8(i); - } - } - - for (int y = 0; y < nMipHeight; ++y, pSourceRow += sourceRowStride, pTargetRow += targetRowStride) - { - if (!bSwap && bSRGB) - { - memcpy(pTargetRow, pSourceRow, sourceRowStride * sizeof(uint32)); - } - else - { - const uint32* pSourceTexel = pSourceRow; - uint32* pTargetTexel = pTargetRow; - for (int x = 0; x < nMipWidth; ++x, ++pSourceTexel, ++pTargetTexel) - { - const uint8 red = gammaTable[uint8(*pSourceTexel >> 0)]; - const uint8 green = gammaTable[uint8(*pSourceTexel >> 8)]; - const uint8 blue = gammaTable[uint8(*pSourceTexel >> 16)]; - const uint32 alpha = *pSourceTexel & 0xFF000000; - *pTargetTexel = (red << (bSwap ? 16 : 0)) | (green << 8) | (blue << (bSwap ? 0 : 16)) | alpha; - } - } - - // Fill remaining columns with zeros - memset(pTargetRow + sourceRowStride, 0, (targetRowStride - sourceRowStride) * sizeof(uint32)); - } - - // Fill remaining rows with zeros - for (int y = nMipHeight; y < nRequestedHeight; ++y) - { - memset(pTargetRow, 0, targetRowStride * sizeof(uint32)); - pTargetRow += targetRowStride; - } - - // Convert to GDI icon - ICONINFO iconinfo = {0}; - iconinfo.fIcon = type == eResourceType_Cursor ? FALSE : TRUE; - iconinfo.hbmMask = ::CreateBitmap(nRequestedWidth, nRequestedHeight, 1, 1, NULL); - iconinfo.hbmColor = hBitmap; - result = ::CreateIconIndirect(&iconinfo); - DeleteObject(iconinfo.hbmMask); - } - - // Clean up - DeleteObject(hBitmap); - if (bTryDecompress) - { - delete[] pImgDecomp; - } - pImage.reset(); - - return result; -} - -#endif diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index ef49370c08..7d169c2643 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -14,9 +14,6 @@ set(FILES CryCommon.cpp Allocator.h FinalizingSpline.h - Gem.h - I3DEngine.h - I3DEngine_info.h IAudioInterfacesCommonData.h IAudioSystem.h IChunkFile.h @@ -86,7 +83,6 @@ set(FILES ITexture.h IThreadManager.h IThreadTask.h - ITimeOfDay.h ITimer.h IValidator.h IVideoRenderer.h @@ -143,7 +139,6 @@ set(FILES CryAssert.h CryCrc32.h CryCustomTypes.h - CryEngineDecalInfo.h CryFile.h CryFixedArray.h CryFixedString.h @@ -292,7 +287,6 @@ set(FILES platform_impl.cpp Win32specific.h Win64specific.h - WindowsUtils.h CryExtension/CryCreateClassInstance.h CryExtension/CryGUID.h CryExtension/CryTypeID.h @@ -317,7 +311,6 @@ set(FILES CryPool/STLWrapper.h CryPool/ThreadSafe.h stl/STLAlignedAlloc.h - ILocalMemoryUsage.h Serialization/Assert.h Serialization/BitVector.h Serialization/BitVectorImpl.h diff --git a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake index ca133c2497..d20a33f791 100644 --- a/Code/CryEngine/CryCommon/crycommon_testing_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_testing_files.cmake @@ -10,7 +10,6 @@ # set(FILES - Mocks/I3DEngineMock.h Mocks/IAudioSystemMock.h Mocks/IConsoleMock.h Mocks/ICryPakMock.h diff --git a/Code/CryEngine/CrySystem/CrySystem_precompiled.h b/Code/CryEngine/CrySystem/CrySystem_precompiled.h index 6cf4c6005a..b446199b4e 100644 --- a/Code/CryEngine/CrySystem/CrySystem_precompiled.h +++ b/Code/CryEngine/CrySystem/CrySystem_precompiled.h @@ -102,7 +102,6 @@ inline int RoundToClosestMB(size_t memSize) #include #include #include -#include #include #include #include @@ -127,7 +126,6 @@ namespace AZ::IO struct IArchive; } struct ICryFont; -struct I3DEngine; struct IMovieSystem; struct IAudioSystem; struct IPhysicalWorld; diff --git a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp index 996dee7810..d31f122d9b 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/LevelSystem.cpp @@ -193,10 +193,6 @@ static void UnloadMap([[maybe_unused]] IConsoleCmdArgs* args) if (gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) { gEnv->pSystem->GetILevelSystem()->UnloadLevel(); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->LoadEmptyLevel(); - } } } @@ -674,18 +670,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) pSpamDelay->Set(0.0f); } - if (gEnv->p3DEngine) - { - bool is3DEngineLoaded = gEnv->IsEditor() ? gEnv->p3DEngine->InitLevelForEditor(pLevelInfo->GetPath(), pLevelInfo->m_defaultGameTypeName.c_str()) - : gEnv->p3DEngine->LoadLevel(pLevelInfo->GetPath(), pLevelInfo->m_defaultGameTypeName.c_str()); - if (!is3DEngineLoaded) - { - OnLoadingError(levelName, "3DEngine failed to handle loading the level"); - - return 0; - } - } - // Parse level specific config data. AZStd::string const sLevelNameOnly(PathUtil::GetFileName(levelName)); @@ -760,14 +744,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PRECACHE); - ////////////////////////////////////////////////////////////////////////// - // Notify 3D engine that loading finished - ////////////////////////////////////////////////////////////////////////// - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->PostLoadLevel(); - } - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// gEnv->pConsole->SetScrollMax(600 / 2); @@ -991,18 +967,6 @@ void CLevelSystem::UnloadLevel() CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); - I3DEngine* p3DEngine = gEnv->p3DEngine; - if (p3DEngine) - { - IDeferredPhysicsEventManager* pPhysEventManager = p3DEngine->GetDeferredPhysicsEventManager(); - if (pPhysEventManager) - { - // clear deferred physics queues before renderer, since we could have jobs running - // which access a rendermesh - pPhysEventManager->ClearDeferredEvents(); - } - } - //AM: Flush render thread (Flush is not exposed - using EndFrame()) //We are about to delete resources that could be in use if (gEnv->pRenderer) @@ -1076,25 +1040,10 @@ void CLevelSystem::UnloadLevel() SAFE_RELEASE(m_pCurrentLevel); - /* - Force Lua garbage collection before p3DEngine->UnloadLevel() and pRenderer->FreeResources(flags) are called. - p3DEngine->UnloadLevel() will destroy particle emitters even if they're still referenced by Lua objects that are yet to be collected. - (as per comment in 3dEngineLoad.cpp (line 501) - "Force to clean all particles that are left, even if still referenced."). - Then, during the next GC cycle, Lua finally cleans up, the particle emitter smart pointers will be pointing to invalid memory). - Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event), which is too late - (after the render resources have been purged). - This extra GC step takes a few ms more level unload time, which is a small price for fixing nasty crashes. - If, however, we wanted to claim it back, we could potentially get rid of the GC step that is triggered by ESYSTEM_EVENT_LEVEL_POST_UNLOAD to break even. - */ - + // Force Lua garbage collection (may no longer be needed now the legacy renderer has been removed). + // Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event). EBUS_EVENT(AZ::ScriptSystemRequestBus, GarbageCollect); - // Delete engine resources - if (p3DEngine) - { - p3DEngine->UnloadLevel(); - - } // Force to clean render resources left after deleting all objects and materials. IRenderer* pRenderer = gEnv->pRenderer; if (pRenderer) diff --git a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index 67bf0a6c8e..4b6e210522 100644 --- a/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/CryEngine/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -55,10 +55,6 @@ namespace LegacyLevelSystem if (gEnv->pSystem && gEnv->pSystem->GetILevelSystem() && !gEnv->IsEditor()) { gEnv->pSystem->GetILevelSystem()->UnloadLevel(); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->LoadEmptyLevel(); - } } } @@ -262,22 +258,6 @@ namespace LegacyLevelSystem pSpamDelay->Set(0.0f); } - if (gEnv->p3DEngine) - { - AZ::IO::PathView levelPath(levelName); - AZStd::string parentPath(levelPath.ParentPath().Native()); - - static constexpr const char* defaultGameTypeName = "Mission0"; - bool is3DEngineLoaded = gEnv->IsEditor() ? gEnv->p3DEngine->InitLevelForEditor(parentPath.c_str(), defaultGameTypeName) - : gEnv->p3DEngine->LoadLevel(parentPath.c_str(), defaultGameTypeName); - if (!is3DEngineLoaded) - { - OnLoadingError(levelName, "3DEngine failed to handle loading the level"); - - return 0; - } - } - // Parse level specific config data. AZStd::string const sLevelNameOnly(PathUtil::GetFileName(levelName)); @@ -340,14 +320,6 @@ namespace LegacyLevelSystem gEnv->pSystem->SetSystemGlobalState(ESYSTEM_GLOBAL_STATE_LEVEL_LOAD_START_PRECACHE); - ////////////////////////////////////////////////////////////////////////// - // Notify 3D engine that loading finished - ////////////////////////////////////////////////////////////////////////// - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->PostLoadLevel(); - } - ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// gEnv->pConsole->SetScrollMax(600 / 2); @@ -569,18 +541,6 @@ namespace LegacyLevelSystem CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); - I3DEngine* p3DEngine = gEnv->p3DEngine; - if (p3DEngine) - { - IDeferredPhysicsEventManager* pPhysEventManager = p3DEngine->GetDeferredPhysicsEventManager(); - if (pPhysEventManager) - { - // clear deferred physics queues before renderer, since we could have jobs running - // which access a rendermesh - pPhysEventManager->ClearDeferredEvents(); - } - } - // AM: Flush render thread (Flush is not exposed - using EndFrame()) // We are about to delete resources that could be in use if (gEnv->pRenderer) @@ -644,25 +604,10 @@ namespace LegacyLevelSystem GetISystem()->GetIResourceManager()->UnloadLevel(); - /* - Force Lua garbage collection before p3DEngine->UnloadLevel() and pRenderer->FreeResources(flags) are called. - p3DEngine->UnloadLevel() will destroy particle emitters even if they're still referenced by Lua objects that are yet to be - collected. (as per comment in 3dEngineLoad.cpp (line 501) - "Force to clean all particles that are left, even if still referenced."). - Then, during the next GC cycle, Lua finally cleans up, the particle emitter smart pointers will be pointing to invalid memory). - Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event), which is too late - (after the render resources have been purged). - This extra GC step takes a few ms more level unload time, which is a small price for fixing nasty crashes. - If, however, we wanted to claim it back, we could potentially get rid of the GC step that is triggered by - ESYSTEM_EVENT_LEVEL_POST_UNLOAD to break even. - */ - + // Force Lua garbage collection (may no longer be needed now the legacy renderer has been removed). + // Normally the GC step is triggered at the end of this method (by the ESYSTEM_EVENT_LEVEL_POST_UNLOAD event). EBUS_EVENT(AZ::ScriptSystemRequestBus, GarbageCollect); - // Delete engine resources - if (p3DEngine) - { - p3DEngine->UnloadLevel(); - } // Force to clean render resources left after deleting all objects and materials. IRenderer* pRenderer = gEnv->pRenderer; if (pRenderer) diff --git a/Code/CryEngine/CrySystem/PerfHUD.cpp b/Code/CryEngine/CrySystem/PerfHUD.cpp index 23a5fc0ced..2aeabe2650 100644 --- a/Code/CryEngine/CrySystem/PerfHUD.cpp +++ b/Code/CryEngine/CrySystem/PerfHUD.cpp @@ -22,7 +22,6 @@ #include "MiniGUI/MiniMenu.h" #include "MiniGUI/MiniTable.h" #include -#include #include #include "System.h" @@ -853,21 +852,6 @@ void CPerfHUD::SaveStatsCallback([[maybe_unused]] void* data, [[maybe_unused]] b // RENDER CALLBACKS ////////////////////////////////////////////////////////////////////////// -/* -void CPerfHUD::DisplayRenderInfoCallback(const Rect& rect) -{ - IMiniGUIPtr pGUI; - if (CryCreateClassInstanceForInterface( cryiidof(),pGUI )) - { - //right aligned display - float x = rect.right; - float y = rect.top; - float step = 13.f; - - gEnv->p3DEngine->DisplayInfo(x, y, step, true); - } -}*/ - void CPerfHUD::EnableWidget(ICryPerfHUDWidget::EWidgetID id, int mode) { const int nWidgets = m_widgets.size(); @@ -1530,26 +1514,6 @@ void CRenderStatsWidget::Update() m_runtimeData.nFwdLights = 0; m_runtimeData.nFwdShadowLights = 0; - ////////////////////////////////////////////////////////////////////////// - if (gEnv->p3DEngine) - { - I3DEngine::SObjectsStreamingStatus objStats; - gEnv->p3DEngine->GetObjectsStreamingStatus(objStats); - - float fMeshRequiredMB = (float)(objStats.nMemRequired) / (1024 * 1024); - sprintf_s(entryBuffer, "Mesh Required: %.2f (%dMB)", fMeshRequiredMB, azlossy_cast(objStats.nMeshPoolSize)); - if (fMeshRequiredMB < objStats.nMeshPoolSize) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "Too Many Geometry: %.2fMB", fMeshRequiredMB); - } - } - - ////////////////////////////////////////////////////////////////////////// if (gEnv->pRenderer) { @@ -1727,25 +1691,6 @@ CStreamingStatsWidget::CStreamingStatsWidget(IMiniCtrl* pParentMenu, ICryPerfHUD ////////////////////////////////////////////////////////////////////////// void CStreamingStatsWidget::Update() { - char entryBuffer[CMiniInfoBox::MAX_TEXT_LENGTH] = {0}; - - //Clear old entries - m_pInfoBox->ClearEntries(); - - I3DEngine::SObjectsStreamingStatus objStats; - gEnv->p3DEngine->GetObjectsStreamingStatus(objStats); - - float fMeshRequiredMB = (float)(objStats.nMemRequired) / (1024 * 1024); - sprintf_s(entryBuffer, "Mesh Required: %.2f (%dMB)", fMeshRequiredMB, objStats.nMeshPoolSize); - if (fMeshRequiredMB < objStats.nMeshPoolSize) - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_NORM, CPerfHUD::TEXT_SIZE_NORM); - } - else - { - m_pInfoBox->AddEntry(entryBuffer, CPerfHUD::COL_ERROR, CPerfHUD::TEXT_SIZE_NORM); - CryPerfHUDWarning(1.f, "Too Many Geometry: %.2fMB", fMeshRequiredMB); - } } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.cpp b/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.cpp deleted file mode 100644 index 7eb86de966..0000000000 --- a/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.cpp +++ /dev/null @@ -1,1389 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Visual helper for checking a local memory usage on maps - -/* - TODO: - - Procedural vegetation - - - Permanent mip-map problem (streaming will collect a permanent mip-maps when travelling) - - ? Foliage render nodes - - must make a decision about the local / global problem: - - Particle effects (must check the calculation) - - Characters (calculation is DONE) - - - StatObj LOD streaming (I think that there is no LOD streaming, but i'm not sure about this) - - Terrain texture streaming (not detail textures!) //It's not needed because this system using a fix-size pool - - Animation streaming: completely different system, not need to measure now - - IsoMesh streaming: completely different system, not need to measure now -*/ - - -#include "CrySystem_precompiled.h" - -#include "LocalMemoryUsage.h" - -#include -#include -#include -#include - -#include - -//#define MAX_LODS 6 // I want an engine-wide const :-( -#define MAX_SLOTS 100 // GetSlotCount() is not working :-( -#define BIG_NUMBER 1e20f - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -namespace LocalMemoryUsageDrawHelper -{ - enum eDrawRectParams - { - DSP_YDIR = 0, - DSP_XDIR = 1, - DSP_REVERSE_TRIANGLES = 2, - DSP_REVERSE_ARROW = 4, - }; - - void DrawRect(IRenderer* pRenderer, const CCamera* camera, const Vec3& p1, const Vec3& p3, const ColorB& color, int params = 0) - { - Vec3 p2, p4, projectedPos; - if (!(params & DSP_REVERSE_TRIANGLES)) - { - if (params & DSP_XDIR) - { - p2 = Vec3(p1.x, p3.y, p1.z); - p4 = Vec3(p3.x, p1.y, p3.z); - } - else - { - p2 = Vec3(p1.x, p3.y, p3.z); - p4 = Vec3(p3.x, p1.y, p1.z); - } - } - else - { - if (params & DSP_XDIR) - { - p4 = Vec3(p1.x, p3.y, p1.z); - p2 = Vec3(p3.x, p1.y, p3.z); - } - else - { - p4 = Vec3(p1.x, p3.y, p3.z); - p2 = Vec3(p3.x, p1.y, p1.z); - } - } - - if (camera->Project(p1, projectedPos) || camera->Project(p2, projectedPos) || camera->Project(p3, projectedPos) || camera->Project(p4, projectedPos)) - { - IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); - - pRenderAuxGeom->DrawTriangle(p1, color, p2, color, p3, color); - pRenderAuxGeom->DrawTriangle(p3, color, p4, color, p1, color); - } - } - - void DrawArrow(IRenderer* pRenderer, const CCamera* camera, Vec3 pStart, Vec3 pEnd, float width, float head, float lengthSub, const ColorB& color, int params = 0) - { - Vec3 p1, p2, p3, p4, p5, p6, p7, projectedPos; - - if (params & DSP_REVERSE_ARROW) - { - std::swap(pStart, pEnd); - } - - Vec3 vParallel((pEnd - pStart).GetNormalized()); - Vec3 vOrto = vParallel.Cross(Vec3(0, 0, 1)).GetNormalized(); - pStart += vParallel * lengthSub; - pEnd -= vParallel * lengthSub; - - p1 = pStart - (vOrto * width * 0.5f); - p2 = pStart + (vOrto * width * 0.5f); - p3 = (pEnd - vParallel * head) - (vOrto * width * 0.5f); - p4 = (pEnd - vParallel * head) + (vOrto * width * 0.5f); - p5 = (pEnd - vParallel * head * 1.5f) - (vOrto * head * 0.9f); - p6 = (pEnd - vParallel * head * 1.5f) + (vOrto * head * 0.9f); - p7 = pEnd; - - if (camera->Project(p1, projectedPos) || camera->Project(p7, projectedPos)) - { - IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); - - pRenderAuxGeom->DrawTriangle(p1, color, p2, color, p4, color); - pRenderAuxGeom->DrawTriangle(p4, color, p3, color, p1, color); - pRenderAuxGeom->DrawTriangle(p3, color, p4, color, p7, color); - pRenderAuxGeom->DrawTriangle(p4, color, p6, color, p7, color); - pRenderAuxGeom->DrawTriangle(p5, color, p3, color, p7, color); - } - } - - #define DRAWHELPER_CIRCLE_POINT_NR 32 - - - static Vec3 s_CirclePoints[DRAWHELPER_CIRCLE_POINT_NR + 1]; - static bool s_CircleDataInited = false; - void InitCircleData() - { - s_CircleDataInited = true; - float angleDiff = 2.0f * 3.1415927f / DRAWHELPER_CIRCLE_POINT_NR; - - for (int i = 0; i < DRAWHELPER_CIRCLE_POINT_NR + 1; i++) - { - s_CirclePoints[i] = Vec3(cos(i * angleDiff), sin(i * angleDiff), 0.0f); - } - } - - void DrawCircle(IRenderer* pRenderer, [[maybe_unused]] const CCamera* camera, const Vec3& origo, float radius, float ratio, const ColorB& color1, const ColorB& color2) - { - if (!s_CircleDataInited) - { - InitCircleData(); - } - float radius2 = radius * 0.90f; - - IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); - - Vec3 oldPoint = origo + s_CirclePoints[0] * radius; - Vec3 oldPoint2 = origo + s_CirclePoints[0] * radius2; - - for (int i = 0; i < DRAWHELPER_CIRCLE_POINT_NR; i++) - { - Vec3 newPoint = origo + s_CirclePoints[i + 1] * radius; - Vec3 newPoint2 = origo + s_CirclePoints[i + 1] * radius2; - if (i < ratio * DRAWHELPER_CIRCLE_POINT_NR) - { - pRenderAuxGeom->DrawTriangle(origo, color1, oldPoint, color1, newPoint, color1); - } - else - { - //pRenderAuxGeom->DrawTriangle( origo, color2, oldPoint, color2, newPoint, color2 ); - pRenderAuxGeom->DrawTriangle(oldPoint2, color2, oldPoint, color2, newPoint, color2); - pRenderAuxGeom->DrawTriangle(newPoint, color2, newPoint2, color2, oldPoint2, color2); - } - oldPoint = newPoint; - oldPoint2 = newPoint2; - } - } -} - -/* -namespace Distance -{ - // Distance: AABB_AABB - //---------------------------------------------------------------------------------- - // Calculate the closest distance of a AABB to an another AABB in 3d-space. - // The function returns the squared distance. - // optionally the closest point on the hull is calculated - // - // Example: - // float result = Distance::Point_AABBSq( aabb1, aabb2 ); - //---------------------------------------------------------------------------------- - - ILINE float AABB_AABBSq( const AABB& aabb1, const AABB& aabb2 ) - { - float fDist2 = 0; - for(int i=0; i<3; ++i) - { - float max1 = aabb1.max[i]; - if(max1 < aabb2.min[i]) - { - fDist2 += sqr(max1-aabb2.min[i]); - } - else - { - float min1 = aabb1.min[i]; - if(min1 > aabb2.max[i]) - { - fDist2 += sqr(aabb2.max[i]-min1); - } - } - } - return fDist2; - } - - // Distance: AABB_AABB_2D - //---------------------------------------------------------------------------------- - // Calculate the closest distance of a AABB to an another AABB in 2d-space. - // The function returns the squared distance. - // optionally the closest point on the hull is calculated - // - // Example: - // float result = Distance::AABB_AABB2DSq( aabb1, aabb2 ); - //---------------------------------------------------------------------------------- - - ILINE float AABB_AABB2DSq( const AABB& aabb1, const AABB& aabb2 ) - { - float fDist2 = 0; - for(int i=0; i<2; ++i) //We are using only 2 of the dimensions! - { - float max1 = aabb1.max[i]; - if(max1 < aabb2.min[i]) - { - fDist2 += sqr(max1-aabb2.min[i]); - } - else - { - float min1 = aabb1.min[i]; - if(min1 > aabb2.max[i]) - { - fDist2 += sqr(aabb2.max[i]-min1); - } - } - } - return fDist2; - } -} -*/ - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -int CLocalMemoryUsage::SResource::m_arrMemoryUsage[LOCALMEMORY_SECTOR_PER_PASS]; -int CLocalMemoryUsage::SResource::m_arrPieces[LOCALMEMORY_SECTOR_PER_PASS]; - - -CLocalMemoryUsage::SResource::SResource() -{ - m_used = true; -} - -void CLocalMemoryUsage::SResource::Init(CLocalMemoryUsage* pLocalMemoryUsage) -{ - m_pLocalMemoryUsage = pLocalMemoryUsage; - - StartChecking(); -} - -void CLocalMemoryUsage::SResource::StartChecking() -{ - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - float* pMipFactor = m_arrMipFactor; - for (int i = 0; i < actProcessedSectors.w * actProcessedSectors.h; i++) - { - *pMipFactor = BIG_NUMBER; - pMipFactor++; - } - bool* pRowDirty = m_arrRowDirty; - for (int i = 0; i < LOCALMEMORY_SECTOR_PER_PASS; i++) - { - *pRowDirty = false; - pRowDirty++; - } -} - -void CLocalMemoryUsage::SResource::CheckOnAllSectorsP1(const AABB& bounding, float maxViewDist, float scale, float mipFactor) -{ - //FRAME_PROFILER("! CLocalMemoryUsage::SResource::CheckOnAllSectorsP1", GetISystem(), PROFILE_SYSTEM); - - float modifiedmaxViewDist = maxViewDist; - float modifiedmaxViewDistSqr = sqr(modifiedmaxViewDist); - - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - int xMin = (int)max(0, int((bounding.min.x - modifiedmaxViewDist) / LOCALMEMORY_SECTOR_SIZE ) - actProcessedSectors.x); - int xMax = (int)min(actProcessedSectors.w, int((bounding.max.x + modifiedmaxViewDist) / LOCALMEMORY_SECTOR_SIZE + 1) - actProcessedSectors.x); - int yMin = (int)max(0, int((bounding.min.y - modifiedmaxViewDist) / LOCALMEMORY_SECTOR_SIZE ) - actProcessedSectors.y); - int yMax = (int)min(actProcessedSectors.h, int((bounding.max.y + modifiedmaxViewDist) / LOCALMEMORY_SECTOR_SIZE + 1) - actProcessedSectors.y); - - AABB sectorBounding(AABB::RESET); - float sectorDistanceSqr; - float fDistYSqr; - - for (int y = yMin; y < yMax; y++) - { - float* pMipFactor = &m_arrMipFactor[actProcessedSectors.w * y + xMin]; - - sectorBounding.min.y = (y + actProcessedSectors.y) * LOCALMEMORY_SECTOR_SIZE; - sectorBounding.max.y = sectorBounding.min.y + LOCALMEMORY_SECTOR_SIZE; - sectorBounding.min.x = (xMin + actProcessedSectors.x) * LOCALMEMORY_SECTOR_SIZE; - - assert(y < LOCALMEMORY_SECTOR_PER_PASS); - m_arrRowDirty[y] = true; - - //Calculating Y distance sqr - { - fDistYSqr = 0; - if (bounding.max.y < sectorBounding.min.y) - { - fDistYSqr += sqr(bounding.max.y - sectorBounding.min.y); - } - else - { - if (bounding.min.y > sectorBounding.max.y) - { - fDistYSqr += sqr(sectorBounding.max.y - bounding.min.y); - } - } - } - - for (int x = xMin; x < xMax; x++) - { - sectorBounding.max.x = sectorBounding.min.x + LOCALMEMORY_SECTOR_SIZE; - - //sectorDistanceSqr = Distance::AABB_AABB2DSq(bounding, sectorBounding); - - //Adding X distance sqr - { - sectorDistanceSqr = fDistYSqr; - if (bounding.max.x < sectorBounding.min.x) - { - sectorDistanceSqr += sqr(bounding.max.x - sectorBounding.min.x); - } - else - { - if (bounding.min.x > sectorBounding.max.x) - { - sectorDistanceSqr += sqr(sectorBounding.max.x - bounding.min.x); - } - } - } - - if (sectorDistanceSqr < modifiedmaxViewDistSqr) - { - *pMipFactor = min(*pMipFactor, sectorDistanceSqr * scale * scale * mipFactor); - } - - pMipFactor++; - - sectorBounding.min.x = sectorBounding.max.x; - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::STextureInfo::STextureInfo() -{ - m_pTexture = NULL; - - //m_size = 0; - //m_xSize = 0; - //m_ySize = 0; - //m_numMips = 0; -} - -CLocalMemoryUsage::STextureInfo::~STextureInfo() -{ - if (m_pTexture) - { - m_pTexture->Release(); - } -} - -void CLocalMemoryUsage::STextureInfo::CheckOnAllSectorsP2() -{ - int x, y, nMip, nStreamableMipNr, memoryUsage, xOldMemoryUsage, xOldPieces; - bool nonZero; - ITexture* pTexture; - - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - bool wasDirty = false; - for (y = 0; y < actProcessedSectors.h; y++) - { - int* pMemoryUsage = m_arrMemoryUsage; - int* pPieces = m_arrPieces; - if (m_arrRowDirty[y] || (wasDirty)) - { - SSector* sector = &m_pLocalMemoryUsage->m_arrSectors[(y + actProcessedSectors.y) * LOCALMEMORY_SECTOR_NR_X + actProcessedSectors.x]; - float* pMipFactor = &m_arrMipFactor[y * actProcessedSectors.w ]; - xOldMemoryUsage = 0; - xOldPieces = 0; - for (x = 0; x < actProcessedSectors.w; x++) - { - nonZero = (*pMipFactor != BIG_NUMBER); - if (nonZero) // One more row - { - pTexture = m_pTexture; - if (!nonZero) - { - memoryUsage = 0; - nStreamableMipNr = 0; - } - else - { - nMip = max(0, pTexture->StreamCalculateMipsSigned(*pMipFactor)); - memoryUsage = pTexture->GetStreamableMemoryUsage(nMip); - nStreamableMipNr = pTexture->GetStreamableMipNumber() - nMip; - } - - sector->m_memoryUsage_Textures += memoryUsage; - - xOldMemoryUsage = memoryUsage; - *pMemoryUsage = memoryUsage; - xOldPieces = nStreamableMipNr; - *pPieces = nStreamableMipNr; - } - else - { - xOldMemoryUsage = 0; - *pMemoryUsage = 0; - xOldPieces = 0; - *pPieces = 0; - } - sector++; - pMipFactor++; - pMemoryUsage++; - pPieces++; - } - wasDirty = m_arrRowDirty[y]; - } - else - { - for (x = 0; x < actProcessedSectors.w; x++) - { - *pMemoryUsage = 0; - pMemoryUsage++; - *pPieces = 0; - pPieces++; - } - wasDirty = false; - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::SMaterialInfo::SMaterialInfo() -{ -} - -void CLocalMemoryUsage::SMaterialInfo::AddTextureInfo(STextureInfoAndTilingFactor textureInfo) -{ - m_textures.push_back(textureInfo); -} - -void CLocalMemoryUsage::SMaterialInfo::CheckOnAllSectorsP2() -{ - int x, y; - - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - for (y = 0; y < actProcessedSectors.h; y++) - { - if (m_arrRowDirty[y]) - { - float* pMipFactor = &m_arrMipFactor[y * actProcessedSectors.w ]; - for (x = 0; x < actProcessedSectors.w; x++) - { - if (*pMipFactor != BIG_NUMBER) - { - //(Spidy) Send the material MinDistance values to textures - for (TTextureVector::iterator it = m_textures.begin(); it != m_textures.end(); ++it) - { - STextureInfoAndTilingFactor& textureInfo = *it; - textureInfo.m_pTextureInfo->m_arrRowDirty[y] = true; - - float& textureMipFactor = textureInfo.m_pTextureInfo->m_arrMipFactor[actProcessedSectors.w * y + x]; - textureMipFactor = min(textureMipFactor, *pMipFactor * textureInfo.m_tilingFactor); - } - } - pMipFactor++; - } - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::SStatObjInfo::SStatObjInfo() -{ - m_streamableContentMemoryUsage = 0; - - m_bSubObject = false; - /* - m_lodNr = 0; - m_vertices = 0; - m_indices = 0; - m_meshSize = 0; - m_physProxySize = 0; - m_physPrimitives = 0; - for( int i=0; i < MAX_LODS; i++) - { - m_indicesPerLod[i]=0; - } - */ -} - -void CLocalMemoryUsage::SStatObjInfo::CheckOnAllSectorsP2() -{ - int x, y, memoryUsage, pieces, xOldMemoryUsage, xOldPieces; - bool nonZero; - - const RectI& actProcessedSectors = m_pLocalMemoryUsage->m_actProcessedSectors; - - bool wasDirty = false; - for (y = 0; y < actProcessedSectors.h; y++) - { - int* pMemoryUsage = m_arrMemoryUsage; - int* pPieces = m_arrPieces; - if (m_arrRowDirty[y]) - { - SSector* sector = &m_pLocalMemoryUsage->m_arrSectors[(y + actProcessedSectors.y) * LOCALMEMORY_SECTOR_NR_X + actProcessedSectors.x]; - float* pMipFactor = &m_arrMipFactor[y * actProcessedSectors.w ]; - xOldMemoryUsage = 0; - xOldPieces = 0; - for (x = 0; x < actProcessedSectors.w; x++) - { - nonZero = (*pMipFactor != BIG_NUMBER); - if (nonZero) // One more row - { - /* - memoryUsage = 0; - float minDistance = sqrt_tpl(minDistanceSqr); - CStatObj* pStatObj = (CStatObj*)(m_pStatObj.get()); //(Spidy) Huh... - - //Iterate on all subobjects, like CStatObj::UpdateStreamableComponents - float fSubObjectScale = 1.0f; - //float fSubObjectScale = matSubObject.GetColumn0().GetLength(); //TODO - int lod = pStatObj->GetLodFromScale(1.0f, fSubObjectScale, minDistance, false); - //(Spidy) az objMatrix scale es a fLodRatioNorm mar bele vannak szamolva a minDistance-ba! - memoryUsage = m_streamableContentMemoryUsage; - */ - memoryUsage = m_streamableContentMemoryUsage; - pieces = 1; - - if (!nonZero) - { - memoryUsage = 0; - pieces = 0; - } - - sector->m_memoryUsage_Geometry += memoryUsage; - - xOldMemoryUsage = memoryUsage; - *pMemoryUsage = memoryUsage; - xOldPieces = pieces; - *pPieces = pieces; - } - else - { - xOldMemoryUsage = 0; - *pMemoryUsage = 0; - xOldPieces = 0; - *pPieces = 0; - } - sector++; - pMipFactor++; - pMemoryUsage++; - pPieces++; - } - wasDirty = m_arrRowDirty[y]; - } - else - { - for (x = 0; x < actProcessedSectors.w; x++) - { - *pMemoryUsage = 0; - pMemoryUsage++; - *pPieces = 0; - pPieces++; - } - wasDirty = false; - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::SSector::SSector() -{ - StartChecking(); -} - -void CLocalMemoryUsage::SSector::StartChecking() -{ - m_memoryUsage_Textures = 0; - m_memoryUsage_Geometry = 0; -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -CLocalMemoryUsage::CLocalMemoryUsage() -{ - REGISTER_CVAR(sys_LocalMemoryTextureLimit, 64, VF_NULL, "LocalMemoryUsage tool: Set the texture memory limit to check streaming (Mb/sec)"); - REGISTER_CVAR(sys_LocalMemoryGeometryLimit, 32, VF_NULL, "LocalMemoryUsage tool: Set the statobj geometry memory limit to check streaming (Mb/sec)"); - REGISTER_CVAR(sys_LocalMemoryTextureStreamingSpeedLimit, 10, VF_NULL, "LocalMemoryUsage tool: Texture streaming speed limit (approx, Mb/sec)"); - REGISTER_CVAR(sys_LocalMemoryGeometryStreamingSpeedLimit, 10, VF_NULL, "LocalMemoryUsage tool: Stat object geometry streaming speed limit (approx, Mb/sec)"); - - REGISTER_CVAR(sys_LocalMemoryWarningRatio, 0.8f, VF_NULL, "LocalMemoryUsage tool: Warning ratio for streaming"); - REGISTER_CVAR(sys_LocalMemoryOuterViewDistance, 500.f, VF_NULL, "LocalMemoryUsage tool: View distance for debug draw"); - REGISTER_CVAR(sys_LocalMemoryInnerViewDistance, 100.f, VF_NULL, "LocalMemoryUsage tool: View distance for detailed debug draw"); - - REGISTER_CVAR(sys_LocalMemoryStreamingSpeedObjectLength, 10.f, VF_NULL, "LocalMemoryUsage tool: Length of the streaming speed debug object"); - REGISTER_CVAR(sys_LocalMemoryStreamingSpeedObjectWidth, 1.5f, VF_NULL, "LocalMemoryUsage tool: Width of the streaming speed debug object"); - REGISTER_CVAR(sys_LocalMemoryObjectWidth, 6.f, VF_NULL, "LocalMemoryUsage tool: Width of the streaming buffer debug object"); - REGISTER_CVAR(sys_LocalMemoryObjectHeight, 2.f, VF_NULL, "LocalMemoryUsage tool: Height of the streaming buffer debug object"); - REGISTER_CVAR(sys_LocalMemoryObjectAlpha, 128, VF_NULL, "LocalMemoryUsage tool: Color alpha of the debug objects"); - - REGISTER_CVAR(sys_LocalMemoryDiagramWidth, 0.5f, VF_NULL, "LocalMemoryUsage tool: Width of the diagrams OBSOLATE"); - - REGISTER_CVAR(sys_LocalMemoryDiagramRadius, 2.5f, VF_NULL, "LocalMemoryUsage tool: Radius of the diagram"); - REGISTER_CVAR(sys_LocalMemoryDiagramDistance, -5.5f, VF_NULL, "LocalMemoryUsage tool: Distance of the diagram from the main debug object"); - REGISTER_CVAR(sys_LocalMemoryDiagramStreamingSpeedRadius, 1.0f, VF_NULL, "LocalMemoryUsage tool: Radius of the streaming speed diagram"); - REGISTER_CVAR(sys_LocalMemoryDiagramStreamingSpeedDistance, 2.2f, VF_NULL, "LocalMemoryUsage tool: Distance of the streaming speed diagram from the streaming speed debug line"); - REGISTER_CVAR(sys_LocalMemoryDiagramAlpha, 255, VF_NULL, "LocalMemoryUsage tool: Color alpha of the diagrams"); - - REGISTER_CVAR(sys_LocalMemoryDrawText, 0, VF_NULL, "LocalMemoryUsage tool: If != 0, it will draw the numeric values"); - REGISTER_CVAR(sys_LocalMemoryLogText, 0, VF_NULL, "LocalMemoryUsage tool: If != 0, it will log the numeric values"); - - REGISTER_CVAR(sys_LocalMemoryOptimalMSecPerSec, 100, VF_NULL, "LocalMemoryUsage tool: Optimal calculation time (MSec) per secundum"); - REGISTER_CVAR(sys_LocalMemoryMaxMSecBetweenCalls, 1000, VF_NULL, "LocalMemoryUsage tool: Maximal time difference (MSec) between calls"); - - m_pStreamCgfPredicitionDistance = 0; - m_pDebugDraw = 0; - if (gEnv->pConsole) - { - m_pStreamCgfPredicitionDistance = gEnv->pConsole->GetCVar("e_StreamCgfPredicitionDistance"); - m_pDebugDraw = gEnv->pConsole->GetCVar("e_DebugDraw"); - } - - m_sectorNr.zero(); - - m_actProcessedSectors = RectI(0, 0, 0, 0); - m_actDrawedSectors = RectI(0, 0, 0, 0); - - m_AverageUpdateTime = 0.01f; - - m_sectorNr.x = LOCALMEMORY_SECTOR_NR_X; //TODO Check size of the world - m_sectorNr.y = LOCALMEMORY_SECTOR_NR_Y; -} - -CLocalMemoryUsage::~CLocalMemoryUsage() -{ - DeleteGlobalData(); -} - -void CLocalMemoryUsage::DeleteGlobalData() -{ - m_globalTextures.clear(); - m_globalMaterials.clear(); - m_globalStatObjs.clear(); -} - -void CLocalMemoryUsage::OnRender(IRenderer* pRenderer, const CCamera* camera) -{ - if (!m_pDebugDraw || (m_pDebugDraw->GetIVal() != 17)) - { - return; - } - - const Matrix34& mat = camera->GetMatrix(); - Vec3 pos; - Vec3 projectedPos; - SSector* sector; - - SAuxGeomRenderFlags auxGeomRenderFlagsClose(e_Mode3D | e_AlphaBlended | e_DrawInFrontOn | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOff); - SAuxGeomRenderFlags auxGeomRenderFlagsFar(e_Mode3D | e_AlphaBlended | e_DrawInFrontOff | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOn); - - IRenderAuxGeom* pRenderAuxGeom = pRenderer->GetIRenderAuxGeom(); - - Vec3 cameraPos = mat.GetTranslation(); - - int xMin = max(0, int((cameraPos.x - sys_LocalMemoryOuterViewDistance) / LOCALMEMORY_SECTOR_SIZE)); - int xMax = min(LOCALMEMORY_SECTOR_PER_PASS - 1, int((cameraPos.x + sys_LocalMemoryOuterViewDistance) / LOCALMEMORY_SECTOR_SIZE + 1)); - int yMin = max(0, int((cameraPos.y - sys_LocalMemoryOuterViewDistance) / LOCALMEMORY_SECTOR_SIZE)); - int yMax = min(LOCALMEMORY_SECTOR_PER_PASS - 1, int((cameraPos.y + sys_LocalMemoryOuterViewDistance) / LOCALMEMORY_SECTOR_SIZE + 1)); - m_actDrawedSectors.x = xMin; - m_actDrawedSectors.y = yMin; - m_actDrawedSectors.w = xMax - xMin + 1; - m_actDrawedSectors.h = yMax - yMin + 1; - - CTimeValue actTime = gEnv->pTimer->GetAsyncTime(); - float timeSin = sin_tpl(actTime.GetSeconds() * 10.0f) * 0.5f + 0.5f; - - ColorB color; - ColorB colorOK(LOCALMEMORY_COLOR_OK, sys_LocalMemoryObjectAlpha); - ColorB colorWarning(LOCALMEMORY_COLOR_WARNING, sys_LocalMemoryObjectAlpha); - ColorB colorError(LOCALMEMORY_COLOR_ERROR, uint8(sys_LocalMemoryObjectAlpha * timeSin)); - ColorB colorTexture(LOCALMEMORY_COLOR_TEXTURE, sys_LocalMemoryDiagramAlpha); - ColorB colorGeometry(LOCALMEMORY_COLOR_GEOMETRY, sys_LocalMemoryDiagramAlpha); - ColorB colorBlack(LOCALMEMORY_COLOR_BLACK); - f32 fColorOK[4] = {LOCALMEMORY_FCOLOR_OK, 1}; - f32 fColorWarning[4] = {LOCALMEMORY_FCOLOR_WARNING, 1}; - f32 fColorError[4] = {LOCALMEMORY_FCOLOR_ERROR, 1}; - f32 fColorOther[4] = {LOCALMEMORY_FCOLOR_OTHER, 1}; - - f32* pColor; - Vec3 v0, v1, v2, v3, v4, vTextureDiagram, vTextureDiagram2, vGeometryDiagram, vGeometryDiagram2; - - float localMemoryTextureLimit = sys_LocalMemoryTextureLimit * 1024.f * 1024.f; - float localMemoryGeometryLimit = sys_LocalMemoryGeometryLimit * 1024.f * 1024.f; - - //The assumption is that this is called on Main Thread, otherwise the loop - //Should be wrapped inside a EnumerateHandlers lambda. - auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); - const float defaultTerrainHeight = AzFramework::Terrain::TerrainDataRequests::GetDefaultTerrainHeight(); - - for (int y = yMin; y < yMax; y++) - { - sector = &m_arrSectors[xMin + y * LOCALMEMORY_SECTOR_NR_X]; - for (int x = xMin; x < xMax; x++) - { - pos.x = (x + 0.5f) * LOCALMEMORY_SECTOR_SIZE; - pos.y = (y + 0.5f) * LOCALMEMORY_SECTOR_SIZE; - pos.z = terrain ? terrain->GetHeightFromFloats(pos.x, pos.y) : defaultTerrainHeight; - - if (m_pDebugDraw->GetIVal() == 17) - { - float textureRatio = sector->m_memoryUsage_Textures / localMemoryTextureLimit; - float geometryRatio = sector->m_memoryUsage_Geometry / localMemoryGeometryLimit; - float maxRatio = max(textureRatio, geometryRatio); - - v0 = pos; - v1 = pos + Vec3(-sys_LocalMemoryObjectWidth, -sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectHeight); - v2 = pos + Vec3(sys_LocalMemoryObjectWidth, -sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectHeight); - v3 = pos + Vec3(sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectHeight); - v4 = pos + Vec3(-sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectWidth, sys_LocalMemoryObjectHeight); - - if (camera->Project(v1, projectedPos) || camera->Project(v2, projectedPos) || camera->Project(v3, projectedPos) || camera->Project(v4, projectedPos)) - { - vTextureDiagram = pos + Vec3(0.f, sys_LocalMemoryObjectWidth + sys_LocalMemoryDiagramDistance + sys_LocalMemoryDiagramRadius, sys_LocalMemoryObjectHeight); - vGeometryDiagram = pos + Vec3(0.f, -sys_LocalMemoryObjectWidth - sys_LocalMemoryDiagramDistance - sys_LocalMemoryDiagramRadius, sys_LocalMemoryObjectHeight); - - if (maxRatio < sys_LocalMemoryWarningRatio) - { - color = colorOK; - pColor = fColorOK; - } - else if (maxRatio < 1.0f) - { - color = colorWarning; - pColor = fColorWarning; - } - else - { - color = colorError; - pColor = fColorError; - } - - bool close = (Distance::Point_Point2D(cameraPos, pos) < sys_LocalMemoryInnerViewDistance); - if (close) - { - pRenderAuxGeom->SetRenderFlags(auxGeomRenderFlagsClose); - - static int xDebug = 14; - static int yDebug = 19; - - if (sys_LocalMemoryDrawText) - { - camera->Project(pos, projectedPos); - - pRenderer->Draw2dLabel(projectedPos.x, projectedPos.y, 1.2f, pColor, true, "Text: %.2fMb Geom: %.2fMb", sector->m_memoryUsage_Textures / (1024.f * 1024.f), sector->m_memoryUsage_Geometry / (1024.f * 1024.f)); - /* For sector debugging - pRenderer->Draw2dLabel(projectedPos.x, projectedPos.y, 1.2f, pColor, true, "Text: %.1fMb Geom: %.1fMb - %d : %d", sector->m_memoryUsage_Textures/(1024.f*1024.f), sector->m_memoryUsage_Geometry/(1024.f*1024.f), x, y); - - if( xDebug == x && yDebug == y ) - { - float sx = projectedPos.x-80; - float sy = projectedPos.y; - - for( TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it ) - { - SStatObjInfo *statObjInfo = &it->second; - IStatObj* pStatObj = statObjInfo->m_pStatObj; - - int memoryUsage = 0; - float mipFactor = statObjInfo->m_arrMipFactor[y * m_actProcessedSectors.w + x]; - if( mipFactor != BIG_NUMBER ) - { - memoryUsage = statObjInfo->m_streamableContentMemoryUsage; - } - sy+=15.f; - pRenderer->Draw2dLabel(sx, sy, 1.2f, pColor, false, "Geom: %.2fMb %.4f Act:%s Orig:%s %s", memoryUsage/(1024.f*1024.f), mipFactor, pStatObj->GetFilePath(), statObjInfo->m_filePath, statObjInfo->m_bSubObject ? " SUBOBJECT" : ""); - //pRenderer->Draw2dLabel(sx, sy, 1.2f, pColor, false, "Geom: %.2fMb %.4f", memoryUsage/(1024.f*1024.f), mipFactor); - } - } - //*/ - } - if (sys_LocalMemoryLogText) - { - if (xDebug == x && yDebug == y) - { - for (TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it) - { - STextureInfo* textureObjInfo = &it->second; - ITexture* pTexture = textureObjInfo->m_pTexture; - - float mipFactor = textureObjInfo->m_arrMipFactor[y * m_actProcessedSectors.w + x]; - if (mipFactor != BIG_NUMBER) - { - CryLog("Texture: %s %dX%d mipfactor:%.4f", pTexture->GetName(), pTexture->GetWidth(), pTexture->GetHeight(), mipFactor); - } - } - sys_LocalMemoryLogText = false; //Log only once! - } - } - } - else - { - pRenderAuxGeom->SetRenderFlags(auxGeomRenderFlagsFar); - } - - pRenderAuxGeom->DrawTriangle(v1, color, v2, color, v3, color); - pRenderAuxGeom->DrawTriangle(v3, color, v4, color, v1, color); - - pRenderAuxGeom->DrawTriangle(v0, color, v1, color, v4, color); - pRenderAuxGeom->DrawTriangle(v0, color, v2, color, v1, color); - pRenderAuxGeom->DrawTriangle(v0, color, v3, color, v2, color); - pRenderAuxGeom->DrawTriangle(v0, color, v4, color, v3, color); - - if (close) - { - LocalMemoryUsageDrawHelper::DrawCircle(pRenderer, camera, vTextureDiagram, sys_LocalMemoryDiagramRadius, textureRatio, colorTexture, colorBlack); - LocalMemoryUsageDrawHelper::DrawCircle(pRenderer, camera, vGeometryDiagram, sys_LocalMemoryDiagramRadius, geometryRatio, colorGeometry, colorBlack); - } - } - } - - sector++; - } - } -} - -void CLocalMemoryUsage::OnUpdate() -{ - if (!m_pDebugDraw || (m_pDebugDraw->GetIVal() != 17)) - { - return; - } - - //CryLogAlways("OnUpdate start-----------------------------------------"); - CTimeValue actTime = gEnv->pTimer->GetAsyncTime(); - - float callTimeDiff = (actTime - m_LastCallTime).GetSeconds(); - float neededCallTimeDiff = m_AverageUpdateTime / (sys_LocalMemoryOptimalMSecPerSec / 1000.f); - - if (callTimeDiff < neededCallTimeDiff && callTimeDiff < sys_LocalMemoryMaxMSecBetweenCalls / 1000.f) - { - return; - } - - DeleteUnusedResources(); - - m_LastCallTime = actTime; - - { - FRAME_PROFILER("! LocalMemoryUsege::Update - Start", GetISystem(), PROFILE_SYSTEM); - //StartChecking(RectI(0,0,m_sectorNr.x, m_sectorNr.y)); - StartChecking(m_actDrawedSectors); - } - - { - FRAME_PROFILER("! LocalMemoryUsege::Update - CollectGeometry P1", GetISystem(), PROFILE_SYSTEM); - CollectGeometryP1(); - } - - { - FRAME_PROFILER("! LocalMemoryUsege::Update - Materials P2", GetISystem(), PROFILE_SYSTEM); - //We must iterate on materials first - for (TMaterialMap::iterator it = m_globalMaterials.begin(); it != m_globalMaterials.end(); ++it) - { - it->second.CheckOnAllSectorsP2(); - } - } - { - FRAME_PROFILER("! LocalMemoryUsege::Update - Textures P2", GetISystem(), PROFILE_SYSTEM); - for (TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it) - { - it->second.CheckOnAllSectorsP2(); - } - } - { - FRAME_PROFILER("! LocalMemoryUsege::Update - StatObjects P2", GetISystem(), PROFILE_SYSTEM); - for (TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it) - { - it->second.CheckOnAllSectorsP2(); - } - } - - CTimeValue endTime = gEnv->pTimer->GetAsyncTime(); - m_AverageUpdateTime = LERP(m_AverageUpdateTime, (endTime - actTime).GetSeconds(), 0.5f); - - //CryLogAlways("OnUpdate end***"); -} - -void CLocalMemoryUsage::DeleteUnusedResources() -{ - FRAME_PROFILER("! LocalMemoryUsege::Update - Deleting unused resources", GetISystem(), PROFILE_SYSTEM); - - // Clear the used flags - for (TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it) - { - it->second.m_used = false; - } - - // Iterate on used StatObjs - int nCount; - gEnv->p3DEngine->GetLoadedStatObjArray(NULL, nCount); - std::vector objectsArray; - objectsArray.resize(nCount); - if (nCount > 0) - { - gEnv->p3DEngine->GetLoadedStatObjArray(&objectsArray[0], nCount); - } - - for (std::vector::iterator it = objectsArray.begin(); it != objectsArray.end(); ++it) - { - IStatObj* pStatObj = *it; - TStatObjMap::iterator findIt = m_globalStatObjs.find((INT_PTR)pStatObj); - - if (findIt != m_globalStatObjs.end() && strcmp(pStatObj->GetFilePath(), findIt->second.m_filePath) == 0 && !findIt->second.m_bSubObject) - { - findIt->second.m_used = true; - } - - if (pStatObj->GetFlags() & STATIC_OBJECT_COMPOUND) - { - for (int k = 0; k < pStatObj->GetSubObjectCount(); k++) - { - if (!pStatObj->GetSubObject(k)) - { - continue; - } - - IStatObj* pSubStatObj = pStatObj->GetSubObject(k)->pStatObj; - - if (pSubStatObj) - { - findIt = m_globalStatObjs.find((INT_PTR)pSubStatObj); - - if (findIt != m_globalStatObjs.end() && strcmp(pSubStatObj->GetFilePath(), findIt->second.m_filePath) == 0 && findIt->second.m_bSubObject) - { - findIt->second.m_used = true; - } - } - } - } - } - - // Erase non-used StatObjs - bool changed = true; - while (changed) - { - changed = false; - for (TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it) - { - if (!it->second.m_used) - { - m_globalStatObjs.erase(it); - changed = true; - break; - } - } - } - /* - for( TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it ) - it->second.m_used = false; - - bool changed = true; - while( changed ) - { - changed = false; - for( TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it ) - { - if( !it->second.m_used ) - { - m_globalTextures.erase(it); - changed = true; - break; - } - } - } - - for( TMaterialMap::iterator it = m_globalMaterials.begin(); it != m_globalMaterials.end(); ++it ) - it->second.m_used = false; - - changed = true; - while( changed ) - { - changed = false; - for( TMaterialMap::iterator it = m_globalMaterials.begin(); it != m_globalMaterials.end(); ++it ) - { - if( !it->second.m_used ) - { - m_globalMaterials.erase(it); - changed = true; - break; - } - } - } - //*/ -} -void CLocalMemoryUsage::StartChecking(const RectI& actProcessedSectors) -{ - m_actProcessedSectors = actProcessedSectors; - - for (int y = 0; y < m_sectorNr.y; y++) - { - SSector* sector = &m_arrSectors[y * LOCALMEMORY_SECTOR_NR_X]; - for (int x = 0; x < m_sectorNr.x; x++) - { - sector->StartChecking(); - sector++; - } - } - - { - for (TTextureMap::iterator it = m_globalTextures.begin(); it != m_globalTextures.end(); ++it) - { - //FRAME_PROFILER("! LocalMemoryUsege::StartChecking - Textures", GetISystem(), PROFILE_SYSTEM); - it->second.StartChecking(); - } - } - { - for (TMaterialMap::iterator it = m_globalMaterials.begin(); it != m_globalMaterials.end(); ++it) - { - //FRAME_PROFILER("! LocalMemoryUsege::StartChecking - Materials", GetISystem(), PROFILE_SYSTEM); - it->second.StartChecking(); - } - } - { - for (TStatObjMap::iterator it = m_globalStatObjs.begin(); it != m_globalStatObjs.end(); ++it) - { - //FRAME_PROFILER("! LocalMemoryUsege::StartChecking - StatObjects", GetISystem(), PROFILE_SYSTEM); - it->second.StartChecking(); - } - } -} - -void CLocalMemoryUsage::CollectGeometryP1() -{ - ISystem* pSystem = GetISystem(); - I3DEngine* p3DEngine = pSystem->GetI3DEngine(); - - // iterate through all instances - std::vector renderNodes; - - uint32 dwCount = 0; - - dwCount += p3DEngine->GetObjectsByType(eERType_Light); - - dwCount += p3DEngine->GetObjectsByType(eERType_RenderComponent); - dwCount += p3DEngine->GetObjectsByType(eERType_SkinnedMeshRenderComponent); - dwCount += p3DEngine->GetObjectsByType(eERType_StaticMeshRenderComponent); - dwCount += p3DEngine->GetObjectsByType(eERType_DynamicMeshRenderComponent); - dwCount += p3DEngine->GetObjectsByType(eERType_Decal); - - if (dwCount > 0) - { - renderNodes.resize(dwCount + 1); - dwCount = 0; - - dwCount += p3DEngine->GetObjectsByType(eERType_Light, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_RenderComponent, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_StaticMeshRenderComponent, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_DynamicMeshRenderComponent, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_SkinnedMeshRenderComponent, &renderNodes[dwCount]); - dwCount += p3DEngine->GetObjectsByType(eERType_Decal, &renderNodes[dwCount]); - - AABB objBox; - - for (uint32 dwI = 0; dwI < dwCount; ++dwI) - { - IRenderNode* pRenderNode = renderNodes[dwI]; - - if (pRenderNode->m_fWSMaxViewDist < 0.01f) - { - continue; - } - - float objScale = 1.f; - if (pRenderNode->GetRenderNodeType() == eERType_Decal) - { - IDecalRenderNode* pDecal = (IDecalRenderNode*)pRenderNode; - objScale = max(0.001f, pDecal->GetMatrix().GetColumn0().GetLength()); - } - else if (pRenderNode->GetRenderNodeType() == eERType_FogVolume) - { - objScale = max(0.001f, ((IFogVolumeRenderNode*)pRenderNode)->GetMatrix().GetColumn0().GetLength()); - } - - float maxViewDist = pRenderNode->m_fWSMaxViewDist; - pRenderNode->FillBBox(objBox); - - _smart_ptr pRenderNodeMat = pRenderNode->GetMaterialOverride(); - - { - IStatObj* pStatObj = pRenderNode->GetEntityStatObj(); - - if (pStatObj != NULL) - { - CheckStatObjMaterialP1(pStatObj, pRenderNodeMat, objBox, maxViewDist, objScale); - } - else - { - CheckMeshMaterialP1(pRenderNode->GetRenderMesh(0), pRenderNodeMat, objBox, maxViewDist, objScale); - } - } - - for (int dwSlot = 0; dwSlot < pRenderNode->GetSlotCount(); ++dwSlot) - { - _smart_ptr pSlotMat = pRenderNode->GetEntitySlotMaterial(dwSlot); - if (!pSlotMat) - { - pSlotMat = pRenderNodeMat; - } - - Matrix34A matParent; - - if (IStatObj* pStatObj = pRenderNode->GetEntityStatObj(dwSlot, 0, &matParent, true)) - { - CheckStatObjP1(pStatObj, pRenderNode, objBox, maxViewDist, objScale); - - _smart_ptr pStatObjMat = pStatObj->GetMaterial(); - CheckStatObjMaterialP1(pStatObj, pSlotMat ? pSlotMat : pStatObjMat, objBox, maxViewDist, objScale); - } - } - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -PREFAST_SUPPRESS_WARNING(6262); -CLocalMemoryUsage::SStatObjInfo* CLocalMemoryUsage::CheckStatObjP1(IStatObj* pStatObj, [[maybe_unused]] IRenderNode* pRenderNode, AABB bounding, float maxViewDist, float scale) -{ - if (!pStatObj) - { - return NULL; - } - - if (strncmp(pStatObj->GetFilePath(), "%level%", 7) == 0) //HACK %LEVEL% brushes - { - return NULL; - } - - SStatObjInfo* pStatObjInfo = NULL; - - TStatObjMap::iterator iter = m_globalStatObjs.find((INT_PTR)pStatObj); - if (iter != m_globalStatObjs.end()) - { - pStatObjInfo = &iter->second; - pStatObjInfo->m_streamableContentMemoryUsage = pStatObj->GetStreamableContentMemoryUsage(); //TODO TEMP - } - else - { - { - FRAME_PROFILER("! CLocalMemoryUsage::CheckStatObjP1 HASH", GetISystem(), PROFILE_SYSTEM); - PREFAST_SUPPRESS_WARNING(6262) - pStatObjInfo = &m_globalStatObjs[(INT_PTR)pStatObj]; - } - - pStatObjInfo->Init(this); - pStatObjInfo->m_streamableContentMemoryUsage = pStatObj->GetStreamableContentMemoryUsage(); - //pStatObjInfo->m_pStatObj = pStatObj; - pStatObjInfo->m_filePath = pStatObj->GetFilePath(); - pStatObjInfo->m_bSubObject = pStatObj->IsSubObject(); - //CollectStatObjInfo_Recursive( pStatObjInfo, pStatObj ); - } - - pStatObjInfo->CheckOnAllSectorsP1(bounding, maxViewDist, scale, 1.0f); - - return pStatObjInfo; -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -PREFAST_SUPPRESS_WARNING(6262); -void CLocalMemoryUsage::CheckMaterialP1(_smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale, float mipFactor) -{ - if (pMaterial) - { - SMaterialInfo* pMaterialInfo = NULL; - - TMaterialMap::iterator iter = m_globalMaterials.find((INT_PTR)pMaterial.get()); - if (iter != m_globalMaterials.end()) - { - pMaterialInfo = &iter->second; - } - else - { - { - FRAME_PROFILER("! CLocalMemoryUsage::CheckMaterialP1 HASH", GetISystem(), PROFILE_SYSTEM); - PREFAST_SUPPRESS_WARNING(6262) - pMaterialInfo = &m_globalMaterials[(INT_PTR)pMaterial.get()]; - } - pMaterialInfo->Init(this); - //pMaterialInfo->m_pMaterial=pMaterial; - CollectMaterialInfo_Recursive(pMaterialInfo, pMaterial); - } - - pMaterialInfo->CheckOnAllSectorsP1(bounding, maxViewDist, scale, mipFactor); - } -} - -PREFAST_SUPPRESS_WARNING(6262); -void CLocalMemoryUsage::CheckChunkMaterialP1(_smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale, CRenderChunk* pRenderChunk) -{ - _smart_ptr pCurrentMaterial = pMaterial; - - if (pRenderChunk != NULL) - { - if (pRenderChunk->m_nMatID < pMaterial->GetSubMtlCount()) - { - pCurrentMaterial = pMaterial->GetSubMtl(pRenderChunk->m_nMatID); - } - - if (pCurrentMaterial != NULL) - { - CheckMaterialP1(pCurrentMaterial, bounding, maxViewDist, scale, pRenderChunk->m_texelAreaDensity); - } - } - else - { - CheckMaterialP1(pCurrentMaterial, bounding, maxViewDist, scale, 1.f); - } -} - -PREFAST_SUPPRESS_WARNING(6262); -void CLocalMemoryUsage::CheckMeshMaterialP1(IRenderMesh* pRenderMesh, _smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale) -{ - if (pRenderMesh) - { - if (pMaterial) - { - TRenderChunkArray* pChunks = &pRenderMesh->GetChunks(); - - if (pChunks != NULL) - { - for (unsigned int i = 0; i < pChunks->size(); i++) - { - CheckChunkMaterialP1(pMaterial, bounding, maxViewDist, scale, &(*pChunks)[i]); - } - } - - pChunks = &pRenderMesh->GetChunksSkinned(); - for (unsigned int i = 0; i < pChunks->size(); i++) - { - CheckChunkMaterialP1(pMaterial, bounding, maxViewDist, scale, &(*pChunks)[i]); - } - } - } - else - { - if (pMaterial) - { - CheckChunkMaterialP1(pMaterial, bounding, maxViewDist, scale, NULL); - } - } -} - -void CLocalMemoryUsage::CheckStatObjMaterialP1(IStatObj* pStatObj, _smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale) -{ - if (pStatObj) - { - for (int i = 0; i < pStatObj->GetSubObjectCount(); i++) - { - CheckStatObjMaterialP1(pStatObj->GetSubObject(i)->pStatObj, pMaterial, bounding, scale, maxViewDist); - } - - CheckMeshMaterialP1(pStatObj->GetRenderMesh(), pMaterial, bounding, maxViewDist, scale); - } -} - -void CLocalMemoryUsage::CollectMaterialInfo_Recursive(SMaterialInfo* materialInfo, _smart_ptr pMaterial) -{ - SShaderItem& rItem = pMaterial->GetShaderItem(); - - uint32 dwSubMatCount = pMaterial->GetSubMtlCount(); - - for (uint32 dwSubMat = 0; dwSubMat < dwSubMatCount; ++dwSubMat) - { - _smart_ptr pSub = pMaterial->GetSubMtl(dwSubMat); - - if (pSub) - { - CollectMaterialInfo_Recursive(materialInfo, pSub); - } - } - - // this pMaterial - if (rItem.m_pShaderResources) - { - for (auto iter = rItem.m_pShaderResources->GetTexturesResourceMap()->begin(); - iter != rItem.m_pShaderResources->GetTexturesResourceMap()->end(); ++iter) - { - const SEfResTexture* pTextureRes = &iter->second; - - if (pTextureRes->m_Sampler.m_pITex) - { - ITexture* pTexture = pTextureRes->m_Sampler.m_pITex; - if (pTexture && pTexture->GetStreamableMipNumber() > 0) - { - STextureInfoAndTilingFactor textureInfo; - - textureInfo.m_pTextureInfo = GetTextureInfo(pTexture); - textureInfo.m_tilingFactor = pTextureRes->GetTiling(0) * pTextureRes->GetTiling(1); - - materialInfo->AddTextureInfo(textureInfo); - } - } - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -PREFAST_SUPPRESS_WARNING(6262) -CLocalMemoryUsage::STextureInfo * CLocalMemoryUsage::GetTextureInfo(ITexture * pTexture) -{ - if (!pTexture) - { - return NULL; - } - - TTextureMap::iterator iter = m_globalTextures.find((INT_PTR)pTexture); - if (iter != m_globalTextures.end()) - { - return &iter->second; - } - - //FUNCTION_PROFILER(GetISystem(), PROFILE_SYSTEM); - STextureInfo* pTextureInfo; - { - FRAME_PROFILER("! CLocalMemoryUsage::CheckStatObjP1 HASH", GetISystem(), PROFILE_SYSTEM); - PREFAST_SUPPRESS_WARNING(6262) - pTextureInfo = &m_globalTextures[(INT_PTR)pTexture]; - } - pTextureInfo->Init(this); - pTextureInfo->m_pTexture = pTexture; - pTexture->AddRef(); - - //Collect informations - //pTextureInfo->m_size = pTexture->GetDeviceDataSize(); - //pTextureInfo->m_xSize = pTexture->GetWidth(); - //pTextureInfo->m_ySize = pTexture->GetHeight(); - //pTextureInfo->m_numMips = pTexture->GetNumMips(); - - return pTextureInfo; -} - -///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.h b/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.h deleted file mode 100644 index 450e2eb2f9..0000000000 --- a/Code/CryEngine/CrySystem/Statistics/LocalMemoryUsage.h +++ /dev/null @@ -1,245 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Visual helper for checking a local memory usage on maps - - -#ifndef CRYINCLUDE_CRYSYSTEM_STATISTICS_LOCALMEMORYUSAGE_H -#define CRYINCLUDE_CRYSYSTEM_STATISTICS_LOCALMEMORYUSAGE_H -#pragma once - - -#include "../CryCommon/Cry_Geo.h" -#include "ILocalMemoryUsage.h" -#include "TimeValue.h" - -#define LOCALMEMORY_SECTOR_SIZE 32.f //Size of one sector -#define LOCALMEMORY_SECTOR_NR_X 128 //4096 / LOCALMEMORY_SECTOR_SIZE Sector number of the world (x) -#define LOCALMEMORY_SECTOR_NR_Y 128 //4096 / LOCALMEMORY_SECTOR_SIZE Sector number of the world (y) -#define LOCALMEMORY_SECTOR_PER_PASS 128 //4096 / 32 Sector nr for one calculation pass. Now it is the whole world; - -//Sector number must be = LOCALMEMORY_SECTOR_PER_PASS * n - -#define LOCALMEMORY_COLOR_OK 0, 255, 0 -#define LOCALMEMORY_COLOR_WARNING 255, 255, 0 -#define LOCALMEMORY_COLOR_ERROR 255, 0, 0 -#define LOCALMEMORY_COLOR_TEXTURE 0, 0, 255 -#define LOCALMEMORY_COLOR_GEOMETRY 0, 0, 0 -#define LOCALMEMORY_COLOR_BLACK 0, 0, 0, 192 -#define LOCALMEMORY_FCOLOR_OK 0, 1, 0 -#define LOCALMEMORY_FCOLOR_WARNING 1, 1, 0 -#define LOCALMEMORY_FCOLOR_ERROR 1, 0, 0 -#define LOCALMEMORY_FCOLOR_OTHER 0, 0, 1 - -struct IMaterial; -struct IStatObj; -struct IRenderMesh; -struct IRenderNode; -struct CRenderChunk; -class CCamera; - -#include - -struct CLocalMemoryUsage - : public ILocalMemoryUsage -{ -private: - - struct STextureInfo; - struct SMaterialInfo; - struct SStatObjInfo; - - typedef std__hash_map TTextureMap; // Type: hash map of textures - typedef std__hash_map TMaterialMap; // Type: hash map of materials - typedef std__hash_map TStatObjMap; // Type: hash map of stat objects - - //******************* - - struct SResource - { - CLocalMemoryUsage* m_pLocalMemoryUsage; // Inner pointer to the singleton (we can use gEnv->pLocalMemoryUsage with type cast instead this) - - float m_arrMipFactor[LOCALMEMORY_SECTOR_PER_PASS * LOCALMEMORY_SECTOR_PER_PASS]; // Mipmap factor based on minimum distance of the resource from the sector (bounding box distance) - bool m_arrRowDirty[LOCALMEMORY_SECTOR_PER_PASS]; // Dirty flag for m_arrMipFactor rows - bool m_used; - - static int m_arrMemoryUsage[LOCALMEMORY_SECTOR_PER_PASS]; // Memory usage of the resource in sectors (last row) - static int m_arrPieces[LOCALMEMORY_SECTOR_PER_PASS]; // Pieces nr of the resource in sectors (last row) - - virtual void StartChecking(); // Called every frame first - void CheckOnAllSectorsP1(const AABB& bounding, float maxViewDist, float viewDistMultiplierForLOD, float mipFactor); // Calculates the minimum of sector bounding vs renderobject bounding distances - - SResource(); - virtual void Init(CLocalMemoryUsage* pLocalMemoryUsage); - //If we will needed a destructor, it must be virtual! - }; - - //******************* - - struct STextureInfo - : public SResource - { - ITexture* m_pTexture; // Texture pointer - //int m_size; // For later use - Used memory - //int m_xSize; // For later use - Texture x size - //int m_ySize; // For later use - Texture y size - //int m_numMips; // For later use - Number of mip maps - - void CheckOnAllSectorsP2(); // Calculate memory usage using distances - - STextureInfo(); - ~STextureInfo(); - }; - - //******************* - - struct STextureInfoAndTilingFactor - { - STextureInfo* m_pTextureInfo; - float m_tilingFactor; - }; - - typedef std::vector TTextureVector; // Type: vector of textures - - struct SMaterialInfo - : public SResource - { - //_smart_ptr m_pMaterial; // For later use - TTextureVector m_textures; // Used textures - - SMaterialInfo(); - - void AddTextureInfo(STextureInfoAndTilingFactor texture);// Add a new texture (unique) - void CheckOnAllSectorsP2(); // Forward distance informations to textures - }; - - //******************* - - struct SStatObjInfo - : public SResource - { - int m_streamableContentMemoryUsage; // Total streamable memory usage - //IStatObj *m_pStatObj; //TODO kiszedni - string m_filePath; // The original file name and path of the StatObj - bool m_bSubObject; // Is the original StatObj a subobject? - /* - int m_lodNr; // For later use - int m_vertices; - int m_meshSize; - int m_physProxySize; - int m_physPrimitives; - int m_indices; - int m_indicesPerLod[MAX_LODS]; - */ - - SStatObjInfo(); - void CheckOnAllSectorsP2(); // Calculate memory usage using distances - }; - - //******************* - - struct SSector - { - SSector(); - - void StartChecking(); // Called every frame first - - int m_memoryUsage_Textures; // Sum of texture memory usage - - int m_memoryUsage_Geometry; // Sum of geometry memory usage - }; - - //******************* - PREFAST_SUPPRESS_WARNING(6262); - TTextureMap m_globalTextures; // Hash map of resources: textures - PREFAST_SUPPRESS_WARNING(6262); - TMaterialMap m_globalMaterials; // Hash map of resources: materials - PREFAST_SUPPRESS_WARNING(6262); - TStatObjMap m_globalStatObjs; // Hash map of resources: stat objects - - ICVar* m_pStreamCgfPredicitionDistance; // Config: additional object distance for streaming - ICVar* m_pDebugDraw; // Config: debug draw mode - - int sys_LocalMemoryTextureLimit; // Config: texture limit for streaming - int sys_LocalMemoryGeometryLimit; // Config: stat object geometry limit for streaming - int sys_LocalMemoryTextureStreamingSpeedLimit; // Config: texture streaming speed limit (approx) - int sys_LocalMemoryGeometryStreamingSpeedLimit; // Config: stat object geometry streaming speed limit (approx) - - float sys_LocalMemoryWarningRatio; // Config: Warning ratio for streaming - float sys_LocalMemoryOuterViewDistance; // Config: View distance for debug draw - float sys_LocalMemoryInnerViewDistance; // Config: View distance for detailed debug draw - - float sys_LocalMemoryObjectWidth; // Config: Width of the debug object - float sys_LocalMemoryObjectHeight; // Config: Height of the debug object - int sys_LocalMemoryObjectAlpha; // Config: Color alpha of the debug object - - float sys_LocalMemoryStreamingSpeedObjectLength; // Config: Length of the streaming speed debug object - float sys_LocalMemoryStreamingSpeedObjectWidth; // Config: Width of the streaming speed debug object - - float sys_LocalMemoryDiagramWidth; // Config: Width of the diagram - - float sys_LocalMemoryDiagramRadius; // Config: Radius of the diagram - float sys_LocalMemoryDiagramDistance; // Config: Distance of the diagram from the main debug object - float sys_LocalMemoryDiagramStreamingSpeedRadius; // Config: Radius of the streaming speed diagram - float sys_LocalMemoryDiagramStreamingSpeedDistance; // Config: Distance of the streaming speed diagram from the streaming speed debug line - int sys_LocalMemoryDiagramAlpha; // Config: Color alpha of the diagram - - int sys_LocalMemoryDrawText; // Config: If != 0, it will draw the numeric values - int sys_LocalMemoryLogText; // Config: If != 0, it will log the numeric values - - int sys_LocalMemoryOptimalMSecPerSec; // Config: Optimal calculation time (MSec) per secundum - int sys_LocalMemoryMaxMSecBetweenCalls; // Config: Maximal time difference (MSec) between calls - - RectI m_actProcessedSectors; // Processed sectors (now it is the whole world) - RectI m_actDrawedSectors; // Processed sectors (now it is the whole world) - - Vec2i m_sectorNr; // Sector x and y number - - float m_AverageUpdateTime; // Avarage Update() time (MSec) - CTimeValue m_LastCallTime; // Last call time of Update() - - SSector m_arrSectors[LOCALMEMORY_SECTOR_NR_X * LOCALMEMORY_SECTOR_NR_Y]; // Sectors - -public: - - CLocalMemoryUsage(); - ~CLocalMemoryUsage(); - - virtual void OnRender(IRenderer* pRenderer, const CCamera* camera); - virtual void OnUpdate(); - virtual void DeleteGlobalData(); // Deletes the m_globalXXX hash maps - -private: - void DeleteUnusedResources(); // Delete the non-used resources (especially StatObjs) - void StartChecking(const RectI& actProcessedSectors); // Called every frame first - void CollectGeometryP1(); // Calculates the minimum of sector bounding vs renderobject bounding distances - - // Get / create StatObjInfo then run Pass1 - SStatObjInfo* CheckStatObjP1(IStatObj* pStatObj, IRenderNode* pRenderNode, AABB bounding, float maxViewDist, float scale); - //void CollectStatObjInfo_Recursive( SStatObjInfo* statObjInfo, IStatObj *pStatObj ); - //void CollectGeometryInfo( SStatObjInfo* statObjInfo, IStatObj *pStatObj ); - - // Get / create MaterialInfo then run Pass1 - void CheckMaterialP1(_smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale, float mipFactor); - void CheckChunkMaterialP1(_smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale, CRenderChunk* pRenderChunk); - void CheckMeshMaterialP1(IRenderMesh* pRenderMesh, _smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale); - void CheckStatObjMaterialP1(IStatObj* pStatObj, _smart_ptr pMaterial, AABB bounding, float maxViewDist, float scale); - // Collects textures used by the material - void CollectMaterialInfo_Recursive(SMaterialInfo* materialInfo, _smart_ptr pMaterial); - - // Get / create TextureInfo - STextureInfo* GetTextureInfo(ITexture* pTexture); -}; - -#undef MAX_LODS -#endif // CRYINCLUDE_CRYSYSTEM_STATISTICS_LOCALMEMORYUSAGE_H diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index 827a393103..af9b674f6a 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -119,8 +119,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include AZ_RESTRICTED_FILE(System_cpp) #endif - -#include #include #include #include @@ -131,7 +129,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include "VisRegTest.h" #include -#include #include @@ -154,7 +151,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include "Serialization/ArchiveHost.h" #include "SystemEventDispatcher.h" #include "ServerThrottle.h" -#include "ILocalMemoryUsage.h" #include "ResourceManager.h" #include "HMDBus.h" #include "OverloadSceneManager/OverloadSceneManager.h" @@ -682,15 +678,6 @@ void CSystem::ShutDown() // Shutdown any running VR devices. EBUS_EVENT(AZ::VR::HMDInitRequestBus, Shutdown); - - ////////////////////////////////////////////////////////////////////////// - // Clear 3D Engine resources. - if (m_env.p3DEngine) - { - m_env.p3DEngine->UnloadLevel(); - } - ////////////////////////////////////////////////////////////////////////// - // Shutdown resource manager. m_pResourceManager->Shutdown(); @@ -706,7 +693,6 @@ void CSystem::ShutDown() SAFE_DELETE(m_env.pServiceNetwork); SAFE_RELEASE(m_env.pLyShine); SAFE_RELEASE(m_env.pCryFont); - SAFE_RELEASE(m_env.p3DEngine); // depends on EntitySystem if (m_env.pConsole) { ((CXConsole*)m_env.pConsole)->FreeRenderResources(); @@ -1231,8 +1217,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) return false; } - RenderBegin(); - #ifndef EXCLUDE_UPDATE_ON_CONSOLE // do the dedicated sleep earlier than the frame profiler to avoid having it counted if (gEnv->IsDedicated()) @@ -1295,11 +1279,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) GetIRemoteConsole()->Update(); #endif - if (gEnv->pLocalMemoryUsage != NULL) - { - gEnv->pLocalMemoryUsage->OnUpdate(); - } - if (!gEnv->IsEditor() && gEnv->pRenderer) { // If the dimensions of the render target change, @@ -1490,11 +1469,6 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) //update time subsystem m_Time.UpdateOnFrameStart(); - if (m_env.p3DEngine) - { - m_env.p3DEngine->OnFrameStart(); - } - ////////////////////////////////////////////////////////////////////// // update rate limiter for dedicated server if (m_pServerThrottle.get()) @@ -1651,7 +1625,7 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) } ////////////////////////////////////////////////////////////////////// -bool CSystem::UpdatePostTickBus(int updateFlags, int nPauseMode) +bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/) { CTimeValue updateStart = gEnv->pTimer->GetAsyncTime(); @@ -1663,44 +1637,6 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int nPauseMode) UpdateMovieSystem(updateFlags, fMovieFrameTime, false); } - ////////////////////////////////////////////////////////////////////// - //update process (3D engine) - if (!(updateFlags & ESYSUPDATE_EDITOR) && !m_bNoUpdate && m_env.p3DEngine) - { - FRAME_PROFILER("SysUpdate:Update3DEngine", this, PROFILE_SYSTEM); - - if (ITimeOfDay* pTOD = m_env.p3DEngine->GetTimeOfDay()) - { - pTOD->Tick(); - } - - if (m_env.p3DEngine) - { - m_env.p3DEngine->Tick(); // clear per frame temp data - } - if (m_pProcess && (m_pProcess->GetFlags() & PROC_3DENGINE)) - { - if ((nPauseMode != 1)) - { - if (!IsEquivalent(m_ViewCamera.GetPosition(), Vec3(0, 0, 0), VEC_EPSILON)) - { - if (m_env.p3DEngine) - { - // m_env.p3DEngine->SetCamera(m_ViewCamera); - m_pProcess->Update(); - } - } - } - } - else - { - if (m_pProcess) - { - m_pProcess->Update(); - } - } - } - ////////////////////////////////////////////////////////////////////// //update sound system part 2 if (!g_cvars.sys_deferAudioUpdateOptim && !m_bNoUpdate) @@ -1748,41 +1684,8 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int nPauseMode) gEnv->pCryPak->DisableRuntimeFileAccess(true); } - // If it's in editing mode (in editor) the render is done in RenderViewport so we skip rendering here. - if (!gEnv->IsEditing() && gEnv->pRenderer && gEnv->p3DEngine) - { - if (GetIViewSystem()) - { - GetIViewSystem()->Update(min(gEnv->pTimer->GetFrameTime(), 0.1f)); - } - - // Begin occlusion job after setting the correct camera. - gEnv->p3DEngine->PrepareOcclusion(GetViewCamera()); - - CrySystemNotificationBus::Broadcast(&CrySystemNotifications::OnPreRender); - - // Also broadcast for anyone else that needs to draw global debug to do so now - AzFramework::DebugDisplayEventBus::Broadcast(&AzFramework::DebugDisplayEvents::DrawGlobalDebugInfo); - - Render(); - - gEnv->p3DEngine->EndOcclusion(); - - CrySystemNotificationBus::Broadcast(&CrySystemNotifications::OnPostRender); - - RenderEnd(); - - gEnv->p3DEngine->SyncProcessStreamingUpdate(); - - if (NeedDoWorkDuringOcclusionChecks()) - { - DoWorkDuringOcclusionChecks(); - } - - // Sync the work that must be done in the main thread by the end of frame. - gEnv->pRenderer->GetGenerateShadowRendItemJobExecutor()->WaitForCompletion(); - gEnv->pRenderer->GetGenerateRendItemJobExecutor()->WaitForCompletion(); - } + // Also broadcast for anyone else that needs to draw global debug to do so now + AzFramework::DebugDisplayEventBus::Broadcast(&AzFramework::DebugDisplayEvents::DrawGlobalDebugInfo); return !IsQuitting(); } diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index e4fcc82552..f5235f2ea8 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -408,13 +408,6 @@ public: virtual void DoWorkDuringOcclusionChecks(); virtual bool NeedDoWorkDuringOcclusionChecks() { return m_bNeedDoWorkDuringOcclusionChecks; } - //! Begin rendering frame. - void RenderBegin(); - //! Render subsystems. - void Render(); - //! End rendering frame and swap back buffer. - void RenderEnd(bool bRenderStats = true, bool bMainWindow = true); - //Called when the renderer finishes rendering the scene void OnScene3DEnd() override; @@ -429,11 +422,6 @@ public: //! Update screen and call some important tick functions during loading. void SynchronousLoadingTick(const char* pFunc, int line); - //! Renders the statistics; this is called from RenderEnd, but if the - //! Host application (Editor) doesn't employ the Render cycle in ISystem, - //! it may call this method to render the essential statistics - void RenderStatistics() override; - uint32 GetUsedMemory(); virtual void DumpMemoryUsageStatistics(bool bUseKB); @@ -469,7 +457,6 @@ public: AZ::IO::IArchive* GetIPak() { return m_env.pCryPak; }; IConsole* GetIConsole() { return m_env.pConsole; }; IRemoteConsole* GetIRemoteConsole(); - I3DEngine* GetI3DEngine(){ return m_env.p3DEngine; } IMovieSystem* GetIMovieSystem() { return m_env.pMovieSystem; }; IMemoryManager* GetIMemoryManager(){ return m_pMemoryManager; } IThreadManager* GetIThreadManager() override {return m_env.pThreadManager; } @@ -696,9 +683,6 @@ private: void CreateRendererVars(const SSystemInitParams& startupParams); void CreateSystemVars(); void CreateAudioVars(); - void RenderStats(); - void RenderOverscanBorders(); - void RenderMemStats(); AZStd::unique_ptr LoadDLL(const char* dllName); diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 826810ef8a..22445ec4a5 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -86,7 +86,6 @@ #endif //WIN32 -#include #include #include #include @@ -107,7 +106,6 @@ #include "PhysRenderer.h" #include "LocalizedStringManager.h" #include "SystemEventDispatcher.h" -#include "Statistics/LocalMemoryUsage.h" #include "ThreadConfigManager.h" #include "Validator.h" #include "ServerThrottle.h" @@ -768,11 +766,6 @@ static void LoadDetectedSpec(ICVar* pVar) GetISystem()->SetConfigSpec(static_cast(spec), platform, false); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetMaterialManager()->RefreshMaterialRuntime(); - } - no_recursive = false; } @@ -2788,12 +2781,6 @@ AZ_POP_DISABLE_WARNING m_env.pRenderer->TryFlush(); } -#if !defined(RELEASE) - m_env.pLocalMemoryUsage = new CLocalMemoryUsage(); -#else - m_env.pLocalMemoryUsage = nullptr; -#endif - if (g_cvars.sys_float_exceptions > 0) { if (g_cvars.sys_float_exceptions == 3 && gEnv->IsEditor()) // Turn off float exceptions in editor if sys_float_exceptions = 3 diff --git a/Code/CryEngine/CrySystem/SystemRender.cpp b/Code/CryEngine/CrySystem/SystemRender.cpp index a544cef4a5..68045a86ea 100644 --- a/Code/CryEngine/CrySystem/SystemRender.cpp +++ b/Code/CryEngine/CrySystem/SystemRender.cpp @@ -31,7 +31,6 @@ #include #include "Log.h" #include "XConsole.h" -#include #include #include "PhysRenderer.h" #include @@ -222,92 +221,6 @@ void CSystem::CreateRendererVars(const SSystemInitParams& startupParams) "Usage: r_OverscanBordersDrawDebugView [0=off/1=show]"); } -////////////////////////////////////////////////////////////////////////// -void CSystem::RenderBegin() -{ - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - - if (m_bIgnoreUpdates) - { - return; - } - - bool rndAvail = m_env.pRenderer != 0; - - ////////////////////////////////////////////////////////////////////// - //start the rendering pipeline - if (rndAvail) - { - m_env.pRenderer->BeginFrame(); - } - - gEnv->nMainFrameID = (rndAvail) ? m_env.pRenderer->GetFrameID(false) : 0; -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::RenderEnd([[maybe_unused]] bool bRenderStats, bool bMainWindow) -{ - { - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - - if (m_bIgnoreUpdates) - { - return; - } - - if (!m_env.pRenderer) - { - return; - } - - if (bMainWindow) // we don't do this in UI Editor window for example - { -#if !defined (_RELEASE) - // Flush render data and swap buffers. - m_env.pRenderer->RenderDebug(bRenderStats); -#endif - -#if defined(USE_PERFHUD) - if (m_pPerfHUD) - { - m_pPerfHUD->Draw(); - } - if (m_pMiniGUI) - { - m_pMiniGUI->Draw(); - } -#endif - - if (!gEnv->pSystem->GetILevelSystem() || !gEnv->pSystem->GetILevelSystem()->IsLevelLoaded()) - { - IConsole* console = GetIConsole(); - - //Same goes for the console. When no level is loaded, it's okay to render it outside of the renderer - //so that users can load maps or change settings. - if (console != nullptr) - { - console->Draw(); - } - } - } - - m_env.pRenderer->ForceGC(); // XXX Rename this - m_env.pRenderer->EndFrame(); - - - if (IConsole* pConsole = GetIConsole()) - { - // if we have pending cvar calculation, execute it here - // since we know cvars will be correct here after ->EndFrame(). - if (!pConsole->IsHashCalculated()) - { - pConsole->CalcCheatVarHash(); - } - } - } -} - void CSystem::OnScene3DEnd() { //Render Console @@ -391,231 +304,3 @@ void CSystem::DisplayErrorMessage(const char* acMessage, #endif m_ErrorMessages.push_back(message); } - -//! Renders the statistics; this is called from RenderEnd, but if the -//! Host application (Editor) doesn't employ the Render cycle in ISystem, -//! it may call this method to render the essential statistics -////////////////////////////////////////////////////////////////////////// -void CSystem::RenderStatistics() -{ - RenderStats(); -} - -////////////////////////////////////////////////////////////////////// -void CSystem::Render() -{ - if (m_bIgnoreUpdates) - { - return; - } - - //check what is the current process - if (!m_pProcess) - { - return; //should never happen - } - //check if the game is in pause or - //in menu mode - //bool bPause=false; - //if (m_pProcess->GetFlags() & PROC_MENU) - // bPause=true; - - FUNCTION_PROFILER_FAST(GetISystem(), PROFILE_SYSTEM, g_bProfilerEnabled); - - ////////////////////////////////////////////////////////////////////// - //draw - m_env.p3DEngine->PreWorldStreamUpdate(m_ViewCamera); - - if (m_pProcess) - { - if (m_pProcess->GetFlags() & PROC_3DENGINE) - { - if (!gEnv->IsEditing()) // Editor calls it's own rendering update - { - if (m_env.p3DEngine && !m_env.IsFMVPlaying()) - { - if (!IsEquivalent(m_ViewCamera.GetPosition(), Vec3(0, 0, 0), VEC_EPSILON) || // never pass undefined camera to p3DEngine->RenderWorld() - gEnv->IsDedicated() || (gEnv->pRenderer && gEnv->pRenderer->IsPost3DRendererEnabled())) - { - GetIRenderer()->SetViewport(0, 0, GetIRenderer()->GetWidth(), GetIRenderer()->GetHeight()); - m_env.p3DEngine->RenderWorld(SHDF_ALLOW_WATER | SHDF_ALLOWPOSTPROCESS | SHDF_ALLOWHDR | SHDF_ZPASS | SHDF_ALLOW_AO, SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_ViewCamera), __FUNCTION__); - } - else - { - if (gEnv->pRenderer) - { - // force rendering of black screen to be sure we don't only render the clear color (which is the fog color by default) - gEnv->pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - gEnv->pRenderer->Draw2dImage(0, 0, 800, 600, -1, 0.0f, 0.0f, 1.0f, 1.0f, 0.f, - 0.0f, 0.0f, 0.0f, 1.0f, 0.f); - } - } - } -#if !defined(_RELEASE) - if (m_pVisRegTest) - { - m_pVisRegTest->AfterRender(); - } -#endif - - if (m_env.pMovieSystem) - { - m_env.pMovieSystem->Render(); - } - } - } - else - { - GetIRenderer()->SetViewport(0, 0, GetIRenderer()->GetWidth(), GetIRenderer()->GetHeight()); - m_pProcess->RenderWorld(SHDF_ALLOW_WATER | SHDF_ALLOWPOSTPROCESS | SHDF_ALLOWHDR | SHDF_ZPASS | SHDF_ALLOW_AO, SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_ViewCamera), __FUNCTION__); - } - } - - m_env.p3DEngine->WorldStreamUpdate(); - - gEnv->pRenderer->SwitchToNativeResolutionBackbuffer(); -} - - -////////////////////////////////////////////////////////////////////////// -void CSystem::RenderStats() -{ -#if defined(ENABLE_PROFILING_CODE) -#ifndef _RELEASE - // if we rendered an error message on screen during the last frame, then sleep now - // to force hard stall for 3sec - if (m_bHasRenderedErrorMessage && !gEnv->IsEditor() && !IsLoading()) - { - // DO NOT REMOVE OR COMMENT THIS OUT! - // If you hit this, then you most likely have invalid (synchronous) file accesses - // which must be fixed in order to not stall the entire game. - Sleep(3000); - m_bHasRenderedErrorMessage = false; - } -#endif - - // render info messages on screen - float fTextPosX = 5.0f; - float fTextPosY = -10; - float fTextStepY = 13; - - float fFrameTime = gEnv->pTimer->GetRealFrameTime(); - TErrorMessages::iterator itnext; - for (TErrorMessages::iterator it = m_ErrorMessages.begin(); it != m_ErrorMessages.end(); it = itnext) - { - itnext = it; - ++itnext; - SErrorMessage& message = *it; - - SDrawTextInfo ti; - ti.flags = eDrawText_FixedSize | eDrawText_2D | eDrawText_Monospace; - memcpy(ti.color, message.m_Color, 4 * sizeof(float)); - ti.xscale = ti.yscale = 1.4f; - m_env.pRenderer->DrawTextQueued(Vec3(fTextPosX, fTextPosY += fTextStepY, 1.0f), ti, message.m_Message.c_str()); - - if (!IsLoading()) - { - message.m_fTimeToShow -= fFrameTime; - } - - if (message.m_HardFailure) - { - m_bHasRenderedErrorMessage = true; - } - - if (message.m_fTimeToShow < 0.0f) - { - m_ErrorMessages.erase(it); - } - } -#endif - - if (!m_env.pConsole) - { - return; - } - -#ifndef _RELEASE - if (m_rOverscanBordersDrawDebugView) - { - RenderOverscanBorders(); - } -#endif - - int iDisplayInfo = m_rDisplayInfo->GetIVal(); - if (iDisplayInfo == 0) - { - return; - } - - // Draw engine stats - if (m_env.p3DEngine) - { - // Draw 3dengine stats and get last text cursor position - float nTextPosX = 101 - 20, nTextPosY = -2, nTextStepY = 3; - m_env.p3DEngine->DisplayInfo(nTextPosX, nTextPosY, nTextStepY, iDisplayInfo != 1); - - // Dump Open 3D Engine CPU and GPU memory statistics to screen - m_env.p3DEngine->DisplayMemoryStatistics(); - - #if defined(ENABLE_LW_PROFILERS) - if (m_rDisplayInfo->GetIVal() == 2) - { - m_env.pRenderer->TextToScreen(nTextPosX, nTextPosY += nTextStepY, "SysMem %.1f mb", - float(DumpMMStats(false)) / 1024.f); - } - #endif - - #if 0 - for (int i = 0; i < NUM_POOLS; ++i) - { - int used = (g_pPakHeap->m_iBigPoolUsed[i] ? (int)g_pPakHeap->m_iBigPoolSize[i] : 0); - int size = (int)g_pPakHeap->m_iBigPoolSize[i]; - float fC1[4] = {1, 1, 0, 1}; - m_env.pRenderer->Draw2dLabel(10, 100.0f + i * 16, 2.1f, fC1, false, "BigPool %d: %d bytes of %d bytes used", i, used, size); - } - #endif - } -} - -void CSystem::RenderOverscanBorders() -{ -#ifndef _RELEASE - - if (m_env.pRenderer && m_rOverscanBordersDrawDebugView) - { - int iOverscanBordersDrawDebugView = m_rOverscanBordersDrawDebugView->GetIVal(); - if (iOverscanBordersDrawDebugView) - { - const int texId = -1; - const float uv = 0.0f; - const float rot = 0.0f; - const int whiteTextureId = m_env.pRenderer->GetWhiteTextureId(); - - const float r = 1.0f; - const float g = 1.0f; - const float b = 1.0f; - const float a = 0.2f; - - Vec2 overscanBorders = Vec2(0.0f, 0.0f); - m_env.pRenderer->EF_Query(EFQ_OverscanBorders, overscanBorders); - - const float overscanBorderWidth = overscanBorders.x * VIRTUAL_SCREEN_WIDTH; - const float overscanBorderHeight = overscanBorders.y * VIRTUAL_SCREEN_HEIGHT; - - const float xPos = overscanBorderWidth; - const float yPos = overscanBorderHeight; - const float width = VIRTUAL_SCREEN_WIDTH - (2.0f * overscanBorderWidth); - const float height = VIRTUAL_SCREEN_HEIGHT - (2.0f * overscanBorderHeight); - - m_env.pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - m_env.pRenderer->Draw2dImage(xPos, yPos, - width, height, - whiteTextureId, - uv, uv, uv, uv, - rot, - r, g, b, a); - } - } -#endif -} diff --git a/Code/CryEngine/CrySystem/SystemWin32.cpp b/Code/CryEngine/CrySystem/SystemWin32.cpp index 974e578f38..ce352966ac 100644 --- a/Code/CryEngine/CrySystem/SystemWin32.cpp +++ b/Code/CryEngine/CrySystem/SystemWin32.cpp @@ -15,7 +15,6 @@ #include "System.h" #include -#include #include #include #include @@ -302,23 +301,6 @@ void CSystem::CollectMemStats (ICrySizer* pSizer, MemStatsPurposeEnum nPurpose, } } - - if (m_env.p3DEngine) - { - SIZER_COMPONENT_NAME(pSizer, "Cry3DEngine"); - { - m_env.p3DEngine->GetMemoryUsage (pSizer); - { - SIZER_COMPONENT_NAME (pSizer, "$Allocations waste"); - const SmallModuleInfo* info = FindModuleInfo(stats, "Cry3DEngine.dll"); - if (info) - { - pSizer->AddObject(info, info->memInfo.allocated - info->memInfo.requested); - } - } - } - } - if (m_env.pRenderer) { SIZER_COMPONENT_NAME(pSizer, "CryRenderer"); diff --git a/Code/CryEngine/CrySystem/ViewSystem/View.cpp b/Code/CryEngine/CrySystem/ViewSystem/View.cpp index 384d1c76f5..f8b84bea19 100644 --- a/Code/CryEngine/CrySystem/ViewSystem/View.cpp +++ b/Code/CryEngine/CrySystem/ViewSystem/View.cpp @@ -98,7 +98,7 @@ void CView::Update(float frameTime, bool isActive) //see if the view have to use a custom near clipping plane const float nearPlane = (m_viewParams.nearplane >= CAMERA_MIN_NEAR) ? (m_viewParams.nearplane) : fNearZ; - const float farPlane = (m_viewParams.farplane > 0.f) ? m_viewParams.farplane : gEnv->p3DEngine->GetMaxViewDistance(); + const float farPlane = (m_viewParams.farplane > 0.f) ? m_viewParams.farplane : DEFAULT_FAR; float fov = (m_viewParams.fov < 0.001f) ? DEFAULT_FOV : m_viewParams.fov; // [VR] specific diff --git a/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp b/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp index 65581662c3..13f7f5b82d 100644 --- a/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp +++ b/Code/CryEngine/CrySystem/ViewSystem/ViewSystem.cpp @@ -533,11 +533,6 @@ void CViewSystem::BeginCutScene(IAnimSequence* pSeq, [[maybe_unused]] unsigned l { m_cutsceneCount++; - if (m_cutsceneCount == 1) - { - gEnv->p3DEngine->ResetPostEffects(); - } - VS_CALL_LISTENERS(OnBeginCutScene(pSeq, bResetFX)); } @@ -546,11 +541,6 @@ void CViewSystem::EndCutScene(IAnimSequence* pSeq, [[maybe_unused]] unsigned lon { m_cutsceneCount -= (m_cutsceneCount > 0); - if (m_cutsceneCount == 0) - { - gEnv->p3DEngine->ResetPostEffects(); - } - ClearCutsceneViews(); VS_CALL_LISTENERS(OnEndCutScene(pSeq)); diff --git a/Code/CryEngine/CrySystem/VisRegTest.cpp b/Code/CryEngine/CrySystem/VisRegTest.cpp index 81ef205b47..206d8f349a 100644 --- a/Code/CryEngine/CrySystem/VisRegTest.cpp +++ b/Code/CryEngine/CrySystem/VisRegTest.cpp @@ -18,7 +18,6 @@ #include "VisRegTest.h" #include "ISystem.h" -#include "I3DEngine.h" #include "IRenderer.h" #include "IConsole.h" #include "ITimer.h" diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 23ad644041..bfc7b092fd 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -57,7 +57,6 @@ set(FILES UnixConsole.h SystemInit.h Serialization/MemoryReader.h - Statistics/LocalMemoryUsage.h MemoryFragmentationProfiler.h XML/ReadWriteXMLSink.h Serialization/ArchiveHost.h @@ -151,7 +150,6 @@ set(FILES MiniGUI/MiniInfoBox.h MiniGUI/MiniMenu.h MiniGUI/MiniTable.h - Statistics/LocalMemoryUsage.cpp ZLibCompressor.cpp ZLibCompressor.h SoftCode/SoftCodeMgr.cpp diff --git a/Code/Sandbox/Editor/2DViewport.cpp b/Code/Sandbox/Editor/2DViewport.cpp index d86ea03bdf..0487c9381f 100644 --- a/Code/Sandbox/Editor/2DViewport.cpp +++ b/Code/Sandbox/Editor/2DViewport.cpp @@ -650,114 +650,6 @@ void Q2DViewport::OnDestroy() ////////////////////////////////////////////////////////////////////////// void Q2DViewport::Render() { - if (GetIEditor()->IsInGameMode()) - { - return; - } - - if (!m_renderer) - { - return; - } - - if (!isVisible()) - { - return; - } - - if (!GetIEditor()->GetDocument()->IsDocumentReady()) - { - return; - } - - if (m_renderer->IsStereoEnabled()) - { - return; - } - - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - QRect rc = rect(); - if (rc.isEmpty()) - { - return; - } - - CalculateViewTM(); - - // Render - WIN_HWND priorContext = m_renderer->GetCurrentContextHWND(); - - m_renderer->SetCurrentContext(renderOverlayHWND()); - m_renderer->BeginFrame(); - m_renderer->ChangeViewport(0, 0, rc.right(), rc.bottom(), true); - - CScopedWireFrameMode scopedWireFrame(m_renderer, R_SOLID_MODE); - auto colorf = Rgb2ColorF(m_colorBackground); - m_renderer->ClearTargetsLater(FRT_CLEAR, colorf); - - ////////////////////////////////////////////////////////////////////////// - // 2D Mode. - ////////////////////////////////////////////////////////////////////////// - if (rc.right() != 0 && rc.bottom() != 0) - { - TransformationMatrices backupSceneMatrices; - - m_renderer->Set2DMode(rc.right(), rc.bottom(), backupSceneMatrices); - - ////////////////////////////////////////////////////////////////////////// - // Draw viewport elements here. - ////////////////////////////////////////////////////////////////////////// - // Calc world bounding box for objects rendering. - m_displayBounds = GetWorldBounds(QPoint(0, 0), QPoint(rc.width(), rc.height())); - - // Draw all objects. - DisplayContext& dc = m_displayContext; - dc.settings = GetIEditor()->GetDisplaySettings(); - dc.view = this; - dc.renderer = m_renderer; - dc.engine = GetIEditor()->Get3DEngine(); - dc.flags = DISPLAY_2D; - dc.box = m_displayBounds; - dc.camera = &GetIEditor()->GetSystem()->GetViewCamera(); - - if (!dc.settings->IsDisplayLabels() || !dc.settings->IsDisplayHelpers()) - { - dc.flags |= DISPLAY_HIDENAMES; - } - if (dc.settings->IsDisplayLinks() && dc.settings->IsDisplayHelpers()) - { - dc.flags |= DISPLAY_LINKS; - } - if (m_bDegradateQuality) - { - dc.flags |= DISPLAY_DEGRADATED; - } - - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(GetIEditor()->GetSystem()->GetViewCamera()); - - m_renderer->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID()); - m_renderer->BeginSpawningShadowGeneratingRendItemJobs(passInfo.ThreadID()); - m_renderer->EF_StartEf(passInfo); - - dc.SetState(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeBack | e_DepthWriteOff | e_DepthTestOn); - Draw(dc); - - m_renderer->EF_EndEf3D(SHDF_STREAM_SYNC, -1, -1, passInfo); - - m_renderer->EF_RenderTextMessages(); - - // Return back from 2D mode. - m_renderer->Unset2DMode(backupSceneMatrices); - - m_renderer->RenderDebug(false); - - ProcessRenderLisneters(m_displayContext); - - m_renderer->EndFrame(); - } - - GetIEditor()->GetRenderer()->SetCurrentContext(priorContext); } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp index 0c99e63c47..c8bd157b65 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.cpp @@ -50,8 +50,6 @@ #include "Include/IObjectManager.h" #include "CryEditDoc.h" #include "QtViewPaneManager.h" -#include "AzAssetBrowser/Preview/LegacyPreviewerFactory.h" - namespace AzAssetBrowserRequestHandlerPrivate { @@ -230,18 +228,15 @@ namespace AzAssetBrowserRequestHandlerPrivate } AzAssetBrowserRequestHandler::AzAssetBrowserRequestHandler() - : m_previewerFactory(aznew LegacyPreviewerFactory) { using namespace AzToolsFramework::AssetBrowser; AssetBrowserInteractionNotificationBus::Handler::BusConnect(); AzQtComponents::DragAndDropEventsBus::Handler::BusConnect(AzQtComponents::DragAndDropContexts::EditorViewport); - AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler::BusConnect(); } AzAssetBrowserRequestHandler::~AzAssetBrowserRequestHandler() { - AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect(); AzQtComponents::DragAndDropEventsBus::Handler::BusDisconnect(); } @@ -527,15 +522,6 @@ void AzAssetBrowserRequestHandler::Drop(QDropEvent* event, AzQtComponents::DragA } } -const AzToolsFramework::AssetBrowser::PreviewerFactory* AzAssetBrowserRequestHandler::GetPreviewerFactory(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const -{ - if (m_previewerFactory->IsEntrySupported(entry)) - { - return m_previewerFactory.get(); - } - return nullptr; -} - void AzAssetBrowserRequestHandler::AddSourceFileOpeners(const char* fullSourceFileName, const AZ::Uuid& sourceUUID, AzToolsFramework::AssetBrowser::SourceFileOpenerList& openers) { using namespace AzToolsFramework; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.h b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.h index 5b7e10f2a1..707b9041ae 100644 --- a/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.h +++ b/Code/Sandbox/Editor/AzAssetBrowser/AzAssetBrowserRequestHandler.h @@ -37,12 +37,9 @@ namespace AzToolsFramework } } -class LegacyPreviewerFactory; - class AzAssetBrowserRequestHandler : protected AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler , protected AzQtComponents::DragAndDropEventsBus::Handler - , protected AzToolsFramework::AssetBrowser::PreviewerRequestBus::Handler { public: AzAssetBrowserRequestHandler(); @@ -66,16 +63,8 @@ protected: void DragLeave(QDragLeaveEvent* event) override; void Drop(QDropEvent* event, AzQtComponents::DragAndDropContextBase& context) override; - ////////////////////////////////////////////////////////////////////////// - // PreviewerRequestBus::Handler - ////////////////////////////////////////////////////////////////////////// - const AzToolsFramework::AssetBrowser::PreviewerFactory* GetPreviewerFactory(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; - bool CanAcceptDragAndDropEvent( QDropEvent* event, AzQtComponents::DragAndDropContextBase& context, AZStd::optional*> outSources = AZStd::nullopt, AZStd::optional*> outProducts = AZStd::nullopt) const; - -private: - AZStd::unique_ptr m_previewerFactory; }; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.cpp b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.cpp deleted file mode 100644 index 19938db676..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.cpp +++ /dev/null @@ -1,409 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "EditorDefs.h" - -#include "LegacyPreviewer.h" - -// AzToolsFramework -#include -#include -#include - -// Editor -#include "Util/Image.h" -#include "Util/ImageUtil.h" - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - -static const int s_CharWidth = 6; -const QString LegacyPreviewer::Name{ QStringLiteral("LegacyPreviewer") }; - -LegacyPreviewer::LegacyPreviewer(QWidget* parent) - : Previewer(parent) - , m_ui(new Ui::LegacyPreviewerClass()) - , m_textureType(TextureType::RGB) -{ - m_ui->setupUi(this); - m_ui->m_comboBoxRGB->addItems(QStringList() << "RGB" << "RGBA" << "Alpha"); - m_ui->m_previewCtrl->SetAspectRatio(4.0f / 3.0f); - connect(m_ui->m_comboBoxRGB, static_cast(&QComboBox::activated), this, - [=](int index) - { - m_textureType = static_cast(index); - UpdateTextureType(); - }); - Clear(); -} - -LegacyPreviewer::~LegacyPreviewer() -{ -} - -void LegacyPreviewer::Clear() const -{ - m_ui->m_previewCtrl->ReleaseObject(); - m_ui->m_modelPreviewWidget->hide(); - m_ui->m_texturePreviewWidget->hide(); - m_ui->m_fileInfoCtrl->hide(); -} - -void LegacyPreviewer::Display(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) -{ - using namespace AzToolsFramework::AssetBrowser; - - if (!entry) - { - Clear(); - return; - } - - switch (entry->GetEntryType()) - { - case AssetBrowserEntry::AssetEntryType::Source: - { - const SourceAssetBrowserEntry* sourceEntry = azrtti_cast(entry); - DisplaySource(sourceEntry); - break; - } - case AssetBrowserEntry::AssetEntryType::Product: - DisplayProduct(static_cast(entry)); - break; - default: - Clear(); - } -} - -const QString& LegacyPreviewer::GetName() const -{ - return Name; -} - -void LegacyPreviewer::resizeEvent(QResizeEvent* /*event*/) -{ - m_ui->m_fileInfoCtrl->setText(WordWrap(m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); -} - -bool LegacyPreviewer::DisplayProduct(const AzToolsFramework::AssetBrowser::ProductAssetBrowserEntry* product) -{ - m_ui->m_fileInfoCtrl->show(); - - m_fileinfo = QString::fromUtf8(product->GetName().c_str()); - - m_fileinfo += GetFileSize(product->GetRelativePath().c_str()); - - EBusFindAssetTypeByName meshAssetTypeResult("Static Mesh"); - AZ::AssetTypeInfoBus::BroadcastResult(meshAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - - QString filename(product->GetRelativePath().c_str()); - - // Find item. - if (product->GetAssetType() == meshAssetTypeResult.GetAssetType()) - { - m_ui->m_modelPreviewWidget->show(); - m_ui->m_texturePreviewWidget->hide(); - m_ui->m_previewCtrl->LoadFile(filename); - - int nVertexCount = m_ui->m_previewCtrl->GetVertexCount(); - int nFaceCount = m_ui->m_previewCtrl->GetFaceCount(); - int nMaxLod = m_ui->m_previewCtrl->GetMaxLod(); - int nMtls = m_ui->m_previewCtrl->GetMtlCount(); - if (nFaceCount > 0) - { - m_fileinfo += tr("\r\n%1 Faces\r\n%2 Verts\r\n%3 MaxLod\r\n%4 Materials").arg(nFaceCount).arg(nVertexCount).arg(nMaxLod).arg(nMtls); - } - m_ui->m_fileInfoCtrl->setText(WordWrap(m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); - updateGeometry(); - return true; - } - - EBusFindAssetTypeByName textureAssetTypeResult("Texture"); - AZ::AssetTypeInfoBus::BroadcastResult(textureAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - - if (product->GetAssetType() == textureAssetTypeResult.GetAssetType()) - { - // Get full product file path - const char* assetCachePath = AZ::IO::FileIOBase::GetInstance()->GetAlias("@assets@"); - AZStd::string productFullPath; - AzFramework::StringFunc::Path::Join(assetCachePath, product->GetRelativePath().c_str(), productFullPath); - if (AZ::IO::FileIOBase::GetInstance()->Exists(productFullPath.c_str())) - { - // Try to display it in modern dds image loader, if no one exists, use the legacy image loader - bool foundPixmap = DisplayTextureProductModern(productFullPath.c_str()); - return foundPixmap ? foundPixmap : DisplayTextureLegacy(productFullPath.c_str()); - } - else - { - // If we cannot find the product file, means it's not treated as an asset, display its source - return DisplayTextureLegacy(product->GetFullPath().c_str()); - } - } - - Clear(); - return false; -} - -void LegacyPreviewer::DisplaySource(const AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry* source) -{ - using namespace AzToolsFramework::AssetBrowser; - - EBusFindAssetTypeByName textureAssetType("Texture"); - AZ::AssetTypeInfoBus::BroadcastResult(textureAssetType, &AZ::AssetTypeInfo::GetAssetType); - - if (source->GetPrimaryAssetType() == textureAssetType.GetAssetType()) - { - m_ui->m_fileInfoCtrl->show(); - m_fileinfo = QString::fromUtf8(source->GetName().c_str()); - m_fileinfo += GetFileSize(source->GetFullPath().c_str()); - const char* fullSourcePath = source->GetFullPath().c_str(); - // If it's a source dds file, try to display it using modern way - if (AzFramework::StringFunc::Path::IsExtension(fullSourcePath, "dds", false)) - { - if (DisplayTextureProductModern(fullSourcePath)) - { - return; - } - } - DisplayTextureLegacy(source->GetFullPath().c_str()); - } - else - { - AZStd::vector products; - source->GetChildrenRecursively(products); - if (products.empty()) - { - Clear(); - } - else - { - for (auto* product : products) - { - if (DisplayProduct(product)) - { - break; - } - } - } - } -} - -QString LegacyPreviewer::GetFileSize(const char* path) -{ - QString fileSizeStr; - AZ::u64 fileSizeResult = 0; - if (AZ::IO::FileIOBase::GetInstance()->Size(path, fileSizeResult)) - { - static double kb = 1024.0f; - static double mb = kb * 1024.0; - static double gb = mb * 1024.0; - - static QString byteStr = "B"; - static QString kbStr = "KB"; - static QString mbStr = "MB"; - static QString gbStr = "GB"; - -#if AZ_TRAIT_OS_PLATFORM_APPLE - kb = 1000.0; - mb = kb * 1000.0; - gb = mb * 1000.0; - - kbStr = "kB"; - mbStr = "mB"; - gbStr = "gB"; -#endif // AZ_TRAIT_OS_PLATFORM_APPLE - - if (fileSizeResult < kb) - { - fileSizeStr += tr("\r\nFile Size: %1%2").arg(QString::number(fileSizeResult), byteStr); - } - else if (fileSizeResult < mb) - { - double size = fileSizeResult / kb; - fileSizeStr += tr("\r\nFile Size: %1%2").arg(QString::number(size, 'f', 2), kbStr); - } - else if (fileSizeResult < gb) - { - double size = fileSizeResult / mb; - fileSizeStr += tr("\r\nFile Size: %1%2").arg(QString::number(size, 'f', 2), mbStr); - } - else - { - double size = fileSizeResult / gb; - fileSizeStr += tr("\r\nFile Size: %1%2").arg(QString::number(size, 'f', 2), gbStr); - } - } - return fileSizeStr; -} - -bool LegacyPreviewer::DisplayTextureLegacy(const char* fullImagePath) -{ - m_ui->m_modelPreviewWidget->hide(); - m_ui->m_texturePreviewWidget->show(); - - bool foundPixmap = false; - if (!AZ::IO::FileIOBase::GetInstance()->IsDirectory(fullImagePath)) - { - QString strLoadFilename = QString(fullImagePath); - if (CImageUtil::LoadImage(strLoadFilename, m_previewImageSource)) - { - m_fileinfo += QStringLiteral("\r\n%1x%2\r\n%3") - .arg(m_previewImageSource.GetWidth()) - .arg(m_previewImageSource.GetHeight()) - .arg(m_previewImageSource.GetFormatDescription()); - - m_fileinfoAlphaTexture = m_fileinfo; - UpdateTextureType(); - foundPixmap = true; - } - } - - if (!foundPixmap) - { - m_ui->m_previewImageCtrl->setPixmap(QPixmap()); - m_ui->m_fileInfoCtrl->setText(WordWrap(m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); - } - - updateGeometry(); - - return foundPixmap; -} - -bool LegacyPreviewer::DisplayTextureProductModern(const char* fullProductImagePath) -{ - m_ui->m_modelPreviewWidget->hide(); - m_ui->m_texturePreviewWidget->show(); - - bool foundPixmap = false; - QImage previewImage; - AZStd::string productInfo; - AZStd::string productAlphaInfo; - AzToolsFramework::AssetBrowser::AssetBrowserTexturePreviewRequestsBus::BroadcastResult(foundPixmap, &AzToolsFramework::AssetBrowser::AssetBrowserTexturePreviewRequests::GetProductTexturePreview, fullProductImagePath, previewImage, productInfo, productAlphaInfo); - - if (foundPixmap) - { - QPixmap pix = QPixmap::fromImage(previewImage); - m_ui->m_previewImageCtrl->setPixmap(pix); - m_ui->m_previewImageCtrl->updateGeometry(); - CImageUtil::QImageToImage(previewImage, m_previewImageSource); - - m_fileinfo += QStringLiteral("\r\n%1x%2\r\n%3") - .arg(m_previewImageSource.GetWidth()) - .arg(m_previewImageSource.GetHeight()) - .arg(m_previewImageSource.GetFormatDescription()); - - m_fileinfoAlphaTexture = m_fileinfo; - - m_fileinfo += QString(productInfo.c_str()); - if (productAlphaInfo.empty()) - { - // If there is no separate info for alpha, use the image info - m_fileinfoAlphaTexture += QString(productInfo.c_str()); - } - else - { - m_fileinfoAlphaTexture += QString(productAlphaInfo.c_str()); - } - - - UpdateTextureType(); - } - else - { - m_ui->m_previewImageCtrl->setPixmap(QPixmap()); - m_ui->m_fileInfoCtrl->setText(WordWrap(m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); - } - - updateGeometry(); - return foundPixmap; -} - -void LegacyPreviewer::UpdateTextureType() -{ - m_previewImageUpdated.Copy(m_previewImageSource); - - switch (m_textureType) - { - case TextureType::RGB: - { - m_previewImageUpdated.SwapRedAndBlue(); - m_previewImageUpdated.FillAlpha(); - break; - } - case TextureType::RGBA: - { - m_previewImageUpdated.SwapRedAndBlue(); - break; - } - case TextureType::Alpha: - { - for (int h = 0; h < m_previewImageUpdated.GetHeight(); h++) - { - for (int w = 0; w < m_previewImageUpdated.GetWidth(); w++) - { - int a = m_previewImageUpdated.ValueAt(w, h) >> 24; - m_previewImageUpdated.ValueAt(w, h) = RGB(a, a, a) | 0xFF000000; - } - } - break; - } - } - // note that Qt will not deep copy the data, so WE MUST KEEP THE IMAGE DATA AROUND! - QPixmap qtPixmap = QPixmap::fromImage( - QImage(reinterpret_cast(m_previewImageUpdated.GetData()), m_previewImageUpdated.GetWidth(), m_previewImageUpdated.GetHeight(), QImage::Format_ARGB32)); - m_ui->m_previewImageCtrl->setPixmap(qtPixmap); - m_ui->m_fileInfoCtrl->setText(WordWrap(m_textureType == TextureType::Alpha? m_fileinfoAlphaTexture: m_fileinfo, m_ui->m_fileInfoCtrl->width() / s_CharWidth)); - m_ui->m_previewImageCtrl->updateGeometry(); -} - -bool LegacyPreviewer::FileInfoCompare(const FileInfo& f1, const FileInfo& f2) -{ - if ((f1.attrib & _A_SUBDIR) && !(f2.attrib & _A_SUBDIR)) - { - return true; - } - if (!(f1.attrib & _A_SUBDIR) && (f2.attrib & _A_SUBDIR)) - { - return false; - } - - return QString::compare(f1.filename, f2.filename, Qt::CaseInsensitive) < 0; -} - -QString LegacyPreviewer::WordWrap(const QString& string, int maxLength) -{ - QString result; - int length = 0; - - for (auto c : string) - { - if (c == '\n') - { - length = 0; - } - else if (length > maxLength) - { - result.append('\n'); - length = 0; - } - else - { - length++; - } - result.append(c); - } - return result; -} - -#include diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.h b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.h deleted file mode 100644 index 0035f23442..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include - -#include -#include -#endif - -namespace Ui -{ - class LegacyPreviewerClass; -} - -namespace AzToolsFramework -{ - namespace AssetBrowser - { - class ProductAssetBrowserEntry; - class SourceAssetBrowserEntry; - class AssetBrowserEntry; - } -} - -class QResizeEvent; - -class LegacyPreviewer - : public AzToolsFramework::AssetBrowser::Previewer -{ - Q_OBJECT -public: - AZ_CLASS_ALLOCATOR(LegacyPreviewer, AZ::SystemAllocator, 0); - - explicit LegacyPreviewer(QWidget* parent = nullptr); - ~LegacyPreviewer(); - - ////////////////////////////////////////////////////////////////////////// - // AzToolsFramework::AssetBrowser::Previewer - ////////////////////////////////////////////////////////////////////////// - void Clear() const override; - void Display(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) override; - const QString& GetName() const override; - - static const QString Name; - -protected: - void resizeEvent(QResizeEvent * event) override; - -private: - struct FileInfo - { - QString filename; - unsigned attrib; - time_t time_create; /* -1 for FAT file systems */ - time_t time_access; /* -1 for FAT file systems */ - time_t time_write; - _fsize_t size; - }; - - enum class TextureType - { - RGB, - RGBA, - Alpha - }; - - QScopedPointer m_ui; - CImageEx m_previewImageSource; - CImageEx m_previewImageUpdated; - TextureType m_textureType; - QString m_fileinfo; - QString m_fileinfoAlphaTexture; - - bool DisplayProduct(const AzToolsFramework::AssetBrowser::ProductAssetBrowserEntry* product); - void DisplaySource(const AzToolsFramework::AssetBrowser::SourceAssetBrowserEntry* source); - - QString GetFileSize(const char* path); - - bool DisplayTextureLegacy(const char* fullImagePath); - bool DisplayTextureProductModern(const char* fullProductImagePath); - - void UpdateTextureType(); - - static bool FileInfoCompare(const FileInfo& f1, const FileInfo& f2); - //! QLabel word wrap does not break long words such as filenames, so manual word wrap needed - static QString WordWrap(const QString& string, int maxLength); -}; diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.ui b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.ui deleted file mode 100644 index 649192d60f..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewer.ui +++ /dev/null @@ -1,176 +0,0 @@ - - - LegacyPreviewerClass - - - - 0 - 0 - 148 - 282 - - - - Preview - - - - 0 - - - 5 - - - 0 - - - 5 - - - 0 - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - - - - - - - - 0 - 0 - - - - - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - - - - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - - - - Qt::AutoText - - - false - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - true - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - CPreviewModelCtrl - QWidget -
Controls/PreviewModelCtrl.h
- 1 -
- - AzToolsFramework::AspectRatioAwarePixmapWidget - QWidget -
AzToolsFramework/UI/UICore/AspectRatioAwarePixmapWidget.hxx
- 1 -
-
- - -
diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp deleted file mode 100644 index 93620d26a6..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp +++ /dev/null @@ -1,71 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "EditorDefs.h" - -#include "LegacyPreviewerFactory.h" - -// AzToolsFramework -#include // for AssetBrowserEntry::AssetEntryType -#include // for EBusFindAssetTypeByName - -// Editor -#include "LegacyPreviewer.h" - - -AzToolsFramework::AssetBrowser::Previewer* LegacyPreviewerFactory::CreatePreviewer(QWidget* parent) const -{ - return new LegacyPreviewer(parent); -} - -bool LegacyPreviewerFactory::IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const -{ - using namespace AzToolsFramework::AssetBrowser; - - EBusFindAssetTypeByName meshAssetTypeResult("Static Mesh"); - AZ::AssetTypeInfoBus::BroadcastResult(meshAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - EBusFindAssetTypeByName textureAssetTypeResult("Texture"); - AZ::AssetTypeInfoBus::BroadcastResult(textureAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - - switch (entry->GetEntryType()) - { - case AssetBrowserEntry::AssetEntryType::Source: - { - const auto* source = azrtti_cast < const SourceAssetBrowserEntry * > (entry); - if (source->GetPrimaryAssetType() == textureAssetTypeResult.GetAssetType()) - { - return true; - } - AZStd::vector < const ProductAssetBrowserEntry * > products; - source->GetChildrenRecursively < ProductAssetBrowserEntry > (products); - for (auto* product : products) - { - if (product->GetAssetType() == textureAssetTypeResult.GetAssetType() || - product->GetAssetType() == meshAssetTypeResult.GetAssetType()) - { - return true; - } - } - break; - } - case AssetBrowserEntry::AssetEntryType::Product: - const auto* product = azrtti_cast < const ProductAssetBrowserEntry * > (entry); - return product->GetAssetType() == textureAssetTypeResult.GetAssetType() || - product->GetAssetType() == meshAssetTypeResult.GetAssetType(); - } - return false; -} - -const QString& LegacyPreviewerFactory::GetName() const -{ - return LegacyPreviewer::Name; -} diff --git a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h b/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h deleted file mode 100644 index e6b133cb97..0000000000 --- a/Code/Sandbox/Editor/AzAssetBrowser/Preview/LegacyPreviewerFactory.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include -#include - -class QString; - -class LegacyPreviewerFactory final - : public AzToolsFramework::AssetBrowser::PreviewerFactory -{ -public: - AZ_CLASS_ALLOCATOR(LegacyPreviewerFactory, AZ::SystemAllocator, 0); - - LegacyPreviewerFactory() = default; - ~LegacyPreviewerFactory() = default; - - ////////////////////////////////////////////////////////////////////////// - // AzToolsFramework::AssetBrowser::PreviewerFactory - ////////////////////////////////////////////////////////////////////////// - AzToolsFramework::AssetBrowser::Previewer* CreatePreviewer(QWidget* parent = nullptr) const override; - bool IsEntrySupported(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; - const QString& GetName() const override; -}; diff --git a/Code/Sandbox/Editor/BaseLibraryManager.cpp b/Code/Sandbox/Editor/BaseLibraryManager.cpp index 61c6354b1a..d9017c1be8 100644 --- a/Code/Sandbox/Editor/BaseLibraryManager.cpp +++ b/Code/Sandbox/Editor/BaseLibraryManager.cpp @@ -826,9 +826,6 @@ void CBaseLibraryManager::OnEditorNotifyEvent(EEditorNotifyEvent event) SetSelectedItem(0); ClearAll(); break; - case eNotify_OnMissionChange: - SetSelectedItem(0); - break; case eNotify_OnCloseScene: SetSelectedItem(0); ClearAll(); diff --git a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp b/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp deleted file mode 100644 index 9b07f59e6a..0000000000 --- a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp +++ /dev/null @@ -1,1194 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "PreviewModelCtrl.h" - -// AzQtComponents -#include - -// Editor -#include "Settings.h" -#include "Util/Image.h" -#include "Include/IIconManager.h" - -struct CPreviewModelCtrl::SPreviousContext -{ - CCamera renderCamera; - CCamera systemCamera; - int width; - int height; - HWND window; - bool isMainViewport; -}; - -CPreviewModelCtrl::CPreviewModelCtrl(QWidget* parent, Qt::WindowFlags f) - : QWidget(parent, f) -{ - OnCreate(); -} - -void CPreviewModelCtrl::OnCreate() -{ - m_bShowObject = true; - m_pRenderer = 0; - m_pObj = 0; - m_pEntity = 0; - m_nTimer = 0; - m_size = Vec3(0, 0, 0); - - m_bRotate = false; - m_rotateAngle = 0; - - m_backgroundTextureId = 0; - - m_pRenderer = GetIEditor()->GetRenderer(); - - m_fov = 60; - m_camera.SetFrustum(800, 600, DEG2RAD(m_fov), 0.02f, 10000.0f); - - m_bInRotateMode = false; - m_bInMoveMode = false; - - CDLight l; - - float L = 1.0f; - l.m_fRadius = 10000; - l.m_Flags |= DLF_SUN | DLF_DIRECTIONAL; - l.SetLightColor(ColorF(L, L, L, 1)); - l.SetPosition(Vec3(100, 100, 100)); - m_lights.push_back(l); - - m_bUseBacklight = false; - m_bContextCreated = false; - m_bHaveAnythingToRender = false; - m_bGrid = true; - m_bAxis = true; - m_bAxisParticleEditor = false; - m_bUpdate = false; - m_bShowNormals = false; - m_bShowPhysics = false; - m_bShowRenderInfo = false; - - m_cameraAngles.Set(0, 0, 0); - - m_clearColor.Set(0.5f, 0.5f, 0.5f); - m_ambientColor.Set(1.0f, 1.0f, 1.0f); - m_ambientMultiplier = 0.5f; - - m_cameraChangeCallback = NULL; - m_bPrecacheMaterial = false; - m_bDrawWireFrame = false; - - m_tileX = 0.0f; - m_tileY = 0.0f; - m_tileSizeX = 1.0f; - m_tileSizeY = 1.0f; - - m_aabb = AABB(2); - FitToScreen(); - - setAttribute(Qt::WA_NativeWindow); - setAttribute(Qt::WA_PaintOnScreen); - setAttribute(Qt::WA_OpaquePaintEvent); - - GetIEditor()->RegisterNotifyListener(this); -} - -CPreviewModelCtrl::~CPreviewModelCtrl() -{ - OnDestroy(); - ReleaseObject(); - GetIEditor()->UnregisterNotifyListener(this); -} - -bool CPreviewModelCtrl::CreateContext() -{ - // Create context. - if (m_pRenderer && !m_bContextCreated) - { - StorePreviousContext(); - m_bContextCreated = true; - - // save the old context, because CreateContext sets it, and we don't actually want that: - StorePreviousContext(); - m_pRenderer->CreateContext(m_hWnd); - - RestorePreviousContext(); - return true; - } - return false; -} - -void CPreviewModelCtrl::ReleaseObject() -{ - m_pObj = NULL; - m_pEntity = 0; - m_bHaveAnythingToRender = false; -} - -void CPreviewModelCtrl::LoadFile(const QString& modelFile, bool changeCamera) -{ - m_bHaveAnythingToRender = false; - if (!m_hWnd) - { - return; - } - if (!m_pRenderer) - { - return; - } - - ReleaseObject(); - - if (modelFile.isEmpty()) - { - if (m_nTimer != 0) - { - killTimer(m_nTimer); - } - m_nTimer = 0; - update(); - return; - } - - m_loadedFile = modelFile; - - QString strFileExt = QFileInfo(modelFile).suffix(); - const bool isSKEL = strFileExt.compare(QStringLiteral(CRY_SKEL_FILE_EXT), Qt::CaseInsensitive) == 0; - const bool isSKIN = strFileExt.compare(QStringLiteral(CRY_SKIN_FILE_EXT), Qt::CaseInsensitive) == 0; - const bool isCDF = strFileExt.compare(QStringLiteral(CRY_CHARACTER_DEFINITION_FILE_EXT), Qt::CaseInsensitive) == 0; - const bool isCGA = strFileExt.compare(QStringLiteral(CRY_ANIM_GEOMETRY_FILE_EXT), Qt::CaseInsensitive) == 0; - const bool isCGF = strFileExt.compare(QStringLiteral(CRY_GEOMETRY_FILE_EXT), Qt::CaseInsensitive) == 0; - - if (isCGF) - { - // Load object. - m_pObj = GetIEditor()->Get3DEngine()->LoadStatObjAutoRef(modelFile.toUtf8().data(), NULL, NULL, false); - if (!m_pObj) - { - Warning("Loading of geometry object %s failed.", modelFile.toUtf8().constData()); - if (m_nTimer != 0) - { - killTimer(m_nTimer); - } - m_nTimer = 0; - update(); - return; - } - m_aabb.min = m_pObj->GetBoxMin(); - m_aabb.max = m_pObj->GetBoxMax(); - } - else - { - if (m_nTimer != 0) - { - killTimer(m_nTimer); - } - m_nTimer = 0; - update(); - return; - } - - m_bHaveAnythingToRender = true; - - if (changeCamera) - { - FitToScreen(); - } - - update(); -} - -void CPreviewModelCtrl::SetAspectRatio(float aspectRatio) -{ - if (aspectRatio != m_aspectRatio) - { - m_aspectRatio = aspectRatio; - m_useAspectRatio = true; - updateGeometry(); - } -} - -bool CPreviewModelCtrl::hasHeightForWidth() const -{ - return m_useAspectRatio; -} - -int CPreviewModelCtrl::heightForWidth(int w) const -{ - if (m_useAspectRatio) - { - return static_cast(static_cast(w) / m_aspectRatio); - } - - return QWidget::heightForWidth(w); -} - -void CPreviewModelCtrl::SetEntity(IRenderNode* entity) -{ - m_bHaveAnythingToRender = false; - if (m_pEntity != entity) - { - m_pEntity = entity; - if (m_pEntity) - { - m_bHaveAnythingToRender = true; - m_aabb = m_pEntity->GetBBox(); - } - update(); - } -} - -void CPreviewModelCtrl::SetObject(IStatObj* pObject) -{ - if (m_pObj != pObject) - { - m_bHaveAnythingToRender = false; - m_pObj = pObject; - if (m_pObj) - { - m_bHaveAnythingToRender = true; - m_aabb = m_pObj->GetAABB(); - } - update(); - } -} - -void CPreviewModelCtrl::SetCameraRadius(float fRadius) -{ - m_cameraRadius = fRadius; - - Matrix34 m = m_camera.GetMatrix(); - Vec3 dir = m.TransformVector(Vec3(0, 1, 0)); - Matrix34 tm = Matrix33::CreateRotationVDir(dir, 0); - tm.SetTranslation(m_cameraTarget - dir * m_cameraRadius); - m_camera.SetMatrix(tm); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } -} - -void CPreviewModelCtrl::SetCameraLookAt(float fRadiusScale, const Vec3& fromDir) -{ - m_cameraTarget = m_aabb.GetCenter(); - m_cameraRadius = m_aabb.GetRadius() * fRadiusScale; - - Vec3 dir = fromDir.GetNormalized(); - Matrix34 tm = Matrix33::CreateRotationVDir(dir, 0); - tm.SetTranslation(m_cameraTarget - dir * m_cameraRadius); - m_camera.SetMatrix(tm); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } -} - -CCamera& CPreviewModelCtrl::GetCamera() -{ - return m_camera; -} - -void CPreviewModelCtrl::UseBackLight(bool bEnable) -{ - if (bEnable) - { - m_lights.resize(1); - CDLight l; - l.SetPosition(Vec3(-100, 100, -100)); - float L = 0.5f; - l.SetLightColor(ColorF(L, L, L, 1)); - l.m_fRadius = 1000; - l.m_Flags |= DLF_POINT; - m_lights.push_back(l); - } - else - { - m_lights.resize(1); - } - m_bUseBacklight = bEnable; -} - -void CPreviewModelCtrl::SetCamera(CCamera& cam) -{ - m_camera.SetPosition(cam.GetPosition()); - -#if defined(AZ_PLATFORM_WINDOWS) - // Needed for high DPI mode on windows - const qreal ratio = devicePixelRatioF(); -#else - const qreal ratio = 1.0f; -#endif - const int w = width() * ratio * m_tileSizeX; - const int h = height() * ratio * m_tileSizeY; - m_camera.SetFrustum(w, h, DEG2RAD(m_fov), m_camera.GetNearPlane(), m_camera.GetFarPlane()); - - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } -} - -void CPreviewModelCtrl::SetOrbitAngles([[maybe_unused]] const Ang3& ang) -{ - assert(0); -} - -bool CPreviewModelCtrl::Render() -{ - const int w = width(); - const int h = height(); - - if (h < 2 || w < 2) - { - return false; - } - - if (!m_bContextCreated) - { - if (!CreateContext()) - { - return false; - } - } - - _smart_ptr pMaterial; - - if (m_bPrecacheMaterial) - { - // Precache material - This loads/creates the material, shader and textures - // Moving this to the top of Render() so precaching precedes current and future - // rendering code - - _smart_ptr pCurMat = pMaterial; - - if (!pCurMat) - { - pCurMat = GetCurrentMaterial(); - } - - if (pCurMat) - { - pCurMat->PrecacheMaterial(0.0f, NULL, true, true); - } - } - - SetCamera(m_camera); - - m_pRenderer->SetClearColor(Vec3(m_clearColor.r, m_clearColor.g, m_clearColor.b)); - m_pRenderer->BeginFrame(); - SetCurrentContext(); - m_pRenderer->SetRenderTile(m_tileX, m_tileY, m_tileSizeX, m_tileSizeY); - - // Render grid. Explicitly clear color and depth buffer first - // (otherwise ->EndEf3D() will do that and thereby clear the grid). - m_pRenderer->ClearTargetsImmediately(FRT_CLEAR, m_clearColor); - - DrawBackground(); - if (m_bGrid || m_bAxis) - { - DrawGrid(); - } - - // save some cvars - int showNormals = gEnv->pConsole->GetCVar("r_ShowNormals")->GetIVal(); - int showInfo = gEnv->pConsole->GetCVar("r_displayInfo")->GetIVal(); - - gEnv->pConsole->GetCVar("r_ShowNormals")->Set((int)m_bShowNormals); - gEnv->pConsole->GetCVar("r_displayInfo")->Set((int)m_bShowRenderInfo); - - // Render object. - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_camera, SRenderingPassInfo::DEFAULT_FLAGS, true); - m_pRenderer->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID()); - m_pRenderer->BeginSpawningShadowGeneratingRendItemJobs(passInfo.ThreadID()); - m_pRenderer->EF_StartEf(passInfo); - m_pRenderer->ResetToDefault(); - - - { - CScopedWireFrameMode scopedWireFrame(m_pRenderer, m_bDrawWireFrame ? R_WIREFRAME_MODE : R_SOLID_MODE); - - // Add lights. - for (size_t i = 0; i < m_lights.size(); i++) - { - m_pRenderer->EF_ADDDlight(&m_lights[i], passInfo); - } - - if (m_bShowObject) - { - RenderObject(pMaterial, passInfo); - } - - m_pRenderer->EF_EndEf3D(SHDF_NOASYNC | SHDF_STREAM_SYNC, -1, -1, passInfo); - } - - m_pRenderer->EF_RenderTextMessages(); - m_pRenderer->RenderDebug(false); - m_pRenderer->EndFrame(); - m_pRenderer->SetRenderTile(); - - // Restore main context. - RestorePreviousContext(); - - gEnv->pConsole->GetCVar("r_ShowNormals")->Set(showNormals); - gEnv->pConsole->GetCVar("r_displayInfo")->Set(showInfo); - - return true; -} - -void CPreviewModelCtrl::RenderObject(_smart_ptr pMaterial, SRenderingPassInfo& passInfo) -{ - SRendParams rp; - rp.dwFObjFlags = 0; - rp.AmbientColor = m_ambientColor * m_ambientMultiplier; - rp.dwFObjFlags |= FOB_NO_FOG; - rp.pMaterial = pMaterial; - - Matrix34 tm; - tm.SetIdentity(); - rp.pMatrix = &tm; - - if (m_bRotate) - { - tm.SetRotationXYZ(Ang3(0, 0, m_rotateAngle)); - m_rotateAngle += 0.1f; - } - - if (m_pObj) - { - m_pObj->Render(rp, passInfo); - } - - if (m_pEntity) - { - m_pEntity->Render(rp, passInfo); - } -} - -void CPreviewModelCtrl::DrawGrid() -{ - // Draw grid. - float step = 0.1f; - float XR = 5; - float YR = 5; - - IRenderAuxGeom* pRag = m_pRenderer->GetIRenderAuxGeom(); - SAuxGeomRenderFlags nRendFlags = pRag->GetRenderFlags(); - - pRag->SetRenderFlags(e_Def3DPublicRenderflags); - SAuxGeomRenderFlags nNewFlags = pRag->GetRenderFlags(); - nNewFlags.SetAlphaBlendMode(e_AlphaBlended); - pRag->SetRenderFlags(nNewFlags); - - int nGridAlpha = 40; - if (m_bGrid) - { - // Draw grid. - for (float x = -XR; x < XR; x += step) - { - if (fabs(x) > 0.01) - { - pRag->DrawLine(Vec3(x, -YR, 0), ColorB(150, 150, 150, nGridAlpha), Vec3(x, YR, 0), ColorB(150, 150, 150, nGridAlpha)); - } - } - for (float y = -YR; y < YR; y += step) - { - if (fabs(y) > 0.01) - { - pRag->DrawLine(Vec3(-XR, y, 0), ColorB(150, 150, 150, nGridAlpha), Vec3(XR, y, 0), ColorB(150, 150, 150, nGridAlpha)); - } - } - } - - nGridAlpha = 60; - if (m_bAxis) - { - // Draw axis. - pRag->DrawLine(Vec3(0, 0, 0), ColorB(255, 0, 0, nGridAlpha), Vec3(XR, 0, 0), ColorB(255, 0, 0, nGridAlpha)); - pRag->DrawLine(Vec3(0, 0, 0), ColorB(0, 255, 0, nGridAlpha), Vec3(0, YR, 0), ColorB(0, 255, 0, nGridAlpha)); - pRag->DrawLine(Vec3(0, 0, 0), ColorB(0, 0, 255, nGridAlpha), Vec3(0, 0, YR), ColorB(0, 0, 255, nGridAlpha)); - } - pRag->Flush(); - pRag->SetRenderFlags(nRendFlags); -} - -void CPreviewModelCtrl::timerEvent(QTimerEvent* event) -{ - if (isVisible()) - { - if (m_bHaveAnythingToRender) - { - update(); - } - } - - QWidget::timerEvent(event); -} - -void CPreviewModelCtrl::SetCameraTM(const Matrix34& cameraTM) -{ - m_camera.SetMatrix(cameraTM); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } -} - -void CPreviewModelCtrl::GetCameraTM(Matrix34& cameraTM) -{ - cameraTM = m_camera.GetMatrix(); -} - -void CPreviewModelCtrl::DeleteRenderContex() -{ - ReleaseObject(); - - // Destroy render context. - if (m_pRenderer && m_bContextCreated) - { - m_pRenderer->DeleteContext(m_hWnd); - m_bContextCreated = false; - } -} - -void CPreviewModelCtrl::OnDestroy() -{ - DeleteRenderContex(); - - if (m_nTimer) - { - killTimer(m_nTimer); - } -} - -void CPreviewModelCtrl::OnLButtonDown(QPoint point) -{ - m_bInRotateMode = true; - m_mousePosition = point; - m_previousMousePosition = m_mousePosition; - - setFocus(); - update(); -} - -void CPreviewModelCtrl::OnLButtonUp(QPoint point) -{ - m_bInRotateMode = false; - update(); - m_mousePosition = point; - m_previousMousePosition = m_mousePosition; -} - -void CPreviewModelCtrl::OnMButtonDown(QPoint point) -{ - m_bInPanMode = true; - update(); - m_mousePosition = point; - m_previousMousePosition = m_mousePosition; -} - -void CPreviewModelCtrl::OnMButtonUp(QPoint point) -{ - m_bInPanMode = false; - update(); - m_mousePosition = point; - m_previousMousePosition = m_mousePosition; -} - -void CPreviewModelCtrl::mouseMoveEvent(QMouseEvent* event) -{ - // TODO: Add your message handler code here and/or call default - QWidget::mouseMoveEvent(event); - - const QPoint& point = event->pos(); - if (point == m_previousMousePosition) - { - return; - } - - if (m_bInMoveMode) - { - // Zoom. - Matrix34 m = m_camera.GetMatrix(); - Vec3 xdir(0, 0, 0); - Vec3 zdir = m.GetColumn1().GetNormalized(); - - float step = 0.002f; - float dx = (point.x() - m_previousMousePosition.x()); - float dy = (point.y() - m_previousMousePosition.y()); - m_camera.SetPosition(m_camera.GetPosition() + step * xdir * dx + step * zdir * dy); - SetCamera(m_camera); - - if (gSettings.stylusMode) - { - m_previousMousePosition = point; - } - else - { - AzQtComponents::SetCursorPos(mapToGlobal(m_previousMousePosition)); - } - - update(); - } - else if (m_bInRotateMode) - { - Vec3 pos = m_camera.GetMatrix().GetTranslation(); - m_cameraRadius = Vec3(m_camera.GetMatrix().GetTranslation() - m_cameraTarget).GetLength(); - // Look - Ang3 angles(-point.y() + m_previousMousePosition.y(), 0, -point.x() + m_previousMousePosition.x()); - angles = angles * 0.002f; - - Matrix34 camtm = m_camera.GetMatrix(); - Matrix33 Rz = Matrix33::CreateRotationXYZ(Ang3(0, 0, angles.z)); // Rotate around vertical axis. - Matrix33 Rx = Matrix33::CreateRotationAA(angles.x, camtm.GetColumn0()); // Rotate with angle around x axis in camera space. - - Vec3 dir = camtm.TransformVector(Vec3(0, 1, 0)); - Vec3 newdir = (Rx * Rz).TransformVector(dir).GetNormalized(); - camtm = Matrix34(Matrix33::CreateRotationVDir(newdir, 0), m_cameraTarget - newdir * m_cameraRadius); - m_camera.SetMatrix(camtm); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } - - if (gSettings.stylusMode) - { - m_previousMousePosition = point; - } - else - { - AzQtComponents::SetCursorPos(mapToGlobal(m_previousMousePosition)); - } - - update(); - } - else if (m_bInPanMode) - { - // Slide. - float speedScale = 0.001f; - Matrix34 m = m_camera.GetMatrix(); - Vec3 xdir = m.GetColumn0().GetNormalized(); - Vec3 zdir = m.GetColumn2().GetNormalized(); - - Vec3 pos = m_cameraTarget; - pos += 0.1f * xdir * (point.x() - m_previousMousePosition.x()) * speedScale + 0.1f * zdir * (m_previousMousePosition.y() - point.y()) * speedScale; - m_cameraTarget = pos; - - Vec3 dir = m.TransformVector(Vec3(0, 1, 0)); - m.SetTranslation(m_cameraTarget - dir * m_cameraRadius); - m_camera.SetMatrix(m); - if (m_cameraChangeCallback) - { - m_cameraChangeCallback(m_pCameraChangeUserData, this); - } - - if (gSettings.stylusMode) - { - m_previousMousePosition = point; - } - else - { - AzQtComponents::SetCursorPos(mapToGlobal(m_previousMousePosition)); - } - - update(); - } -} - -void CPreviewModelCtrl::OnRButtonDown(QPoint point) -{ - m_bInMoveMode = true; - m_mousePosition = point; - m_previousMousePosition = point; - update(); -} - -void CPreviewModelCtrl::OnRButtonUp(QPoint point) -{ - m_bInMoveMode = false; - - m_mousePosition = point; - m_previousMousePosition = point; - - update(); -} - -void CPreviewModelCtrl::wheelEvent(QWheelEvent* event) -{ - const short zDelta = event->angleDelta().y(); - // TODO: Add your message handler code here and/or call default - Matrix34 m = m_camera.GetMatrix(); - Vec3 zdir = m.GetColumn1().GetNormalized(); - - //m_camera.SetPosition( m_camera.GetPos() + ydir*(m_mousePos.y-point.y),xdir*(m_mousePos.x-point.x) ); - m_camera.SetPosition(m_camera.GetPosition() + 0.002f * zdir * (zDelta)); - SetCamera(m_camera); - update(); -} - -void CPreviewModelCtrl::EnableUpdate(bool bUpdate) -{ - m_bUpdate = bUpdate; - if (m_bUpdate && !m_nTimer) - { - m_nTimer = startTimer(1000); - } - else if (!m_bUpdate && m_nTimer) - { - killTimer(m_nTimer), m_nTimer = 0; - } -} - -void CPreviewModelCtrl::Update(bool bForceUpdate) -{ - ProcessKeys(); - - if (m_bUpdate && m_bHaveAnythingToRender || bForceUpdate) - { - if (isVisible()) - { - update(); - } - } -} - -void CPreviewModelCtrl::SetRotation(bool bEnable) -{ - m_bRotate = bEnable; -} - -void CPreviewModelCtrl::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnIdleUpdate: - Update(); - break; - } -} - -void CPreviewModelCtrl::GetImageOffscreen(CImageEx& image, const QSize& customSize) -{ - // hiding a window can cause this to be dropped, since it no longer associates with - // an actual operating system window handle. - if (!m_hWnd) - { - return; - } - if (!m_pRenderer) - { - return; - } - - m_pRenderer->EnableSwapBuffers(false); - Render(); - m_pRenderer->EnableSwapBuffers(true); - - int w; - int h; - - if (customSize.isValid()) - { - w = customSize.width(); - h = customSize.height(); - } - else - { - w = width(); - h = height(); - } - - image.Allocate(w, h); - - // the renderer will read the frame buffer of the current render context, so we need to set ours as the current before we execute this command. - SetCurrentContext(); - m_pRenderer->ReadFrameBufferFast(image.GetData(), w, h); - RestorePreviousContext(); -} - -void CPreviewModelCtrl::SetClearColor(const ColorF& color) -{ - m_clearColor = color; -} - - -namespace PreviewModelControl -{ - struct MaterialId - { - const void* ptr; - int id; - - MaterialId(const void* a_ptr, int a_id) - : ptr(a_ptr) - , id(a_id) - { - } - - bool operator<(const MaterialId& a) const - { - return ptr < a.ptr || id < a.id; - } - }; - - static int GetFaceCountRecursively(IStatObj* p) - { - if (!p) - { - return 0; - } - int n = 0; - if (p->GetRenderMesh()) - { - n += p->GetRenderMesh()->GetIndicesCount() / 3; - } - for (int i = 0; i < p->GetSubObjectCount(); ++i) - { - IStatObj::SSubObject* const pS = p->GetSubObject(i); - if (pS) - { - n += GetFaceCountRecursively(pS->pStatObj); - } - } - return n; - } - - static int GetVertexCountRecursively(IStatObj* p) - { - if (!p) - { - return 0; - } - int n = 0; - if (p->GetRenderMesh()) - { - n += p->GetRenderMesh()->GetVerticesCount(); - } - for (int i = 0; i < p->GetSubObjectCount(); ++i) - { - IStatObj::SSubObject* const pS = p->GetSubObject(i); - if (pS) - { - n += GetVertexCountRecursively(pS->pStatObj); - } - } - return n; - } - - static int GetMaxLodRecursively(IStatObj* p) - { - if (!p) - { - return 0; - } - int n = 0; - for (int i = 1; i < 10; i++) - { - if (p->GetLodObject(i)) - { - n = i; - } - } - for (int i = 0; i < p->GetSubObjectCount(); ++i) - { - IStatObj::SSubObject* const pS = p->GetSubObject(i); - if (pS) - { - const int n2 = GetMaxLodRecursively(pS->pStatObj); - n = (n < n2) ? n2 : n; - } - } - return n; - } - - static void CollectMaterialsRecursively(std::set& mats, IStatObj* p) - { - if (!p) - { - return; - } - if (p->GetRenderMesh()) - { - TRenderChunkArray& ch = p->GetRenderMesh()->GetChunks(); - for (size_t i = 0; i < ch.size(); ++i) - { - mats.insert(PreviewModelControl::MaterialId(p->GetMaterial(), ch[i].m_nMatID)); - } - } - for (int i = 0; i < p->GetSubObjectCount(); ++i) - { - IStatObj::SSubObject* const pS = p->GetSubObject(i); - if (pS) - { - CollectMaterialsRecursively(mats, pS->pStatObj); - } - } - } -} - - -int CPreviewModelCtrl::GetFaceCount() -{ - if (m_pObj) - { - return PreviewModelControl::GetFaceCountRecursively(m_pObj); - } - return 0; -} - -int CPreviewModelCtrl::GetVertexCount() -{ - if (m_pObj) - { - return PreviewModelControl::GetVertexCountRecursively(m_pObj); - } - return 0; -} - -int CPreviewModelCtrl::GetMaxLod() -{ - if (m_pObj) - { - return PreviewModelControl::GetMaxLodRecursively(m_pObj); - } - return 0; -} - -int CPreviewModelCtrl::GetMtlCount() -{ - if (m_pObj) - { - std::set mats; - CollectMaterialsRecursively(mats, m_pObj); - return (int)mats.size(); - } - return 0; -} - -void CPreviewModelCtrl::FitToScreen() -{ - SetCameraLookAt(2.0f, Vec3(1, 1, -0.5)); -} - -void CPreviewModelCtrl::ProcessKeys() -{ - if (!hasFocus()) - { - return; - } - - int moveSpeed = 1; - - Matrix34 m = m_camera.GetMatrix(); - - Vec3 ydir = m.GetColumn2().GetNormalized(); - Vec3 xdir = m.GetColumn0().GetNormalized(); - - Vec3 pos = m.GetTranslation(); - - float speedScale = 60.0f * GetIEditor()->GetSystem()->GetITimer()->GetFrameTime(); - if (speedScale > 20) - { - speedScale = 20; - } - - speedScale *= 0.04f; - - if (CheckVirtualKey(Qt::Key_Shift)) - { - speedScale *= gSettings.cameraFastMoveSpeed; - } - - bool isDirty = false; - - if (CheckVirtualKey(Qt::Key_Up) || CheckVirtualKey(Qt::Key_W)) - { - // move forward - m_camera.SetPosition(pos + speedScale * moveSpeed * ydir); - SetCamera(m_camera); - isDirty = true; - } - - if (CheckVirtualKey(Qt::Key_Down) || CheckVirtualKey(Qt::Key_S)) - { - // move backward - m_camera.SetPosition(pos - speedScale * moveSpeed * ydir); - SetCamera(m_camera); - isDirty = true; - } - - if (isDirty) - { - if (!m_bUpdate) - { - // if we're not going to be autoupdating then we need to do a one-time invalidation here. - update(); - } - } -} - -void CPreviewModelCtrl::SetBackgroundTexture(const QString& textureFilename) -{ - m_backgroundTextureId = GetIEditor()->GetIconManager()->GetIconTexture(textureFilename.toUtf8().constData()); -} - -void CPreviewModelCtrl::DrawBackground() -{ - if (!m_backgroundTextureId) - { - return; - } - - int rcw = width(); - int rch = height(); - - TransformationMatrices backupSceneMatrices; - - m_pRenderer->Set2DMode(rcw, rch, backupSceneMatrices, 0.0f, 1.0f); - - m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - - float uvs[4], uvt[4]; - uvs[3] = 0; - uvt[3] = 1; - uvs[2] = 1; - uvt[2] = 1; - uvs[1] = 1; - uvt[1] = 0; - uvs[0] = 0; - uvt[0] = 0; - - float color[4] = {1, 1, 1, 1}; - - m_pRenderer->DrawImageWithUV(0, 0, 0.5f, rcw, rch, m_backgroundTextureId, uvs, uvt, color[0], color[1], color[2], color[3]); - m_pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA); - - m_pRenderer->Unset2DMode(backupSceneMatrices); -} - -_smart_ptr CPreviewModelCtrl::GetCurrentMaterial() -{ - if (m_pObj) - { - return m_pObj->GetMaterial(); - } - else if (m_pEntity) - { - return m_pEntity->GetMaterial(); - } - - return NULL; -} - -void CPreviewModelCtrl::StorePreviousContext() -{ - SPreviousContext previous; - previous.width = m_pRenderer->GetWidth(); - previous.height = m_pRenderer->GetHeight(); - previous.window = (HWND)m_pRenderer->GetCurrentContextHWND(); - previous.renderCamera = m_pRenderer->GetCamera(); - previous.systemCamera = gEnv->pSystem->GetViewCamera(); - previous.isMainViewport = m_pRenderer->IsCurrentContextMainVP(); - m_previousContexts.push_back(previous); -} - -// Copied from the non-crashing QViewport.cpp -void CPreviewModelCtrl::SetCurrentContext() -{ - StorePreviousContext(); - - m_pRenderer->SetCurrentContext(m_hWnd); - -#if defined(AZ_PLATFORM_WINDOWS) - // Needed for high DPI mode on windows - const qreal ratio = devicePixelRatioF(); -#else - const qreal ratio = 1.0f; -#endif - m_pRenderer->ChangeViewport(0, 0, width() * ratio, height() * ratio); - m_pRenderer->SetCamera(m_camera); - gEnv->pSystem->SetViewCamera(m_camera); -} - -void CPreviewModelCtrl::RestorePreviousContext() -{ - if (m_previousContexts.empty()) - { - assert(0); - return; - } - - SPreviousContext x = m_previousContexts.back(); - m_previousContexts.pop_back(); - m_pRenderer->SetCurrentContext(x.window); - m_pRenderer->ChangeViewport(0, 0, x.width, x.height, x.isMainViewport); - m_pRenderer->SetCamera(x.renderCamera); - gEnv->pSystem->SetViewCamera(x.systemCamera); -} - -void CPreviewModelCtrl::showEvent([[maybe_unused]] QShowEvent* event) -{ - m_hWnd = reinterpret_cast(effectiveWinId()); -} - -QSize CPreviewModelCtrl::minimumSizeHint() const -{ - return QSize(50, 50); -} - -QPaintEngine* CPreviewModelCtrl::paintEngine() const -{ - return nullptr; -} - -void CPreviewModelCtrl::paintEvent(QPaintEvent* event) -{ - event->accept(); - Render(); -} - -void CPreviewModelCtrl::mousePressEvent(QMouseEvent* event) -{ - switch (event->button()) - { - case Qt::LeftButton: - OnLButtonDown(event->pos()); - break; - case Qt::MiddleButton: - OnMButtonDown(event->pos()); - break; - case Qt::RightButton: - OnRButtonDown(event->pos()); - break; - } -} - -void CPreviewModelCtrl::mouseReleaseEvent(QMouseEvent* event) -{ - switch (event->button()) - { - case Qt::LeftButton: - OnLButtonUp(event->pos()); - break; - case Qt::MiddleButton: - OnMButtonUp(event->pos()); - break; - case Qt::RightButton: - OnRButtonUp(event->pos()); - break; - } -} - -#include diff --git a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h b/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h deleted file mode 100644 index 6388be9fd5..0000000000 --- a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h +++ /dev/null @@ -1,198 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_CONTROLS_PREVIEWMODELCTRL_H -#define CRYINCLUDE_EDITOR_CONTROLS_PREVIEWMODELCTRL_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include - -#include - -#endif - -struct IRenderNode; -class CImageEx; - -class CPreviewModelCtrl - : public QWidget - , public IEditorNotifyListener -{ - Q_OBJECT -public: - explicit CPreviewModelCtrl(QWidget* parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()); - - QSize minimumSizeHint() const override; - -public: - void LoadFile(const QString& modelFile, bool changeCamera = true); - Vec3 GetSize() const { return m_size; }; - QString GetLoadedFile() const { return m_loadedFile; } - - void SetEntity(IRenderNode* entity); - void SetObject(IStatObj* pObject); - IStatObj* GetObject() { return m_pObj; } - void SetCameraLookAt(float fRadiusScale, const Vec3& dir = Vec3(0, 1, 0)); - void SetCameraRadius(float fRadius); - CCamera& GetCamera(); - void SetGrid(bool bEnable) { m_bGrid = bEnable; } - void SetAxis(bool bEnable, bool forParticleEditor = false) { m_bAxis = bEnable; m_bAxisParticleEditor = forParticleEditor; } - void SetRotation(bool bEnable); - void SetClearColor(const ColorF& color); - void SetBackgroundTexture(const QString& textureFilename); - void UseBackLight(bool bEnable); - bool UseBackLight() const { return m_bUseBacklight; } - void SetShowNormals(bool bShow) { m_bShowNormals = bShow; } - void SetShowPhysics(bool bShow) { m_bShowPhysics = bShow; } - void SetShowRenderInfo(bool bShow) { m_bShowRenderInfo = bShow; } - - void EnableUpdate(bool bEnable); - bool IsUpdateEnabled() const { return m_bUpdate; } - void Update(bool bForceUpdate = false); - void ProcessKeys(); - - // this turns on and off aspect-ratio-maintaining. Use it when the widget is free to resize itself. - void SetAspectRatio(float newAspectRatio); - int heightForWidth(int w) const override; - bool hasHeightForWidth() const override; - - void GetImageOffscreen(CImageEx& image, const QSize& customSize = QSize(0, 0)); - - void GetCameraTM(Matrix34& cameraTM); - void SetCameraTM(const Matrix34& cameraTM); - - // Place camera so that whole object fits on screen. - void FitToScreen(); - - // Get information about the preview model. - int GetFaceCount(); - int GetVertexCount(); - int GetMaxLod(); - int GetMtlCount(); - - void SetShowObject(bool bShowObject) {m_bShowObject = bShowObject; } - bool GetShowObject() {return m_bShowObject; } - - void SetAmbient(ColorF amb) { m_ambientColor = amb; } - void SetAmbientMultiplier(f32 multiplier) { m_ambientMultiplier = multiplier; } - - typedef void (* CameraChangeCallback)(void* m_userData, CPreviewModelCtrl* m_currentCamera); - void SetCameraChangeCallback(CameraChangeCallback callback, void* userData) { m_cameraChangeCallback = callback, m_pCameraChangeUserData = userData; } - - void EnableMaterialPrecaching(bool bPrecacheMaterial) { m_bPrecacheMaterial = bPrecacheMaterial; } - void EnableWireframeRendering(bool bDrawWireframe) { m_bDrawWireFrame = bDrawWireframe; } - -public: - ~CPreviewModelCtrl(); - - bool CreateContext(); - void ReleaseObject(); - void DeleteRenderContex(); - -protected: - void OnCreate(); - void OnDestroy(); - void OnLButtonDown(QPoint point); - void OnLButtonUp(QPoint point); - void OnMButtonDown(QPoint point); - void OnMButtonUp(QPoint point); - void OnRButtonUp(QPoint point); - void OnRButtonDown(QPoint point); - - QPaintEngine* paintEngine() const override; - void showEvent(QShowEvent* event) override; - void paintEvent(QPaintEvent* event) override; - void timerEvent(QTimerEvent* event) override; - void mouseMoveEvent(QMouseEvent* event) override; - void mousePressEvent(QMouseEvent* event) override; - void mouseReleaseEvent(QMouseEvent* event) override; - void wheelEvent(QWheelEvent* event) override; - - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - -protected: - virtual bool Render(); - virtual void SetCamera(CCamera& cam); - - virtual void RenderObject(_smart_ptr pMaterial, SRenderingPassInfo& passInfo); - - HWND m_hWnd; - CCamera m_camera; - float m_fov; - - struct SPreviousContext; - std::vector m_previousContexts; - - void SetOrbitAngles(const Ang3& ang); - void DrawGrid(); - void DrawBackground(); - _smart_ptr GetCurrentMaterial(); - - _smart_ptr m_pObj; - - IRenderer* m_pRenderer; - bool m_bContextCreated; - - Vec3 m_size; - Vec3 m_pos; - int m_nTimer; - bool m_useAspectRatio = false; - float m_aspectRatio = 1.0f; - - QString m_loadedFile; - std::vector m_lights; - - AABB m_aabb; - Vec3 m_cameraTarget; - float m_cameraRadius; - Vec3 m_cameraAngles; - bool m_bInRotateMode; - bool m_bInMoveMode; - bool m_bInPanMode; - QPoint m_mousePosition; - QPoint m_previousMousePosition; - IRenderNode* m_pEntity; - bool m_bHaveAnythingToRender; - bool m_bGrid; - bool m_bAxis; - bool m_bAxisParticleEditor; - bool m_bUpdate; - bool m_bRotate; - float m_rotateAngle; - ColorF m_clearColor; - ColorF m_ambientColor; - f32 m_ambientMultiplier; - bool m_bUseBacklight; - bool m_bShowObject; - bool m_bPrecacheMaterial; - bool m_bDrawWireFrame; - bool m_bShowNormals; - bool m_bShowPhysics; - bool m_bShowRenderInfo; - int m_backgroundTextureId; - float m_tileX; - float m_tileY; - float m_tileSizeX; - float m_tileSizeY; - CameraChangeCallback m_cameraChangeCallback; - void* m_pCameraChangeUserData; - -protected: - void StorePreviousContext(); - void SetCurrentContext(); - void RestorePreviousContext(); -}; -#endif // CRYINCLUDE_EDITOR_CONTROLS_PREVIEWMODELCTRL_H diff --git a/Code/Sandbox/Editor/Controls/TimeOfDaySlider.cpp b/Code/Sandbox/Editor/Controls/TimeOfDaySlider.cpp deleted file mode 100644 index 9b2b62d6f5..0000000000 --- a/Code/Sandbox/Editor/Controls/TimeOfDaySlider.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : implementation file - - -#include "EditorDefs.h" - -#include "TimeOfDaySlider.h" - -QString TimeOfDaySlider::hoverValueText(int sliderValue) const -{ - return QString::fromLatin1("%1:%2").arg(static_cast(sliderValue / 60)).arg(sliderValue % 60, 2, 10, QLatin1Char('0')); -} - -#include diff --git a/Code/Sandbox/Editor/Controls/TimeOfDaySlider.h b/Code/Sandbox/Editor/Controls/TimeOfDaySlider.h deleted file mode 100644 index 72c4c08394..0000000000 --- a/Code/Sandbox/Editor/Controls/TimeOfDaySlider.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H -#define CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H -#pragma once - - -#if !defined(Q_MOC_RUN) -#include -#endif - -class TimeOfDaySlider - : public AzQtComponents::SliderInt -{ - Q_OBJECT -public: - using AzQtComponents::SliderInt::SliderInt; - -protected: - QString hoverValueText(int sliderValue) const override; -}; - -#endif // CRYINCLUDE_EDITOR_TIMEOFDAYSLIDER_H diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index aa255e185d..9ad57d6581 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -78,7 +78,6 @@ AZ_POP_DISABLE_WARNING #include // CryCommon -#include #include #include #include @@ -99,7 +98,6 @@ AZ_POP_DISABLE_WARNING #include "GridSettingsDialog.h" #include "LayoutConfigDialog.h" #include "ViewManager.h" -#include "ModelViewport.h" #include "FileTypeUtils.h" #include "PluginManager.h" @@ -109,14 +107,12 @@ AZ_POP_DISABLE_WARNING #include "GameEngine.h" #include "StartupTraceHandler.h" -#include "ThumbnailGenerator.h" #include "ToolsConfigPage.h" #include "Objects/SelectionGroup.h" #include "Include/IObjectManager.h" #include "WaitProgress.h" #include "ToolBox.h" -#include "Geometry/EdMesh.h" #include "LevelInfo.h" #include "EditorPreferencesDialog.h" #include "GraphicsSettingsDialog.h" @@ -392,7 +388,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_FILE_RESAVESLICES, OnFileResaveSlices) ON_COMMAND(ID_FILE_EDITEDITORINI, OnFileEditEditorini) ON_COMMAND(ID_PREFERENCES, OnPreferences) - ON_COMMAND(ID_RELOAD_GEOMETRY, OnReloadGeometry) ON_COMMAND(ID_REDO, OnRedo) ON_COMMAND(ID_TOOLBAR_WIDGET_REDO, OnRedo) ON_COMMAND(ID_RELOAD_TEXTURES, OnReloadTextures) @@ -401,7 +396,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_FILE_NEW_SLICE, OnCreateSlice) ON_COMMAND(ID_FILE_OPEN_SLICE, OnOpenSlice) #endif - ON_COMMAND(ID_RESOURCES_GENERATECGFTHUMBNAILS, OnGenerateCgfThumbnails) ON_COMMAND(ID_SWITCH_PHYSICS, OnSwitchPhysics) ON_COMMAND(ID_GAME_SYNCPLAYER, OnSyncPlayer) ON_COMMAND(ID_RESOURCES_REDUCEWORKINGSET, OnResourcesReduceworkingset) @@ -457,7 +451,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_FILE_SAVELEVELRESOURCES, OnFileSavelevelresources) ON_COMMAND(ID_CLEAR_REGISTRY, OnClearRegistryData) ON_COMMAND(ID_VALIDATELEVEL, OnValidatelevel) - ON_COMMAND(ID_TOOLS_VALIDATEOBJECTPOSITIONS, OnValidateObjectPositions) ON_COMMAND(ID_TOOLS_PREFERENCES, OnToolsPreferences) ON_COMMAND(ID_GRAPHICS_SETTINGS, OnGraphicsSettings) ON_COMMAND(ID_SWITCHCAMERA_DEFAULTCAMERA, OnSwitchToDefaultCamera) @@ -471,8 +464,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_DISPLAY_SHOWHELPERS, OnShowHelpers) ON_COMMAND(ID_OPEN_TRACKVIEW, OnOpenTrackView) ON_COMMAND(ID_OPEN_UICANVASEDITOR, OnOpenUICanvasEditor) - ON_COMMAND(ID_TERRAIN_TIMEOFDAY, OnTimeOfDay) - ON_COMMAND(ID_TERRAIN_TIMEOFDAYBUTTON, OnTimeOfDay) ON_COMMAND_RANGE(ID_GAME_PC_ENABLELOWSPEC, ID_GAME_PC_ENABLEVERYHIGHSPEC, OnChangeGameSpec) @@ -1912,11 +1903,6 @@ void CCryEditApp::LoadFile(QString fileName) { return; } - CViewport* vp = GetIEditor()->GetViewManager()->GetView(0); - if (CModelViewport* mvp = viewport_cast(vp)) - { - mvp->LoadObject(fileName, 1); - } LoadTagLocations(); @@ -2952,43 +2938,6 @@ void CCryEditApp::OnReloadTextures() GetIEditor()->GetRenderer()->EF_ReloadTextures(); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnReloadGeometry() -{ - CErrorsRecorder errRecorder(GetIEditor()); - CWaitProgress wait("Reloading static geometry"); - - CLogFile::WriteLine("Reloading Static objects geometries."); - CEdMesh::ReloadAllGeometries(); - - GetIEditor()->GetObjectManager()->SendEvent(EVENT_UNLOAD_GEOM); - - GetIEditor()->GetObjectManager()->SendEvent(EVENT_RELOAD_GEOM); - GetIEditor()->Notify(eNotify_OnReloadTrackView); - - // Rephysicalize viewport meshes - for (int i = 0; i < GetIEditor()->GetViewManager()->GetViewCount(); ++i) - { - CViewport* vp = GetIEditor()->GetViewManager()->GetView(i); - if (CModelViewport* mvp = viewport_cast(vp)) - { - mvp->RePhysicalize(); - } - } - - IRenderNode** plist = new IRenderNode*[ - gEnv->p3DEngine->GetObjectsByType(eERType_StaticMeshRenderComponent,0) - ]; - for (const EERType type : AZStd::array{eERType_Dummy_10, eERType_StaticMeshRenderComponent}) - { - for (int j = gEnv->p3DEngine->GetObjectsByType(type, plist) - 1; j >= 0; j--) - { - plist[j]->Physicalize(true); - } - } - delete[] plist; -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnUndo() { @@ -3153,15 +3102,6 @@ void CCryEditApp::OnSyncPlayerUpdate(QAction* action) action->setChecked(!GetIEditor()->GetGameEngine()->IsSyncPlayerPosition()); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnGenerateCgfThumbnails() -{ - qApp->setOverrideCursor(Qt::BusyCursor); - CThumbnailGenerator gen; - gen.GenerateForDirectory("Objects\\"); - qApp->restoreOverrideCursor(); -} - void CCryEditApp::OnUpdateNonGameMode(QAction* action) { action->setEnabled(!GetIEditor()->IsInGameMode()); @@ -3263,7 +3203,6 @@ CCryEditApp::ECreateLevelResult CCryEditApp::CreateLevel(const QString& levelNam GetIEditor()->GetGameEngine()->LoadLevel(GetIEditor()->GetGameEngine()->GetMissionName(), true, true); GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_START, 0, 0); - GetIEditor()->GetGameEngine()->ReloadEnvironment(); GetIEditor()->GetSystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_PRECACHE_END, 0, 0); } @@ -3882,119 +3821,6 @@ void CCryEditApp::OnValidatelevel() levelInfo.Validate(); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnValidateObjectPositions() -{ - IObjectManager* objMan = GetIEditor()->GetObjectManager(); - - if (!objMan) - { - return; - } - - CErrorReport errorReport; - errorReport.SetCurrentFile(""); - errorReport.SetImmediateMode(false); - - int objCount = objMan->GetObjectCount(); - AABB bbox1; - AABB bbox2; - int bugNo = 0; - QString statTxt(""); - - std::vector objects; - objMan->GetObjects(objects); - - std::vector foundObjects; - - std::vector objIDs; - - for (int i1 = 0; i1 < objCount; ++i1) - { - CBaseObject* pObj1 = objects[i1]; - - if (!pObj1) - { - continue; - } - - // Object must have geometry - if (!pObj1->GetGeometry()) - { - continue; - } - - pObj1->GetBoundBox(bbox1); - - // Check if object has other objects inside its bbox - foundObjects.clear(); - objMan->FindObjectsInAABB(bbox1, foundObjects); - - for (int i2 = 0; i2 < foundObjects.size(); ++i2) - { - CBaseObject* pObj2 = objects[i2]; - if (!pObj2) - { - continue; - } - - if (pObj2->GetId() == pObj1->GetId()) - { - continue; - } - - if (pObj2->GetParent()) - { - continue; - } - - if (stl::find(objIDs, pObj2->GetId())) - { - continue; - } - - if (!pObj2->GetGeometry()) - { - continue; - } - - pObj2->GetBoundBox(bbox2); - - if (!bbox1.IsContainPoint(bbox2.max)) - { - continue; - } - - if (!bbox1.IsContainPoint(bbox2.min)) - { - continue; - } - - objIDs.push_back(pObj2->GetId()); - - CErrorRecord error; - error.pObject = pObj2; - error.count = bugNo; - error.error = tr("%1 inside %2 object").arg(pObj2->GetName(), pObj1->GetName()); - error.description = "Object left inside other object"; - errorReport.ReportError(error); - ++bugNo; - } - - statTxt = tr("%1/%2 [Reported Objects: %3]").arg(i1).arg(objCount).arg(bugNo); - GetIEditor()->SetStatusText(statTxt); - } - - if (errorReport.GetErrorCount() == 0) - { - QMessageBox::critical(AzToolsFramework::GetActiveWindow(), QString(), QObject::tr("No Errors Found")); - } - else - { - errorReport.Display(); - } -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnToolsPreferences() { @@ -4143,12 +3969,6 @@ void CCryEditApp::OnOpenUICanvasEditor() QtViewPaneManager::instance()->OpenPane(LyViewPane::UiEditor); } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnTimeOfDay() -{ - GetIEditor()->OpenView("Time Of Day"); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::SetGameSpecCheck(ESystemConfigSpec spec, ESystemConfigPlatform platform, int &nCheck, bool &enable) { diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index 6faa167146..c0b26a9405 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -230,11 +230,9 @@ public: void OnFileEditEditorini(); void OnPreferences(); void OnReloadTextures(); - void OnReloadGeometry(); void OnRedo(); void OnUpdateRedo(QAction* action); void OnUpdateUndo(QAction* action); - void OnGenerateCgfThumbnails(); void OnSwitchPhysics(); void OnSwitchPhysicsUpdate(QAction* action); void OnSyncPlayer(); @@ -419,7 +417,6 @@ private: void OnFileSavelevelresources(); void OnClearRegistryData(); void OnValidatelevel(); - void OnValidateObjectPositions(); void OnToolsPreferences(); void OnGraphicsSettings(); void OnSwitchToDefaultCamera(); @@ -434,7 +431,6 @@ private: void OnOpenTrackView(); void OnOpenAudioControlsEditor(); void OnOpenUICanvasEditor(); - void OnTimeOfDay(); void OnChangeGameSpec(UINT nID); void SetGameSpecCheck(ESystemConfigSpec spec, ESystemConfigPlatform platform, int &nCheck, bool &enable); void OnUpdateGameSpec(QAction* action); diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 2138c5c79e..557341f28c 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -42,7 +42,6 @@ #include "Settings.h" #include "PluginManager.h" -#include "Mission.h" #include "ViewManager.h" #include "DisplaySettings.h" #include "GameEngine.h" @@ -57,7 +56,6 @@ #include "CheckOutDialog.h" #include "GameExporter.h" #include "MainWindow.h" -#include "ITimeOfDay.h" #include "LevelFileDialog.h" #include "StatObjBus.h" @@ -123,7 +121,6 @@ CCryEditDoc::CCryEditDoc() // The right way would require us to save to the level folder the export status of the // level. , m_boLevelExported(true) - , m_mission(NULL) , m_modified(false) , m_envProbeHeight(200.0f) , m_envProbeSliceRelativePath("EngineAssets/Slices/DefaultLevelSetup.slice") @@ -158,7 +155,6 @@ CCryEditDoc::CCryEditDoc() CCryEditDoc::~CCryEditDoc() { GetIEditor()->SetDocument(nullptr); - ClearMissions(); delete m_pLevelShaderCache; @@ -255,17 +251,6 @@ bool CCryEditDoc::Save() return OnSaveDocument(GetActivePathName()); } -void CCryEditDoc::ChangeMission() -{ - GetIEditor()->Notify(eNotify_OnMissionChange); - - // Notify listeners. - for (std::list::iterator it = m_listeners.begin(); it != m_listeners.end(); ++it) - { - (*it)->OnMissionChange(); - } -} - void CCryEditDoc::DeleteContents() { m_hasErrors = false; @@ -295,10 +280,6 @@ void CCryEditDoc::DeleteContents() // Delete all objects from Object Manager. GetIEditor()->GetObjectManager()->DeleteAllObjects(); - ClearMissions(); - - GetIEditor()->GetGameEngine()->ResetResources(); - // Load scripts data SetModifiedFlag(FALSE); SetModifiedModules(eModifiedNothing); @@ -341,7 +322,6 @@ void CCryEditDoc::Save(TDocMultiArchive& arrXmlAr) if (!isPrefabEnabled) { CAutoDocNotReady autoDocNotReady; - QString currentMissionName; if (arrXmlAr[DMAS_GENERAL] != NULL) { @@ -356,8 +336,6 @@ void CCryEditDoc::Save(TDocMultiArchive& arrXmlAr) // Fog settings /////////////////////////////////////////////////////// SerializeFogSettings((*arrXmlAr[DMAS_GENERAL])); - // Serialize Missions ////////////////////////////////////////////////// - SerializeMissions(arrXmlAr, currentMissionName, false); SerializeShaderCache((*arrXmlAr[DMAS_GENERAL_NAMED_DATA])); SerializeNameSelection((*arrXmlAr[DMAS_GENERAL])); @@ -404,7 +382,6 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) HEAP_CHECK CLogFile::FormatLine("Loading from %s...", szFilename.toUtf8().data()); - QString currentMissionName; QString szLevelPath = Path::GetPath(szFilename); { @@ -482,29 +459,6 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) Audio::AudioSystemRequestBus::Broadcast(&Audio::AudioSystemRequestBus::Events::PushRequestBlocking, oAudioRequestData); } - HEAP_CHECK - - if (!isPrefabEnabled) - { - // multiple missions are no longer supported, only load the current mission (last used) - SerializeMissions(arrXmlAr, currentMissionName, false); - } - - HEAP_CHECK - - if (GetIEditor()->Get3DEngine()) - { - if (!isPrefabEnabled) - { - GetIEditor()->Get3DEngine()->LoadCompiledOctreeForEditor(); - } - } - - { - CAutoLogTime logtime("Game Engine level load"); - GetIEditor()->GetGameEngine()->LoadLevel(currentMissionName, true, true); - } - if (!isPrefabEnabled) { ////////////////////////////////////////////////////////////////////////// @@ -523,27 +477,6 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) SerializeFogSettings((*arrXmlAr[DMAS_GENERAL])); } - { - QByteArray str; - str = tr("Activating Mission %1").arg(currentMissionName).toUtf8(); - - CAutoLogTime logtime(str.data()); - - // Select current mission. - m_mission = FindMission(currentMissionName); - - if (m_mission) - { - SyncCurrentMissionContent(true); - } - else - { - GetCurrentMission(); - } - } - - ForceSkyUpdate(); - if (!isPrefabEnabled) { // Serialize Shader Cache. @@ -730,94 +663,6 @@ void CCryEditDoc::SerializeFogSettings(CXmlArchive& xmlAr) } } -void CCryEditDoc::SerializeMissions(TDocMultiArchive& arrXmlAr, QString& currentMissionName, bool bPartsInXml) -{ - bool bLoading = IsLoadingXmlArArray(arrXmlAr); - - if (bLoading) - { - // Loading - CLogFile::WriteLine("Loading missions..."); - // Clear old layers - ClearMissions(); - // Load shared objects and layers. - XmlNodeRef objectsNode = arrXmlAr[DMAS_GENERAL]->root->findChild("Objects"); - XmlNodeRef objectLayersNode = arrXmlAr[DMAS_GENERAL]->root->findChild("ObjectLayers"); - // Load the layer count - XmlNodeRef node = arrXmlAr[DMAS_GENERAL]->root->findChild("Missions"); - - if (!node) - { - return; - } - - QString current; - node->getAttr("Current", current); - currentMissionName = current; - - // Read all node - for (int i = 0; i < node->getChildCount(); i++) - { - CXmlArchive ar(*arrXmlAr[DMAS_GENERAL]); - ar.root = node->getChild(i); - CMission* mission = new CMission(this); - mission->Serialize(ar); - if (bPartsInXml) - { - mission->SerializeTimeOfDay(*arrXmlAr[DMAS_TIME_OF_DAY]); - mission->SerializeEnvironment(*arrXmlAr[DMAS_ENVIRONMENT]); - } - else - { - mission->LoadParts(); - } - - // Timur[9/11/2002] For backward compatibility with shared objects - if (objectsNode) - { - mission->AddObjectsNode(objectsNode); - } - if (objectLayersNode) - { - mission->SetLayersNode(objectLayersNode); - } - - AddMission(mission); - } - } - else - { - // Storing - CLogFile::WriteLine("Storing missions..."); - // Save contents of current mission. - SyncCurrentMissionContent(false); - - XmlNodeRef node = arrXmlAr[DMAS_GENERAL]->root->newChild("Missions"); - - //! Store current mission name. - currentMissionName = GetCurrentMission()->GetName(); - node->setAttr("Current", currentMissionName.toUtf8().data()); - - // Write all surface types. - for (int i = 0; i < m_missions.size(); i++) - { - CXmlArchive ar(*arrXmlAr[DMAS_GENERAL]); - ar.root = node->newChild("Mission"); - m_missions[i]->Serialize(ar, false); - if (bPartsInXml) - { - m_missions[i]->SerializeTimeOfDay(*arrXmlAr[DMAS_TIME_OF_DAY]); - m_missions[i]->SerializeEnvironment(*arrXmlAr[DMAS_ENVIRONMENT]); - } - else - { - m_missions[i]->SaveParts(); - } - } - CLogFile::WriteString("Done"); - } -} - void CCryEditDoc::SerializeShaderCache(CXmlArchive& xmlAr) { if (xmlAr.bLoading) @@ -2089,58 +1934,6 @@ void CCryEditDoc::SaveAutoBackup(bool bForce) isInProgress = false; } - -CMission* CCryEditDoc::GetCurrentMission(bool bSkipLoadingAIWhenSyncingContent /* = false */) -{ - if (m_mission) - { - return m_mission; - } - - if (!m_missions.empty()) - { - // Choose first available mission. - SetCurrentMission(m_missions[0]); - return m_mission; - } - - // Create initial mission. - m_mission = new CMission(this); - m_mission->SetName("Mission0"); - AddMission(m_mission); - m_mission->SyncContent(true, false, bSkipLoadingAIWhenSyncingContent); - return m_mission; -} - -void CCryEditDoc::SetCurrentMission(CMission* mission) -{ - if (mission != m_mission) - { - QWaitCursor wait; - - if (m_mission) - { - m_mission->SyncContent(false, false); - } - - m_mission = mission; - m_mission->SyncContent(true, false); - - GetIEditor()->GetGameEngine()->LoadMission(m_mission->GetName()); - } -} - -void CCryEditDoc::ClearMissions() -{ - for (int i = 0; i < m_missions.size(); i++) - { - delete m_missions[i]; - } - - m_missions.clear(); - m_mission = 0; -} - bool CCryEditDoc::IsLevelExported() const { return m_boLevelExported; @@ -2151,37 +1944,6 @@ void CCryEditDoc::SetLevelExported(bool boExported) m_boLevelExported = boExported; } -CMission* CCryEditDoc::FindMission(const QString& name) const -{ - for (int i = 0; i < m_missions.size(); i++) - { - if (QString::compare(name, m_missions[i]->GetName(), Qt::CaseInsensitive) == 0) - { - return m_missions[i]; - } - } - return 0; -} - -void CCryEditDoc::AddMission(CMission* mission) -{ - assert(std::find(m_missions.begin(), m_missions.end(), mission) == m_missions.end()); - m_missions.push_back(mission); - GetIEditor()->Notify(eNotify_OnInvalidateControls); -} - -void CCryEditDoc::RemoveMission(CMission* mission) -{ - // if deleting current mission. - if (mission == m_mission) - { - m_mission = 0; - } - - m_missions.erase(std::find(m_missions.begin(), m_missions.end(), mission)); - GetIEditor()->Notify(eNotify_OnInvalidateControls); -} - void CCryEditDoc::RegisterListener(IDocListener* listener) { if (listener == nullptr) @@ -2287,19 +2049,6 @@ void CCryEditDoc::OnStartLevelResourceList() gEnv->pCryPak->GetResourceList(AZ::IO::IArchive::RFOM_Level)->Clear(); } -void CCryEditDoc::ForceSkyUpdate() -{ - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine ? gEnv->p3DEngine->GetTimeOfDay() : nullptr; - CMission* pCurMission = GetIEditor()->GetDocument()->GetCurrentMission(); - - if (pTimeOfDay && pCurMission) - { - pTimeOfDay->SetTime(pCurMission->GetTime(), gSettings.bForceSkyUpdate); - pCurMission->SetTime(pCurMission->GetTime()); - GetIEditor()->Notify(eNotify_OnTimeOfDayChange); - } -} - BOOL CCryEditDoc::DoFileSave() { if (GetEditMode() == CCryEditDoc::DocumentEditingMode::LevelEdit) @@ -2361,27 +2110,11 @@ void CCryEditDoc::InitEmptyLevel(int /*resolution*/, int /*unitSize*/, bool /*bU ////////////////////////////////////////////////////////////////////////// if (!GetIEditor()->IsInPreviewMode()) { - // Make new mission. GetIEditor()->ReloadTemplates(); m_environmentTemplate = GetIEditor()->FindTemplate("Environment"); - GetCurrentMission(true); // true = skip loading the AI in case the content needs to get synchronized (otherwise it would attempt to load AI stuff from the previously loaded level (!) which might give confusing warnings) - GetIEditor()->GetGameEngine()->SetMissionName(GetCurrentMission()->GetName()); GetIEditor()->GetGameEngine()->SetLevelCreated(true); - GetIEditor()->GetGameEngine()->ReloadEnvironment(); GetIEditor()->GetGameEngine()->SetLevelCreated(false); - - // Default time of day. - auto defaultTimeOfDayPath = AZ::IO::FixedMaxPath(AZ::Utils::GetEnginePath()) / "Assets" / "Editor" / "default_time_of_day.xml"; - XmlNodeRef root = GetISystem()->LoadXmlFromFile(defaultTimeOfDayPath.c_str()); - if (root) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine ? gEnv->p3DEngine->GetTimeOfDay() : nullptr; - if (pTimeOfDay) - { - pTimeOfDay->Serialize(root, true); - } - } } { @@ -2469,8 +2202,6 @@ void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) pVar->Get(value); childNode->setAttr("value", value.toUtf8().data()); } - - GetIEditor()->GetGameEngine()->ReloadEnvironment(); } QString CCryEditDoc::GetCryIndexPath(const LPCTSTR levelFilePath) @@ -2523,12 +2254,6 @@ void CCryEditDoc::ReleaseXmlArchiveArray(TDocMultiArchive& arrXmlAr) SAFE_DELETE(arrXmlAr[0]); } - -void CCryEditDoc::SyncCurrentMissionContent(bool bRetrieve) -{ - GetCurrentMission()->SyncContent(bRetrieve, false); -} - ////////////////////////////////////////////////////////////////////////// // AzToolsFramework::EditorEntityContextNotificationBus interface implementation void CCryEditDoc::OnSliceInstantiated(const AZ::Data::AssetId& sliceAssetId, AZ::SliceComponent::SliceInstanceAddress& sliceAddress, const AzFramework::SliceInstantiationTicket& /*ticket*/) diff --git a/Code/Sandbox/Editor/CryEditDoc.h b/Code/Sandbox/Editor/CryEditDoc.h index 481e9fa046..be8a5fcec7 100644 --- a/Code/Sandbox/Editor/CryEditDoc.h +++ b/Code/Sandbox/Editor/CryEditDoc.h @@ -22,7 +22,6 @@ #include #endif -class CMission; class CLevelShaderCache; class CClouds; struct LightingSettings; @@ -124,18 +123,6 @@ public: // Create from serialization only const char* GetTemporaryLevelName() const; void DeleteTemporaryLevel(); - void ChangeMission(); - //! Return currently active Mission. - CMission* GetCurrentMission(bool bSkipLoadingAIWhenSyncingContent = false); - //! Get number of missions on Map. - int GetMissionCount() const { return m_missions.size(); } - //! Get Mission by index. - CMission* GetMission(int index) const { return m_missions[index]; } - //! Find Mission by name. - CMission* FindMission(const QString& name) const; - //! Makes specified mission current. - void SetCurrentMission(CMission* mission); - CLevelShaderCache* GetShaderCache() { return m_pLevelShaderCache; } CClouds* GetClouds() { return m_pClouds; } void SetWaterColor(const QColor& col) { m_waterColor = col; } @@ -167,7 +154,6 @@ protected: virtual void Load(TDocMultiArchive& arrXmlAr, const QString& szFilename); virtual void StartStreamingLoad(){} - virtual void SyncCurrentMissionContent(bool bRetrieve); void Save(CXmlArchive& xmlAr); void Load(CXmlArchive& xmlAr, const QString& szFilename); @@ -179,14 +165,8 @@ protected: bool LoadEntitiesFromSlice(const QString& sliceFile); void SerializeFogSettings(CXmlArchive& xmlAr); virtual void SerializeViewSettings(CXmlArchive& xmlAr); - void SerializeMissions(TDocMultiArchive& arrXmlAr, QString& currentMission, bool bPartsInXml); void SerializeShaderCache(CXmlArchive& xmlAr); void SerializeNameSelection(CXmlArchive& xmlAr); - void ForceSkyUpdate(); - //! Add new mission to map. - void AddMission(CMission* mission); - //! Remove existing mission from map. - void RemoveMission(CMission* mission); void LogLoadTime(int time); struct TSaveDocContext @@ -200,10 +180,8 @@ protected: virtual bool OnSaveDocument(const QString& lpszPathName); virtual void OnFileSaveAs(); - void LoadTemplates(); //! called immediately after saving the level. void AfterSave(); - void ClearMissions(); void RegisterConsoleVariables(); void OnStartLevelResourceList(); static void OnValidateSurfaceTypesChanged(ICVar*); @@ -220,9 +198,7 @@ protected: QColor m_waterColor; XmlNodeRef m_fogTemplate; XmlNodeRef m_environmentTemplate; - CMission* m_mission; CClouds* m_pClouds; - std::vector m_missions; std::list m_listeners; bool m_bDocumentReady; CLevelShaderCache* m_pLevelShaderCache; diff --git a/Code/Sandbox/Editor/DisplaySettings.cpp b/Code/Sandbox/Editor/DisplaySettings.cpp index 75e5c54ae9..6454471a80 100644 --- a/Code/Sandbox/Editor/DisplaySettings.cpp +++ b/Code/Sandbox/Editor/DisplaySettings.cpp @@ -86,11 +86,6 @@ void CDisplaySettings::PostInitApply() void CDisplaySettings::SetRenderFlags(int flags) { m_renderFlags = flags; - - if (!GetIEditor()->Get3DEngine()) - { - return; - } } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/EditorDefs.h b/Code/Sandbox/Editor/EditorDefs.h index dd86bdf07a..8c78e9644f 100644 --- a/Code/Sandbox/Editor/EditorDefs.h +++ b/Code/Sandbox/Editor/EditorDefs.h @@ -132,7 +132,6 @@ #include #include #include -#include #include #include #include diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 05986d6561..61cfea0894 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -54,7 +54,6 @@ #include // CryCommon -#include #include // AzFramework @@ -97,6 +96,10 @@ #include +#include +#include +#include + AZ_CVAR( bool, ed_visibility_logTiming, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Output the timing of the new IVisibilitySystem query"); @@ -250,11 +253,6 @@ void EditorViewportWidget::resizeEvent(QResizeEvent* event) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, width(), height()); - if (gEnv->pRenderer) - { - gEnv->pRenderer->EF_DisableTemporalEffects(); - } - // We queue the window resize event because the render overlay may be hidden. // If the render overlay is not visible, the native window that is backing it will // also be hidden, and it will not resize until it becomes visible. @@ -520,9 +518,6 @@ void EditorViewportWidget::Update() // Render { // TODO: Move out this logic to a controller and refactor to work with Atom - // m_renderer->SetClearColor(Vec3(0.4f, 0.4f, 0.4f)); - // 3D engine stats - GetIEditor()->GetSystem()->RenderBegin(); OnRender(); @@ -547,8 +542,6 @@ void EditorViewportWidget::Update() } } - GetIEditor()->GetSystem()->RenderEnd(m_bRenderStats); - gEnv->pSystem->SetViewCamera(CurCamera); } @@ -1556,7 +1549,6 @@ void EditorViewportWidget::ToggleCameraObject() { if (m_viewSourceType == ViewSourceType::SequenceCamera) { - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); ResetToViewSourceType(ViewSourceType::LegacyCamera); } else @@ -2136,17 +2128,23 @@ bool EditorViewportWidget::AdjustObjectPosition(const ray_hit& hit, Vec3& outNor ////////////////////////////////////////////////////////////////////////// bool EditorViewportWidget::RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal) const { - SRayHitInfo hitInfo; + AZ_UNUSED(pRenderMesh); + AZ_UNUSED(vInPos); + AZ_UNUSED(vInDir); + AZ_UNUSED(vOutPos); + AZ_UNUSED(vOutNormal); + return false; + /*SRayHitInfo hitInfo; hitInfo.bUseCache = false; hitInfo.bInFirstHit = false; hitInfo.inRay.origin = vInPos; hitInfo.inRay.direction = vInDir.GetNormalized(); hitInfo.inReferencePoint = vInPos; hitInfo.fMaxHitDistance = 0; - bool bRes = GetIEditor()->Get3DEngine()->RenderMeshRayIntersection(pRenderMesh, hitInfo, nullptr); + bool bRes = ???->RenderMeshRayIntersection(pRenderMesh, hitInfo, nullptr); vOutPos = hitInfo.vHitPos; vOutNormal = hitInfo.vHitNormal; - return bRes; + return bRes;*/ } void EditorViewportWidget::UnProjectFromScreen(float sx, float sy, float sz, float* px, float* py, float* pz) const @@ -2417,10 +2415,6 @@ void EditorViewportWidget::SetDefaultCamera() return; } ResetToViewSourceType(ViewSourceType::None); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); - } GetViewManager()->SetCameraObjectId(m_cameraObjectId); SetName(m_defaultViewName); SetViewTM(m_defaultViewTM); diff --git a/Code/Sandbox/Editor/EditorViewportWidget.h b/Code/Sandbox/Editor/EditorViewportWidget.h index 8673d258cc..09474200f1 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.h +++ b/Code/Sandbox/Editor/EditorViewportWidget.h @@ -481,10 +481,6 @@ protected: OBB m_GroundOBB; Vec3 m_GroundOBBPos; - //------------------------------------------- - // Render options. - bool m_bRenderStats = true; - // Index of camera objects. mutable GUID m_cameraObjectId; mutable AZ::EntityId m_viewEntityId; diff --git a/Code/Sandbox/Editor/EnvironmentPanel.cpp b/Code/Sandbox/Editor/EnvironmentPanel.cpp deleted file mode 100644 index f71babbff6..0000000000 --- a/Code/Sandbox/Editor/EnvironmentPanel.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "EnvironmentPanel.h" - -// Editor -#include "GameEngine.h" -#include "CryEditDoc.h" - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -///////////////////////////////////////////////////////////////////////////// -// CEnvironmentPanel dialog - -CEnvironmentPanel::CEnvironmentPanel(QWidget* pParent /*=nullptr*/) - : QWidget(pParent) - , ui(new Ui::CEnvironmentPanel) -{ - XmlNodeRef node = GetIEditor()->GetDocument()->GetEnvironmentTemplate(); - - m_onSetCallback = AZStd::bind(&CCryEditDoc::OnEnvironmentPropertyChanged, GetIEditor()->GetDocument(), AZStd::placeholders::_1); - - ui->setupUi(this); - ui->m_wndProps->Setup(); - ui->m_wndProps->CreateItems(node, m_varBlock, &m_onSetCallback, true); - ui->m_wndProps->RebuildCtrl(false); - ui->m_wndProps->ExpandAll(); - connect(ui->APPLYBTN, &QPushButton::clicked, this, &CEnvironmentPanel::OnBnClickedApply); -} - -CEnvironmentPanel::~CEnvironmentPanel() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CEnvironmentPanel::OnBnClickedApply() -{ - GetIEditor()->GetGameEngine()->ReloadEnvironment(); -} diff --git a/Code/Sandbox/Editor/EnvironmentPanel.h b/Code/Sandbox/Editor/EnvironmentPanel.h deleted file mode 100644 index ff4594a502..0000000000 --- a/Code/Sandbox/Editor/EnvironmentPanel.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_ENVIRONMENTPANEL_H -#define CRYINCLUDE_EDITOR_ENVIRONMENTPANEL_H - -#pragma once -// EnvironmentPanel.h : header file -// - -#include "Util/Variable.h" - -#include -#include - -///////////////////////////////////////////////////////////////////////////// -// CEnvironmentPanel dialog -namespace Ui { - class CEnvironmentPanel; -} - -class CEnvironmentPanel - : public QWidget -{ - // Construction -public: - CEnvironmentPanel(QWidget* pParent = nullptr); // standard constructor - ~CEnvironmentPanel(); - - // Implementation -protected: - CVarBlockPtr m_varBlock; - -public: - void OnBnClickedApply(); - -private: - QScopedPointer ui; - - IVariable::OnSetCallback m_onSetCallback; -}; - -#endif // CRYINCLUDE_EDITOR_ENVIRONMENTPANEL_H diff --git a/Code/Sandbox/Editor/EnvironmentPanel.ui b/Code/Sandbox/Editor/EnvironmentPanel.ui deleted file mode 100644 index b808fc93fc..0000000000 --- a/Code/Sandbox/Editor/EnvironmentPanel.ui +++ /dev/null @@ -1,56 +0,0 @@ - - - CEnvironmentPanel - - - - 0 - 0 - 264 - 259 - - - - - - - - 0 - 200 - - - - - - - - Apply - - - - - - - Qt::Horizontal - - - - 162 - 20 - - - - - - - - - ReflectedPropertyControl - QWidget -
Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.h
- 1 -
-
- - -
diff --git a/Code/Sandbox/Editor/Export/ExportManager.cpp b/Code/Sandbox/Editor/Export/ExportManager.cpp index ddb8a38870..2d0f784647 100644 --- a/Code/Sandbox/Editor/Export/ExportManager.cpp +++ b/Code/Sandbox/Editor/Export/ExportManager.cpp @@ -22,7 +22,6 @@ #include // Editor -#include "Geometry/EdGeometry.h" #include "ViewManager.h" #include "OBJExporter.h" #include "OCMExporter.h" @@ -41,6 +40,9 @@ #include "Resource.h" #include "Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h" +#include +#include + namespace { void SetTexture(Export::TPath& outName, IRenderShaderResources* pRes, int nSlot) @@ -494,53 +496,6 @@ bool CExportManager::AddStatObj(Export::CObject* pObj, IStatObj* pStatObj, Matri bool CExportManager::AddMeshes(Export::CObject* pObj) { - CEdGeometry* pEdGeom = m_pBaseObj->GetGeometry(); - IIndexedMesh* pIndMesh = 0; - - if (pEdGeom) - { - size_t idx = 0; - size_t nextIdx = 0; - do - { - pIndMesh = 0; - if (m_isOccluder) - { - if (pEdGeom->GetIStatObj() && pEdGeom->GetIStatObj()->GetLodObject(2)) - { - pIndMesh = pEdGeom->GetIStatObj()->GetLodObject(2)->GetIndexedMesh(true); - } - if (!pIndMesh && pEdGeom->GetIStatObj() && pEdGeom->GetIStatObj()->GetLodObject(1)) - { - pIndMesh = pEdGeom->GetIStatObj()->GetLodObject(1)->GetIndexedMesh(true); - } - } - - if (!pIndMesh) - { - pIndMesh = pEdGeom->GetIndexedMesh(idx); - nextIdx++; - } - - if (!pIndMesh) - { - break; - } - - Matrix34 tm; - pEdGeom->GetTM(&tm, idx); - Matrix34A objTM = tm; - AddMesh(pObj, pIndMesh, &objTM); - idx = nextIdx; - } - while (pIndMesh && idx); - - if (idx > 0) - { - return true; - } - } - if (m_pBaseObj->GetType() == OBJTYPE_AZENTITY) { CEntityObject* pEntityObject = (CEntityObject*)m_pBaseObj; @@ -548,11 +503,7 @@ bool CExportManager::AddMeshes(Export::CObject* pObj) if (pEngineNode) { - if (m_isPrecaching) - { - GetIEditor()->Get3DEngine()->PrecacheRenderNode(pEngineNode, 0); - } - else + if (!m_isPrecaching) { for (int i = 0; i < pEngineNode->GetSlotCount(); ++i) { @@ -1115,8 +1066,6 @@ bool CExportManager::AddSelectedRegionObjects() AddObject(objects[i]); } - GetIEditor()->Get3DEngine()->ProposeContentPrecache(); - // Repeat pipeline to collect geometry m_isPrecaching = false; for (size_t i = 0; i < numObjects; ++i) diff --git a/Code/Sandbox/Editor/GameEngine.cpp b/Code/Sandbox/Editor/GameEngine.cpp index d5aec9e7d4..6c1bef7a68 100644 --- a/Code/Sandbox/Editor/GameEngine.cpp +++ b/Code/Sandbox/Editor/GameEngine.cpp @@ -34,15 +34,11 @@ // Editor #include "IEditorImpl.h" #include "CryEditDoc.h" -#include "Geometry/EdMesh.h" -#include "Mission.h" #include "Settings.h" // CryCommon -#include #include #include -#include #include #include @@ -283,7 +279,6 @@ AZ_POP_DISABLE_WARNING AZ::Interface::Unregister(this); GetIEditor()->UnregisterNotifyListener(this); m_pISystem->GetIMovieSystem()->SetCallback(NULL); - CEdMesh::ReleaseAll(); if (m_gameDll) { @@ -493,13 +488,6 @@ AZ::Outcome CGameEngine::Init( SetEditorCoreEnvironment(gEnv); - if (gEnv - && gEnv->p3DEngine - && gEnv->p3DEngine->GetTimeOfDay()) - { - gEnv->p3DEngine->GetTimeOfDay()->BeginEditMode(); - } - if (gEnv && gEnv->pMovieSystem) { gEnv->pMovieSystem->EnablePhysicsEvents(m_bSimulationMode); @@ -549,11 +537,6 @@ void CGameEngine::SetLevelPath(const QString& path) { m_levelExtension = defaultExtension; } - - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->SetLevelPath(m_levelPath.toUtf8().data()); - } } void CGameEngine::SetMissionName(const QString& mission) @@ -607,24 +590,11 @@ bool CGameEngine::LoadLevel( } - // Load level in 3d engine. - if (gEnv->p3DEngine && !gEnv->p3DEngine->InitLevelForEditor(m_levelPath.toUtf8().data(), m_missionName.toUtf8().data())) - { - CLogFile::WriteLine("ERROR: Can't load level !"); - QMessageBox::critical(QApplication::activeWindow(), QString(), QObject::tr("ERROR: Can't load level !")); - return false; - } - // Audio: notify audio of level loading start? GetIEditor()->GetObjectManager()->SendEvent(EVENT_REFRESH); m_bLevelLoaded = true; - if (!bReleaseResources) - { - ReloadEnvironment(); - } - return true; } @@ -638,61 +608,8 @@ bool CGameEngine::ReloadLevel() return true; } -bool CGameEngine::LoadMission(const QString& mission) -{ - if (!IsLevelLoaded()) - { - return false; - } - - if (mission != m_missionName) - { - m_missionName = mission; - gEnv->p3DEngine->LoadMissionDataFromXMLNode(m_missionName.toUtf8().data()); - } - - return true; -} - -bool CGameEngine::ReloadEnvironment() -{ - if (!gEnv->p3DEngine) - { - return false; - } - - if (!IsLevelLoaded() && !m_bJustCreated) - { - return false; - } - - if (!GetIEditor()->GetDocument()) - { - return false; - } - - XmlNodeRef env = XmlHelpers::CreateXmlNode("Environment"); - CXmlTemplate::SetValues(GetIEditor()->GetDocument()->GetEnvironmentTemplate(), env); - - // Notify mission that environment may be changed. - GetIEditor()->GetDocument()->GetCurrentMission()->OnEnvironmentChange(); - - QString xmlStr = QString::fromLatin1(env->getXML()); - - // Reload level data in engine. - gEnv->p3DEngine->LoadEnvironmentSettingsFromXML(env); - - return true; -} - void CGameEngine::SwitchToInGame() { - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->DisablePostEffects(); - gEnv->p3DEngine->ResetPostEffects(); - } - auto streamer = AZ::Interface::Get(); if (streamer) { @@ -707,11 +624,6 @@ void CGameEngine::SwitchToInGame() m_pISystem->SetThreadState(ESubsys_Physics, false); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->ResetParticlesAndDecals(); - } - m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(true); m_bInGameMode = true; @@ -721,10 +633,6 @@ void CGameEngine::SwitchToInGame() pRuler->SetActive(false); } - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetTimeOfDay()->EndEditMode(); - } gEnv->pSystem->GetViewCamera().SetMatrix(m_playerViewTM); // Disable accelerators. @@ -760,24 +668,9 @@ void CGameEngine::SwitchToInEditor() m_pISystem->SetThreadState(ESubsys_Physics, false); - if (gEnv->p3DEngine) - { - // Reset 3d engine effects - gEnv->p3DEngine->DisablePostEffects(); - gEnv->p3DEngine->ResetPostEffects(); - gEnv->p3DEngine->ResetParticlesAndDecals(); - } - CViewport* pGameViewport = GetIEditor()->GetViewManager()->GetGameViewport(); m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(m_bSimulationMode); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetTimeOfDay()->BeginEditMode(); - - // this has to be done before the RemoveSink() call, or else some entities may not be removed - gEnv->p3DEngine->GetDeferredPhysicsEventManager()->ClearDeferredEvents(); - } // Enable accelerators. GetIEditor()->EnableAcceleratos(true); @@ -865,7 +758,6 @@ void CGameEngine::SetGameMode(bool bInGame) // Ignore updates while changing in and out of game mode m_bIgnoreUpdates = true; - LockResources(); // Switching modes will destroy the current AzFramework::EntityConext which may contain // data the queued events hold on to, so execute all queued events before switching. @@ -891,7 +783,6 @@ void CGameEngine::SetGameMode(bool bInGame) GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_EDITOR_GAME_MODE_CHANGED, bInGame, 0); - UnlockResources(); m_bIgnoreUpdates = false; GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_GAME_MODE_SWITCH_END, bInGame, 0); @@ -906,11 +797,6 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) m_pISystem->GetIMovieSystem()->EnablePhysicsEvents(enabled); - if (!bOnlyPhysics) - { - LockResources(); - } - if (enabled) { CRuler* pRuler = GetIEditor()->GetRuler(); @@ -935,35 +821,12 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) if (m_bSimulationMode) { - if (!bOnlyPhysics) - { - if (m_pISystem->GetI3DEngine()) - { - m_pISystem->GetI3DEngine()->ResetPostEffects(); - } - - GetIEditor()->SetConsoleVar("ai_ignoreplayer", 1); - //GetIEditor()->SetConsoleVar( "ai_soundperception",0 ); - } - // [Anton] the order of the next 3 calls changed, since, EVENT_INGAME loads physics state (if any), // and Reset should be called before it GetIEditor()->GetObjectManager()->SendEvent(EVENT_INGAME); } else { - if (!bOnlyPhysics) - { - GetIEditor()->SetConsoleVar("ai_ignoreplayer", 0); - //GetIEditor()->SetConsoleVar( "ai_soundperception",1 ); - - if (m_pISystem->GetI3DEngine()) - { - m_pISystem->GetI3DEngine()->ResetPostEffects(); - } - } - - GetIEditor()->GetObjectManager()->SendEvent(EVENT_OUTOFGAME); } @@ -983,23 +846,9 @@ void CGameEngine::SetSimulationMode(bool enabled, bool bOnlyPhysics) AzToolsFramework::EditorEntityContextRequestBus::Broadcast(&AzToolsFramework::EditorEntityContextRequestBus::Events::StartPlayInEditor); } - if (!bOnlyPhysics) - { - UnlockResources(); - } - AzFramework::InputChannelRequestBus::Broadcast(&AzFramework::InputChannelRequests::ResetState); } -void CGameEngine::ResetResources() -{ - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->UnloadLevel(); - } - -} - void CGameEngine::SetPlayerViewMatrix(const Matrix34& tm, [[maybe_unused]] bool bEyePos) { m_playerViewTM = tm; @@ -1107,24 +956,6 @@ void CGameEngine::OnEditorNotifyEvent(EEditorNotifyEvent event) { switch (event) { - case eNotify_OnBeginNewScene: - case eNotify_OnBeginSceneOpen: - { - ResetResources(); - } - break; - case eNotify_OnEndSceneOpen: - case eNotify_OnEndTerrainRebuild: - { - } - case eNotify_OnEndNewScene: // intentional fall-through? - { - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->PostLoadLevel(); - } - } - break; case eNotify_OnSplashScreenDestroyed: { if (m_pSystemUserCallback != NULL) @@ -1136,22 +967,6 @@ void CGameEngine::OnEditorNotifyEvent(EEditorNotifyEvent event) } } -void CGameEngine::LockResources() -{ - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->LockCGFResources(); - } -} - -void CGameEngine::UnlockResources() -{ - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->UnlockCGFResources(); - } -} - void CGameEngine::OnTerrainModified(const Vec2& modPosition, float modAreaRadius, bool fullTerrain) { INavigationSystem* pNavigationSystem = nullptr; // INavigationSystem will be converted to an AZInterface (LY-111343) diff --git a/Code/Sandbox/Editor/GameEngine.h b/Code/Sandbox/Editor/GameEngine.h index 366ec42f72..c660f971f2 100644 --- a/Code/Sandbox/Editor/GameEngine.h +++ b/Code/Sandbox/Editor/GameEngine.h @@ -94,10 +94,6 @@ public: bool bReleaseResources); //!* Reload level if it was already loaded. bool ReloadLevel(); - //! Load new mission. - bool LoadMission(const QString& mission); - //! Reload environment settings in currently loaded level. - bool ReloadEnvironment(); //! Request to switch In/Out of game mode on next update. //! The switch will happen when no sub systems are currently being updated. //! @param inGame When true editor switch to game mode. @@ -142,9 +138,6 @@ public: //! Called every frame. void Update(); virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - void LockResources(); - void UnlockResources(); - void ResetResources(); void OnTerrainModified(const Vec2& modPosition, float modAreaRadius, bool fullTerrain); void OnAreaModified(const AABB& modifiedArea); diff --git a/Code/Sandbox/Editor/GameExporter.cpp b/Code/Sandbox/Editor/GameExporter.cpp index 64e1fc6514..31f3fafe84 100644 --- a/Code/Sandbox/Editor/GameExporter.cpp +++ b/Code/Sandbox/Editor/GameExporter.cpp @@ -24,7 +24,6 @@ #include "GameExporter.h" #include "GameEngine.h" #include "CryEditDoc.h" -#include "Mission.h" #include "ShaderCache.h" #include "UsedResources.h" #include "WaitProgress.h" @@ -131,13 +130,6 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE m_levelPath = Path::RemoveBackslash(sLevelPath); QString rootLevelPath = Path::AddSlash(pGameEngine->GetLevelPath()); - // Make sure we unload any unused CGFs before exporting so that they don't end up in - // the level data. - if (pEditor->Get3DEngine()) - { - pEditor->Get3DEngine()->FreeUnusedCGFResources(); - } - CCryEditDoc* pDocument = pEditor->GetDocument(); if (flags & eExp_Fast) @@ -191,8 +183,6 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE //////////////////////////////////////////////////////////////////////// if (exportSuccessful) { - ExportVisAreas(sLevelPath.toUtf8().data(), eExportEndian); - //////////////////////////////////////////////////////////////////////// // Exporting map setttings //////////////////////////////////////////////////////////////////////// @@ -254,47 +244,6 @@ bool CGameExporter::Export(unsigned int flags, [[maybe_unused]] EEndian eExportE return exportSuccessful; } - -////////////////////////////////////////////////////////////////////////// -void CGameExporter::ExportVisAreas(const char* pszGamePath, EEndian eExportEndian) -{ - char szFileOutputPath[_MAX_PATH]; - - // export visareas - IEditor* pEditor = GetIEditor(); - - // remove old files - sprintf_s(szFileOutputPath, "%s%s", pszGamePath, COMPILED_VISAREA_MAP_FILE_NAME); - m_levelPak.m_pakFile.RemoveFile(szFileOutputPath); - - SHotUpdateInfo exportInfo; - I3DEngine* p3DEngine = pEditor->Get3DEngine(); - - if (p3DEngine && (eExportEndian == GetPlatformEndian())) // skip second export, this data is common for PC and consoles - { - std::vector* pTempBrushTable = NULL; - std::vector<_smart_ptr>* pTempMatsTable = NULL; - std::vector* pTempVegGroupTable = NULL; - - // export visareas - CLogFile::WriteLine("Exporting indoors..."); - pEditor->SetStatusText("Exporting indoors..."); - if (IVisAreaManager* pVisAreaManager = p3DEngine->GetIVisAreaManager()) - { - if (int nSize = pVisAreaManager->GetCompiledDataSize()) - { // get visareas data from 3dengine and save it into file - uint8* pData = new uint8[nSize]; - pVisAreaManager->GetCompiledData(pData, nSize, &pTempBrushTable, &pTempMatsTable, &pTempVegGroupTable, eExportEndian); - sprintf_s(szFileOutputPath, "%s%s", pszGamePath, COMPILED_VISAREA_MAP_FILE_NAME); - CCryMemFile visareasCompiledFile; - visareasCompiledFile.Write(pData, nSize); - m_levelPak.m_pakFile.UpdateFile(szFileOutputPath, visareasCompiledFile); - delete[] pData; - } - } - } -} - ////////////////////////////////////////////////////////////////////////// void CGameExporter::ExportOcclusionMesh(const char* pszGamePath) { @@ -319,7 +268,7 @@ void CGameExporter::ExportOcclusionMesh(const char* pszGamePath) } ////////////////////////////////////////////////////////////////////////// -void CGameExporter::ExportLevelData(const QString& path, bool bExportMission) +void CGameExporter::ExportLevelData(const QString& path, bool /*bExportMission*/) { IEditor* pEditor = GetIEditor(); pEditor->SetStatusText(QObject::tr("Exporting LevelData.xml...")); @@ -332,49 +281,6 @@ void CGameExporter::ExportLevelData(const QString& path, bool bExportMission) XmlNodeRef rootAction = XmlHelpers::CreateXmlNode("LevelDataAction"); rootAction->setAttr("SandboxVersion", versionString); - ExportMapInfo(root); - - CCryEditDoc* pDocument = pEditor->GetDocument(); - CMission* pCurrentMission = 0; - - if (bExportMission) - { - pCurrentMission = pDocument->GetCurrentMission(); - // Save contents of current mission. - } - - ////////////////////////////////////////////////////////////////////////// - // Export missions tag. - ////////////////////////////////////////////////////////////////////////// - XmlNodeRef missionsNode = rootAction->newChild("Missions"); - QString missionFileName; - QString currentMissionFileName; - I3DEngine* p3DEngine = pEditor->Get3DEngine(); - if (p3DEngine) - { - for (int i = 0; i < pDocument->GetMissionCount(); i++) - { - CMission* pMission = pDocument->GetMission(i); - - QString name = pMission->GetName(); - name.replace(' ', '_'); - missionFileName = QStringLiteral("Mission_%1.xml").arg(name); - - XmlNodeRef missionDescNode = missionsNode->newChild("Mission"); - missionDescNode->setAttr("Name", pMission->GetName().toUtf8().data()); - missionDescNode->setAttr("File", missionFileName.toUtf8().data()); - missionDescNode->setAttr("CGFCount", p3DEngine->GetLoadedObjectCount()); - - int nProgressBarRange = m_numExportedMaterials / 10 + p3DEngine->GetLoadedObjectCount(); - missionDescNode->setAttr("ProgressBarRange", nProgressBarRange); - - if (pMission == pCurrentMission) - { - currentMissionFileName = missionFileName; - } - } - } - ////////////////////////////////////////////////////////////////////////// // Save Level Data XML ////////////////////////////////////////////////////////////////////////// @@ -389,41 +295,6 @@ void CGameExporter::ExportLevelData(const QString& path, bool bExportMission) CCryMemFile fileAction; fileAction.Write(xmlDataAction.c_str(), xmlDataAction.length()); m_levelPak.m_pakFile.UpdateFile(levelDataActionFile.toUtf8().data(), fileAction); - - if (bExportMission) - { - XmlNodeRef objectsNode = NULL; - ////////////////////////////////////////////////////////////////////////// - // Export current mission file. - ////////////////////////////////////////////////////////////////////////// - XmlNodeRef missionNode = rootAction->createNode("Mission"); - pCurrentMission->Export(missionNode, objectsNode); - - if (p3DEngine) - { - missionNode->setAttr("CGFCount", p3DEngine->GetLoadedObjectCount()); - } - - //if (!CFileUtil::OverwriteFile( path+currentMissionFileName )) - // return; - - AZStd::vector entitySaveBuffer; - AZ::IO::ByteContainerStream > entitySaveStream(&entitySaveBuffer); - bool savedEntities = false; - EBUS_EVENT_RESULT(savedEntities, AzToolsFramework::EditorEntityContextRequestBus, SaveToStreamForGame, entitySaveStream, AZ::DataStream::ST_BINARY); - if (savedEntities) - { - QString entitiesFile; - entitiesFile = QStringLiteral("%1%2.entities_xml").arg(path, pCurrentMission ? pCurrentMission->GetName() : ""); - m_levelPak.m_pakFile.UpdateFile(entitiesFile.toUtf8().data(), entitySaveBuffer.begin(), entitySaveBuffer.size()); - } - - _smart_ptr pXmlStrData = missionNode->getXMLData(5000000); - - CCryMemFile fileMission; - fileMission.Write(pXmlStrData->GetString(), pXmlStrData->GetStringLength()); - m_levelPak.m_pakFile.UpdateFile((path + currentMissionFileName).toUtf8().data(), fileMission); - } } ////////////////////////////////////////////////////////////////////////// @@ -446,18 +317,6 @@ void CGameExporter::ExportLevelInfo(const QString& path) const int compiledHeightmapSize = static_cast(terrainAabb.GetXExtent() / terrainGridResolution.GetX()); root->setAttr("HeightmapSize", compiledHeightmapSize); - // Save all missions in this level. - XmlNodeRef missionsNode = root->newChild("Missions"); - int numMissions = pEditor->GetDocument()->GetMissionCount(); - for (int i = 0; i < numMissions; i++) - { - CMission* pMission = pEditor->GetDocument()->GetMission(i); - XmlNodeRef missionNode = missionsNode->newChild("Mission"); - missionNode->setAttr("Name", pMission->GetName().toUtf8().data()); - missionNode->setAttr("Description", pMission->GetDescription().toUtf8().data()); - } - - ////////////////////////////////////////////////////////////////////////// // Save LevelInfo file. ////////////////////////////////////////////////////////////////////////// @@ -469,38 +328,6 @@ void CGameExporter::ExportLevelInfo(const QString& path) m_levelPak.m_pakFile.UpdateFile(filename.toUtf8().data(), file); } -////////////////////////////////////////////////////////////////////////// -void CGameExporter::ExportMapInfo(XmlNodeRef& node) -{ - if (!GetIEditor()->Get3DEngine()) - { - return; - } - - XmlNodeRef info = node->newChild("LevelInfo"); - - IEditor* pEditor = GetIEditor(); - info->setAttr("Name", QFileInfo(pEditor->GetDocument()->GetTitle()).completeBaseName()); - - auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); - const AZ::Aabb terrainAabb = terrain ? terrain->GetTerrainAabb() : AZ::Aabb::CreateFromPoint(AZ::Vector3::CreateZero()); - const AZ::Vector2 terrainGridResolution = terrain ? terrain->GetTerrainGridResolution() : AZ::Vector2::CreateOne(); - - const int terrainSizeInMeters = static_cast(terrainAabb.GetXExtent()); - const int terrainUnitSizeInMeters = static_cast(terrainGridResolution.GetX()); - info->setAttr("HeightmapSize", terrainSizeInMeters / terrainUnitSizeInMeters); - info->setAttr("HeightmapUnitSize", terrainUnitSizeInMeters); - //! Default Max Height value. - constexpr int HEIGHTMAP_MAX_HEIGHT = 150; //This is the default max height in CHeightmap - info->setAttr("HeightmapMaxHeight", HEIGHTMAP_MAX_HEIGHT); - info->setAttr("WaterLevel", pEditor->Get3DEngine()->GetWaterLevel()); - - // Serialize surface types. - CXmlArchive xmlAr; - xmlAr.bLoading = false; - xmlAr.root = node; -} - ////////////////////////////////////////////////////////////////////////// void CGameExporter::ExportLevelResourceList(const QString& path) { diff --git a/Code/Sandbox/Editor/GameExporter.h b/Code/Sandbox/Editor/GameExporter.h index a428046f0a..18ec79189a 100644 --- a/Code/Sandbox/Editor/GameExporter.h +++ b/Code/Sandbox/Editor/GameExporter.h @@ -91,9 +91,7 @@ private: void ExportLevelData(const QString& path, bool bExportMission = true); void ExportLevelInfo(const QString& path); - void ExportVisAreas(const char* pszGamePath, EEndian eExportEndian); void ExportOcclusionMesh(const char* pszGamePath); - void ExportMapInfo(XmlNodeRef& node); void ExportLevelResourceList(const QString& path); void ExportLevelUsedResourceList(const QString& path); diff --git a/Code/Sandbox/Editor/Geometry/EdGeometry.cpp b/Code/Sandbox/Editor/Geometry/EdGeometry.cpp deleted file mode 100644 index 13e8dd96ba..0000000000 --- a/Code/Sandbox/Editor/Geometry/EdGeometry.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "EdGeometry.h" diff --git a/Code/Sandbox/Editor/Geometry/EdGeometry.h b/Code/Sandbox/Editor/Geometry/EdGeometry.h deleted file mode 100644 index 3def344a35..0000000000 --- a/Code/Sandbox/Editor/Geometry/EdGeometry.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_GEOMETRY_EDGEOMETRY_H -#define CRYINCLUDE_EDITOR_GEOMETRY_EDGEOMETRY_H -#pragma once - -struct IIndexedMesh; -struct DisplayContext; -struct HitContext; -struct SSubObjSelectionModifyContext; -class CObjectArchive; - -// Basic supported geometry types. -enum EEdGeometryType -{ - GEOM_TYPE_MESH = 0, // Mesh geometry. - GEOM_TYPE_BRUSH, // Solid brush geometry. - GEOM_TYPE_PATCH, // Bezier patch surface geometry. - GEOM_TYPE_NURB, // Nurbs surface geometry. -}; - -////////////////////////////////////////////////////////////////////////// -// Description: -// CEdGeometry is a base class for all supported editable geometries. -////////////////////////////////////////////////////////////////////////// -class CRYEDIT_API CEdGeometry - : public CRefCountBase -{ -public: - CEdGeometry() {}; - - // Query the type of the geometry mesh. - virtual EEdGeometryType GetType() const = 0; - - // Serialize geometry. - virtual void Serialize(CObjectArchive& ar) = 0; - - // Return geometry axis aligned bounding box. - virtual void GetBounds(AABB& box) = 0; - - // Clones Geometry, returns exact copy of the original geometry. - virtual CEdGeometry* Clone() = 0; - - // Access to the indexed mesh. - // Return false if geometry can not be represented by an indexed mesh. - virtual IIndexedMesh* GetIndexedMesh(size_t idx = 0) = 0; - virtual IStatObj* GetIStatObj() const = 0; - virtual void GetTM(Matrix34* pTM, size_t idx = 0) = 0; - - ////////////////////////////////////////////////////////////////////////// - // Advanced geometry interface for SubObject selection and modification. - ////////////////////////////////////////////////////////////////////////// - virtual void SetModified(bool bModified = true) = 0; - virtual bool IsModified() const = 0; - virtual bool StartSubObjSelection(const Matrix34& nodeWorldTM, int elemType, int nFlags) = 0; - virtual void EndSubObjSelection() = 0; - - // Display geometry for sub object selection. - virtual void Display(DisplayContext& dc) = 0; - - // Sub geometry hit testing and selection. - virtual bool HitTest(HitContext& hit) = 0; - - ////////////////////////////////////////////////////////////////////////// - virtual void ModifySelection(SSubObjSelectionModifyContext& modCtx, bool isUndo = true) = 0; - // Called when selection modification is accepted. - virtual void AcceptModifySelection() = 0; - -protected: - ~CEdGeometry() {}; -}; - -#endif // CRYINCLUDE_EDITOR_GEOMETRY_EDGEOMETRY_H diff --git a/Code/Sandbox/Editor/Geometry/EdMesh.cpp b/Code/Sandbox/Editor/Geometry/EdMesh.cpp deleted file mode 100644 index 466c07ece7..0000000000 --- a/Code/Sandbox/Editor/Geometry/EdMesh.cpp +++ /dev/null @@ -1,1548 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Implementation of CEdMesh class. - - -#include "EditorDefs.h" - -// CryCommon -#include - -// Editor -#include "EdMesh.h" -#include "Viewport.h" -#include "ViewManager.h" -#include "Util/PakFile.h" -#include "Include/HitContext.h" -#include "Include/ITransformManipulator.h" -#include "Objects/ObjectLoader.h" -#include "Undo/IUndoObject.h" -#include "Util/fastlib.h" - - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -//! Undo object for Editable Mesh. -class CUndoEdMesh - : public IUndoObject -{ -public: - CUndoEdMesh(CEdMesh* pEdMesh, int nCopyFlags, const char* undoDescription) - { - // Stores the current state of this object. - assert(pEdMesh != 0); - m_nCopyFlags = nCopyFlags; - m_undoDescription = undoDescription; - m_pEdMesh = pEdMesh; - pEdMesh->CopyToMesh(undoMesh, nCopyFlags); - } -protected: - virtual int GetSize() - { - // sizeof(undoMesh) + sizeof(redoMesh); - return sizeof(*this); - } - virtual QString GetDescription() { return m_undoDescription; }; - - virtual void Undo(bool bUndo) - { - if (bUndo) - { - m_pEdMesh->CopyToMesh(redoMesh, m_nCopyFlags); - } - // Undo object state. - m_pEdMesh->CopyFromMesh(undoMesh, m_nCopyFlags, bUndo); - } - virtual void Redo() - { - m_pEdMesh->CopyFromMesh(redoMesh, m_nCopyFlags, true); - } - -private: - QString m_undoDescription; - int m_nCopyFlags; - _smart_ptr m_pEdMesh; - CTriMesh undoMesh; - CTriMesh redoMesh; -}; - -////////////////////////////////////////////////////////////////////////// -// Static member of CEdMesh. -////////////////////////////////////////////////////////////////////////// -CEdMesh::MeshMap CEdMesh::m_meshMap; - -////////////////////////////////////////////////////////////////////////// -CEdMesh::CEdMesh() -{ - m_pStatObj = 0; - m_pSubObjCache = 0; - m_nUserCount = 0; - m_bModified = false; -} - - -////////////////////////////////////////////////////////////////////////// -CEdMesh::CEdMesh(IStatObj* pGeom) -{ - assert(pGeom); - if (pGeom) - { - m_pStatObj = pGeom; - m_pStatObj->AddRef(); - } - m_pSubObjCache = 0; - m_nUserCount = 0; - m_bModified = false; -} - -////////////////////////////////////////////////////////////////////////// -CEdMesh::~CEdMesh() -{ - for (auto ppIndexedMeshes = m_tempIndexedMeshes.begin(); ppIndexedMeshes != m_tempIndexedMeshes.end(); ++ppIndexedMeshes) - { - SAFE_RELEASE(*ppIndexedMeshes); - } - - SAFE_RELEASE(m_pStatObj); - // Remove this object from map. - m_meshMap.erase(m_filename); - if (m_pSubObjCache) - { - if (m_pSubObjCache->pTriMesh) - { - delete m_pSubObjCache->pTriMesh; - } - delete m_pSubObjCache; - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::Serialize(CObjectArchive& ar) -{ - if (ar.bUndo) - { - return; - } - if (ar.bLoading) - { - } - else - { - if (m_bModified) - { - CBaseObject* pObj = ar.GetCurrentObject(); - if (pObj) - { - QString levelPath = Path::AddPathSlash(GetIEditor()->GetLevelFolder()); - CPakFile* pPakFile = ar.GetGeometryPak((levelPath + "\\Geometry.pak").toUtf8().data()); - if (pPakFile) - { - SaveToCGF(m_filename.toUtf8().data(), pPakFile); - } - } - SetModified(false); - } - } -} - -////////////////////////////////////////////////////////////////////////// -// CEdMesh implementation. -////////////////////////////////////////////////////////////////////////// -CEdMesh* CEdMesh::LoadMesh(const char* filename) -{ - if (strlen(filename) == 0) - { - return 0; - } - - // If object created see if its not yet registered. - CEdMesh* pMesh = stl::find_in_map(m_meshMap, filename, (CEdMesh*)0); - if (pMesh) - { - // Found, return it. - return pMesh; - } - - // Make new. - IStatObj* pGeom = GetIEditor()->Get3DEngine()->LoadStatObjUnsafeManualRef(filename); - if (!pGeom) - { - return 0; - } - - // Not found, Make new. - pMesh = new CEdMesh(pGeom); - pMesh->m_filename = filename; - m_meshMap[filename] = pMesh; - return pMesh; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::AddUser() -{ - m_nUserCount++; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::RemoveUser() -{ - m_nUserCount--; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::ReloadAllGeometries() -{ - for (MeshMap::iterator it = m_meshMap.begin(); it != m_meshMap.end(); ++it) - { - CEdMesh* pMesh = it->second; - if (pMesh) - { - pMesh->ReloadGeometry(); - } - } -} - -void CEdMesh::ReleaseAll() -{ - m_meshMap.clear(); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::ReloadGeometry() -{ - // Reload mesh. - if (m_pStatObj) - { - m_pStatObj->Refresh(FRO_GEOMETRY); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::IsSameObject(const char* filename) -{ - return QString::compare(m_filename, filename, Qt::CaseInsensitive) == 0; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::GetBounds(AABB& box) -{ - assert(m_pStatObj); - - if (m_pStatObj) - { - box.min = m_pStatObj->GetBoxMin(); - box.max = m_pStatObj->GetBoxMax(); - } -} - -////////////////////////////////////////////////////////////////////////// -CEdGeometry* CEdMesh::Clone() -{ - if (m_pStatObj) - { - // Clone StatObj. - IStatObj* pStatObj = m_pStatObj->Clone(true, true, false); - pStatObj->AddRef(); - CEdMesh* pNewMesh = new CEdMesh(pStatObj); - return pNewMesh; - } - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::SetFilename(const QString& filename) -{ - if (!m_filename.isEmpty()) - { - m_meshMap.erase(m_filename); - } - m_filename = Path::MakeGamePath(filename); - m_meshMap[m_filename] = this; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::Render(SRendParams& rp, const SRenderingPassInfo& passInfo) -{ - if (m_pStatObj) - { - m_pStatObj->Render(rp, passInfo); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::IsDefaultObject() -{ - if (m_pStatObj) - { - return m_pStatObj->IsDefaultObject(); - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -IIndexedMesh* CEdMesh::GetIndexedMesh(size_t idx) -{ - if (m_tempIndexedMeshes.size() == 0 && m_pStatObj) - { - if (m_pStatObj->GetIndexedMesh()) - { - if (idx == 0) - { - return m_pStatObj->GetIndexedMesh(); - } - - return nullptr; - } - else - { - // Load from CGF. - QString sFilename = m_pStatObj->GetFilePath(); - CContentCGF cgf(sFilename.toUtf8().data()); - if (gEnv->p3DEngine->LoadChunkFileContent(&cgf, sFilename.toUtf8().data())) - { - for (int i = 0; i < cgf.GetNodeCount(); ++i) - { - CNodeCGF* pNode = cgf.GetNode(i); - if (pNode->type == CNodeCGF::NODE_MESH) - { - CMesh* pMesh = pNode->pMesh; - if (pMesh) - { - IIndexedMesh* pTempIndexedMesh = GetIEditor()->Get3DEngine()->CreateIndexedMesh(); - pTempIndexedMesh->SetMesh(*pMesh); - m_tempIndexedMeshes.push_back(pTempIndexedMesh); - - Matrix34 tm = pNode->localTM; - CNodeCGF* pParent = pNode->pParent; - while (pParent) - { - tm = pParent->localTM * tm; - pParent = pParent->pParent; - } - m_tempMatrices.push_back(tm); - } - } - } - } - } - } - - if (idx < m_tempIndexedMeshes.size()) - { - return m_tempIndexedMeshes[idx]; - } - - return nullptr; -} - -void CEdMesh::GetTM(Matrix34* pTM, size_t idx) -{ - if (idx < m_tempMatrices.size()) - { - *pTM = m_tempMatrices[idx]; - } - else - { - pTM->SetIdentity(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::AcceptModifySelection() -{ - // Implement - UpdateIndexedMeshFromCache(true); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::UpdateIndexedMeshFromCache(bool bFast) -{ - // Implement - if (m_pSubObjCache) - { - if (bFast) - { - if (g_SubObjSelOptions.displayType == SO_DISPLAY_GEOMETRY) - { - m_pSubObjCache->pTriMesh->UpdateIndexedMesh(GetIndexedMesh()); - if (m_pStatObj) - { - m_pStatObj->Invalidate(); - } - } - } - else - { - m_pSubObjCache->pTriMesh->UpdateIndexedMesh(GetIndexedMesh()); - if (m_pStatObj) - { - m_pStatObj->Invalidate(); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::StartSubObjSelection(const Matrix34& nodeWorldTM, int elemType, [[maybe_unused]] int nFlags) -{ - IIndexedMesh* pIndexedMesh = GetIndexedMesh(); - if (!pIndexedMesh) - { - return false; - } - CMesh& mesh = *pIndexedMesh->GetMesh(); - - if (!m_pSubObjCache) - { - m_pSubObjCache = new SubObjCache; - } - m_pSubObjCache->worldTM = nodeWorldTM; - m_pSubObjCache->invWorldTM = nodeWorldTM.GetInverted(); - - if (!m_pSubObjCache->pTriMesh) - { - m_pSubObjCache->pTriMesh = new CTriMesh; - m_pSubObjCache->pTriMesh->SetFromMesh(mesh); - } - UpdateSubObjCache(); - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - triMesh.selectionType = elemType; - - m_pSubObjCache->bNoDisplay = false; - - return true; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::SetModified(bool bModified) -{ - if (m_pSubObjCache && bModified) - { - // Update xformed vertices. - UpdateSubObjCache(); - } - m_bModified = bModified; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::UpdateSubObjCache() -{ - Matrix34& wtm = m_pSubObjCache->worldTM; - - SetWorldTM(wtm); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::EndSubObjSelection() -{ - if (!m_pSubObjCache) - { - return; - } - - UpdateIndexedMeshFromCache(false); - - if (m_pSubObjCache->pTriMesh) - { - delete m_pSubObjCache->pTriMesh; - } - delete m_pSubObjCache; - m_pSubObjCache = 0; - - if (m_pStatObj) - { - if (m_bModified) - { - m_pStatObj->Invalidate(true); - } - // Clear hidden flag from geometry. - m_pStatObj->SetFlags(m_pStatObj->GetFlags() & (~STATIC_OBJECT_HIDDEN)); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::Display(DisplayContext& dc) -{ - if (!m_pSubObjCache || m_pSubObjCache->bNoDisplay) - { - return; - } - - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - if (!triMesh.pWSVertices) - { - return; - } - - if (m_pStatObj) - { - int nStatObjFlags = m_pStatObj->GetFlags(); - if (g_SubObjSelOptions.displayType == SO_DISPLAY_GEOMETRY) - { - nStatObjFlags &= ~STATIC_OBJECT_HIDDEN; - } - else - { - nStatObjFlags |= STATIC_OBJECT_HIDDEN; - } - m_pStatObj->SetFlags(nStatObjFlags); - } - - const Matrix34& worldTM = m_pSubObjCache->worldTM; - Vec3 vWSCameraVector = m_pSubObjCache->worldTM.GetTranslation() - dc.view->GetViewTM().GetTranslation(); - Vec3 vOSCameraVector = m_pSubObjCache->invWorldTM.TransformVector(vWSCameraVector).GetNormalized(); // Object space camera vector. - - // Render geometry vertices. - uint32 nPrevState = dc.GetState(); - - ////////////////////////////////////////////////////////////////////////// - // Calculate front facing vertices. - ////////////////////////////////////////////////////////////////////////// - triMesh.frontFacingVerts.resize(triMesh.GetVertexCount()); - triMesh.frontFacingVerts.clear(); - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - if (vOSCameraVector.Dot(face.normal) < 0) - { - triMesh.frontFacingVerts[face.v[0]] = true; - triMesh.frontFacingVerts[face.v[1]] = true; - triMesh.frontFacingVerts[face.v[2]] = true; - } - } - - ////////////////////////////////////////////////////////////////////////// - // Display flat shaded object. - ////////////////////////////////////////////////////////////////////////// - if (g_SubObjSelOptions.displayType == SO_DISPLAY_FLAT) - { - ColorB faceColor(0, 250, 250, 255); - ColorB col = faceColor; - dc.SetDrawInFrontMode(false); - dc.SetFillMode(e_FillModeSolid); - dc.CullOn(); - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - if (triMesh.selectionType != SO_ELEM_FACE || !triMesh.faceSel[i]) - { - ColorB col2 = faceColor; - float dt = -face.normal.Dot(vOSCameraVector); - dt = max(0.4f, dt); - dt = min(1.0f, dt); - col2.r = ftoi(faceColor.r * dt); - col2.g = ftoi(faceColor.g * dt); - col2.b = ftoi(faceColor.b * dt); - col2.a = faceColor.a; - dc.pRenderAuxGeom->DrawTriangle( - triMesh.pWSVertices[face.v[0]], col2, - triMesh.pWSVertices[face.v[1]], col2, - triMesh.pWSVertices[face.v[2]], col2 - ); - } - } - } - - // Draw selected triangles. - ColorB edgeColor(255, 255, 255, 155); - if (triMesh.StreamHaveSelection(CTriMesh::FACES)) - { - if (g_SubObjSelOptions.bDisplayBackfacing) - { - dc.CullOff(); - } - else - { - dc.CullOn(); - } - dc.SetDrawInFrontMode(true); - dc.SetFillMode(e_FillModeWireframe); - // Draw triangles. - //dc.pRenderAuxGeom->DrawTriangles( triMesh.pVertices,triMesh.GetVertexCount(), mesh.m_pIndices,mesh.GetIndexCount(),edgeColor ); - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - if (!triMesh.faceSel[i]) - { - dc.pRenderAuxGeom->DrawTriangle( - triMesh.pWSVertices[face.v[0]], edgeColor, - triMesh.pWSVertices[face.v[1]], edgeColor, - triMesh.pWSVertices[face.v[2]], edgeColor - ); - } - } - } - - if (g_SubObjSelOptions.bDisplayNormals) - { - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - Vec3 p1 = triMesh.pWSVertices[face.v[0]]; - Vec3 p2 = triMesh.pWSVertices[face.v[1]]; - Vec3 p3 = triMesh.pWSVertices[face.v[2]]; - Vec3 midp = (p1 + p2 + p3) * (1.0f / 3.0f); - dc.pRenderAuxGeom->DrawLine(midp, edgeColor, midp + worldTM.TransformVector(face.normal) * g_SubObjSelOptions.fNormalsLength, edgeColor); - } - } - - if (triMesh.selectionType == SO_ELEM_VERTEX || triMesh.StreamHaveSelection(CTriMesh::VERTICES)) - { - ColorB pointColor(0, 255, 255, 255); - - float fClrAdd = (g_SubObjSelOptions.bSoftSelection) ? 0 : 1; - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - bool bSelected = triMesh.vertSel[i] || triMesh.pWeights[i] != 0; - if (bSelected) - { - int clr = (triMesh.pWeights[i] + fClrAdd) * 255; - dc.pRenderAuxGeom->DrawPoint(triMesh.pWSVertices[i], ColorB(clr, 255 - clr, 255 - clr, 255), 8); - } - else if (!g_SubObjSelOptions.bDisplayBackfacing || triMesh.frontFacingVerts[i]) - { - dc.pRenderAuxGeom->DrawPoint(triMesh.pWSVertices[i], pointColor, 5); - } - } - } - - // Draw edges. - if (triMesh.selectionType == SO_ELEM_EDGE || triMesh.StreamHaveSelection(CTriMesh::EDGES)) - { - ColorB edgeColor2(200, 255, 200, 255); - ColorB selEdgeColor(255, 0, 0, 255); - - // Draw selected edges. - for (int i = 0; i < triMesh.GetEdgeCount(); i++) - { - CTriEdge& edge = triMesh.pEdges[i]; - if (triMesh.edgeSel[i]) - { - const Vec3& p1 = triMesh.pWSVertices[edge.v[0]]; - const Vec3& p2 = triMesh.pWSVertices[edge.v[1]]; - dc.pRenderAuxGeom->DrawLine(p1, selEdgeColor, p2, selEdgeColor, 6); - } - else if (!g_SubObjSelOptions.bDisplayBackfacing || ( - triMesh.frontFacingVerts[edge.v[0]] && triMesh.frontFacingVerts[edge.v[1]])) - { - const Vec3& p1 = triMesh.pWSVertices[edge.v[0]]; - const Vec3& p2 = triMesh.pWSVertices[edge.v[1]]; - dc.pRenderAuxGeom->DrawLine(p1, edgeColor2, p2, edgeColor2); - } - } - } - - if (triMesh.selectionType == SO_ELEM_FACE) - { - ColorB pointColor(0, 255, 255, 255); - ColorB selFaceColor(255, 0, 0, 180); - - // Draw selected faces and face points. - dc.CullOff(); - dc.SetFillMode(e_FillModeSolid); - - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - const Vec3& p1 = triMesh.pWSVertices[face.v[0]]; - const Vec3& p2 = triMesh.pWSVertices[face.v[1]]; - const Vec3& p3 = triMesh.pWSVertices[face.v[2]]; - if (triMesh.faceSel[i]) - { - dc.pRenderAuxGeom->DrawTriangle(p1, selFaceColor, p2, selFaceColor, p3, selFaceColor); - } - - if (!g_SubObjSelOptions.bDisplayBackfacing && vOSCameraVector.Dot(face.normal) > 0) - { - continue; // Backfacing. - } - Vec3 midp = (p1 + p2 + p3) * (1.0f / 3.0f); - dc.pRenderAuxGeom->DrawPoint(midp, pointColor, 4); - } - } - else if (triMesh.StreamHaveSelection(CTriMesh::FACES)) - { - ColorB pointColor(0, 255, 255, 255); - ColorB selFaceColor(255, 0, 0, 180); - - // Draw selected faces and face points. - dc.CullOff(); - dc.SetFillMode(e_FillModeSolid); - - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - const Vec3& p1 = triMesh.pWSVertices[face.v[0]]; - const Vec3& p2 = triMesh.pWSVertices[face.v[1]]; - const Vec3& p3 = triMesh.pWSVertices[face.v[2]]; - if (triMesh.faceSel[i]) - { - dc.pRenderAuxGeom->DrawTriangle(p1, selFaceColor, p2, selFaceColor, p3, selFaceColor); - } - } - } - - dc.SetState(nPrevState); // Restore render state. -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::HitTestVertex(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - // This make sure that bit array size matches num vertices, front facing should be calculated in Display method. - triMesh.frontFacingVerts.resize(triMesh.GetVertexCount()); - - float minDist = FLT_MAX; - int closestElem = -1; - - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - if (env.bIgnoreBackfacing && !triMesh.frontFacingVerts[i]) - { - continue; - } - QPoint p = hit.view->WorldToView(triMesh.pWSVertices[i]); - if (p.x() >= hit.rect.left() && p.x() <= hit.rect.right() && - p.y() >= hit.rect.top() && p.y() <= hit.rect.bottom()) - { - if (env.bHitTestNearest) - { - float dist = env.vWSCameraPos.GetDistance(triMesh.pWSVertices[i]); - if (dist < minDist) - { - closestElem = i; - minDist = dist; - } - } - else - { - result.elems.push_back(i); - } - } - } - ////////////////////////////////////////////////////////////////////////// - if (closestElem >= 0) - { - result.minDistance = minDist; - result.elems.push_back(closestElem); - } - return !result.elems.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::HitTestEdge(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - // This make sure that bit array size matches num vertices, front facing should be calculated in Display method. - triMesh.frontFacingVerts.resize(triMesh.GetVertexCount()); - - float minDist = FLT_MAX; - int closestElem = -1; - - for (int i = 0; i < triMesh.GetEdgeCount(); i++) - { - CTriEdge& edge = triMesh.pEdges[i]; - if (!env.bIgnoreBackfacing || - (triMesh.frontFacingVerts[edge.v[0]] && triMesh.frontFacingVerts[edge.v[1]])) - { - if (hit.view->HitTestLine(triMesh.pWSVertices[edge.v[0]], triMesh.pWSVertices[edge.v[1]], hit.point2d, 5)) - { - if (env.bHitTestNearest) - { - float dist = env.vWSCameraPos.GetDistance(triMesh.pWSVertices[edge.v[0]]); - if (dist < minDist) - { - closestElem = i; - minDist = dist; - } - } - else - { - result.elems.push_back(i); - } - } - } - } - ////////////////////////////////////////////////////////////////////////// - if (closestElem >= 0) - { - result.minDistance = minDist; - result.elems.push_back(closestElem); - } - return !result.elems.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::HitTestFace(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - float minDist = FLT_MAX; - int closestElem = -1; - - Vec3 vOut(0, 0, 0); - Ray hitRay(hit.raySrc, hit.rayDir); - - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - CTriFace& face = triMesh.pFaces[i]; - - if (env.bIgnoreBackfacing && env.vOSCameraVector.Dot(face.normal) > 0) - { - continue; // Back facing. - } - Vec3 p1 = triMesh.pWSVertices[face.v[0]]; - Vec3 p2 = triMesh.pWSVertices[face.v[1]]; - Vec3 p3 = triMesh.pWSVertices[face.v[2]]; - - if (!env.bHitTestNearest) - { - // Hit test face middle point in rectangle. - Vec3 midp = (p1 + p2 + p3) * (1.0f / 3.0f); - - QPoint p = hit.view->WorldToView(midp); - if (p.x() >= hit.rect.left() && p.x() <= hit.rect.right() && - p.y() >= hit.rect.top() && p.y() <= hit.rect.bottom()) - { - result.elems.push_back(i); - } - } - else - { - // Hit test ray/triangle. - if (Intersect::Ray_Triangle(hitRay, p1, p3, p2, vOut)) - { - float dist = hitRay.origin.GetSquaredDistance(vOut); - if (dist < minDist) - { - closestElem = i; - minDist = dist; - } - } - } - } - ////////////////////////////////////////////////////////////////////////// - if (closestElem >= 0) - { - result.minDistance = (float)sqrt(minDist); - result.elems.push_back(closestElem); - } - return !result.elems.empty(); -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::SelectSubObjElements(SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - bool bSelChanged = false; - if (env.bSelectOnHit && !result.elems.empty()) - { - CBitArray* streamSel = triMesh.GetStreamSelection(result.stream); - if (streamSel) - { - // Select on hit. - for (int i = 0, num = result.elems.size(); i < num; i++) - { - int elem = result.elems[i]; - if ((*streamSel)[elem] != env.bSelectValue) - { - bSelChanged = true; - (*streamSel)[elem] = env.bSelectValue; - } - } - if (bSelChanged) - { - if (env.bSelectValue) - { - triMesh.streamSelMask |= (1 << result.stream); - } - else if (!env.bSelectValue && streamSel->is_zero()) - { - triMesh.streamSelMask &= ~(1 << result.stream); - } - } - } - } - return bSelChanged; -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::IsHitTestResultSelected(SSubObjHitTestResult& result) -{ - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - if (!result.elems.empty()) - { - CBitArray* streamSel = triMesh.GetStreamSelection(result.stream); - if (streamSel) - { - // check if first result element is selected. - if ((*streamSel)[ result.elems[0] ]) - { - return true; - } - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::HitTest(HitContext& hit) -{ - if (hit.nSubObjFlags & SO_HIT_NO_EDIT) - // This is for a 'move-by-face-normal'. Prepare the mesh and set the 'bNoDisplay'to true - // so that the normal rendering happens instead of the edit-mode rendering. - { - StartSubObjSelection(hit.object->GetWorldTM(), SO_ELEM_FACE, 0); - m_pSubObjCache->bNoDisplay = true; - } - - if (!m_pSubObjCache) - { - return false; - } - - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - SSubObjHitTestEnvironment env; - env.vWSCameraPos = hit.view->GetViewTM().GetTranslation(); - env.vWSCameraVector = m_pSubObjCache->worldTM.GetTranslation() - hit.view->GetViewTM().GetTranslation(); - env.vOSCameraVector = m_pSubObjCache->invWorldTM.TransformVector(env.vWSCameraVector).GetNormalized(); // Object space camera vector. - - env.bHitTestNearest = hit.nSubObjFlags & SO_HIT_POINT; - env.bHitTestSelected = hit.nSubObjFlags & SO_HIT_TEST_SELECTED; - env.bSelectOnHit = hit.nSubObjFlags & SO_HIT_SELECT; - env.bAdd = hit.nSubObjFlags & SO_HIT_SELECT_ADD; - env.bRemove = hit.nSubObjFlags & SO_HIT_SELECT_REMOVE; - env.bSelectValue = !env.bRemove; - env.bHighlightOnly = hit.nSubObjFlags & SO_HIT_HIGHLIGHT_ONLY; - env.bIgnoreBackfacing = g_SubObjSelOptions.bIgnoreBackfacing && !env.bHitTestNearest; - - int nHitTestWhat = (hit.nSubObjFlags & SO_HIT_ELEM_ALL); - if (nHitTestWhat == 0) - { - if (g_SubObjSelOptions.bSelectByVertex) - { - nHitTestWhat |= SO_HIT_ELEM_VERTEX; - } - switch (triMesh.selectionType) - { - case SO_ELEM_VERTEX: - nHitTestWhat |= SO_HIT_ELEM_VERTEX; - break; - case SO_ELEM_EDGE: - nHitTestWhat |= SO_HIT_ELEM_EDGE; - break; - case SO_ELEM_FACE: - nHitTestWhat |= SO_HIT_ELEM_FACE; - break; - case SO_ELEM_POLYGON: - nHitTestWhat |= SO_HIT_ELEM_POLYGON; - break; - } - } - - IUndoObject* pUndoObj = NULL; - if (env.bSelectOnHit) - { - if (CUndo::IsRecording() && !(hit.nSubObjFlags & SO_HIT_NO_EDIT)) - { - switch (triMesh.selectionType) - { - case SO_ELEM_VERTEX: - pUndoObj = new CUndoEdMesh(this, CTriMesh::COPY_VERT_SEL | CTriMesh::COPY_WEIGHTS, "Select Vertex(s)"); - break; - case SO_ELEM_EDGE: - pUndoObj = new CUndoEdMesh(this, CTriMesh::COPY_EDGE_SEL | CTriMesh::COPY_WEIGHTS, "Select Edge(s)"); - break; - case SO_ELEM_FACE: - pUndoObj = new CUndoEdMesh(this, CTriMesh::COPY_FACE_SEL | CTriMesh::COPY_WEIGHTS, "Select Face(s)"); - break; - } - } - } - - bool bSelChanged = false; - bool bAnyHit = false; - ////////////////////////////////////////////////////////////////////////// - if (env.bSelectOnHit && !env.bAdd && !env.bRemove) - { - bSelChanged = triMesh.ClearSelection(); - } - ////////////////////////////////////////////////////////////////////////// - - SSubObjHitTestResult result[4]; - result[0].stream = CTriMesh::VERTICES; - result[1].stream = CTriMesh::EDGES; - result[2].stream = CTriMesh::FACES; - - if (nHitTestWhat & SO_HIT_ELEM_VERTEX) - { - if (HitTestVertex(hit, env, result[0])) - { - bAnyHit = true; - } - } - - if (nHitTestWhat & SO_HIT_ELEM_EDGE) - { - if (HitTestEdge(hit, env, result[1])) - { - bAnyHit = true; - } - } - - if (nHitTestWhat & SO_HIT_ELEM_FACE) - { - if (HitTestFace(hit, env, result[2])) - { - bAnyHit = true; - } - } - - if (bAnyHit && !env.bSelectOnHit && !env.bHitTestSelected) - { - // Return distance to the first hit element. - hit.dist = min(min(result[0].minDistance, result[1].minDistance), result[2].minDistance); - return true; - } - if (bAnyHit && !env.bSelectOnHit && env.bHitTestSelected) - { - // check if we hit selected item. - if (IsHitTestResultSelected(result[0]) || - IsHitTestResultSelected(result[1]) || - IsHitTestResultSelected(result[2])) - { - hit.dist = min(min(result[0].minDistance, result[1].minDistance), result[2].minDistance); - return true; - } - // If not hit selected. - return false; - } - if (bAnyHit) - { - // Find closest hit. - int n = 0; - if (!result[0].elems.empty()) - { - n = 0; - } - else if (!result[1].elems.empty()) - { - n = 1; - } - else if (!result[2].elems.empty()) - { - n = 2; - } - - hit.dist = result[n].minDistance; - - if (env.bSelectOnHit && - g_SubObjSelOptions.bSelectByVertex && - !result[0].elems.empty() && - !env.bHighlightOnly && - triMesh.selectionType != SO_HIT_ELEM_VERTEX) - { - // When selecting elements by vertex. - switch (triMesh.selectionType) - { - case SO_ELEM_EDGE: - n = 1; - triMesh.GetEdgesByVertex(result[0].elems, result[1].elems); - break; - case SO_ELEM_FACE: - n = 2; - triMesh.GetFacesByVertex(result[0].elems, result[2].elems); - break; - case SO_ELEM_POLYGON: - n = 2; - triMesh.GetFacesByVertex(result[0].elems, result[2].elems); - break; - } - } - if (env.bSelectOnHit && SelectSubObjElements(env, result[n])) - { - bSelChanged = true; - } - } - if (bSelChanged) - { - hit.nSubObjFlags |= SO_HIT_SELECTION_CHANGED; - } - else - { - hit.nSubObjFlags &= ~SO_HIT_SELECTION_CHANGED; - } - - bool bSelectionNotEmpty = false; - if (env.bSelectOnHit && bSelChanged && !env.bHighlightOnly) - { - if (CUndo::IsRecording() && pUndoObj) - { - CUndo::Record(pUndoObj); - } - - bSelectionNotEmpty = triMesh.UpdateSelection(); - if (g_SubObjSelOptions.bSoftSelection) - { - triMesh.SoftSelection(g_SubObjSelOptions); - } - - OnSelectionChange(); - } - else - { - if (pUndoObj) - { - pUndoObj->Release(); - } - } - - return bSelectionNotEmpty; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::OnSelectionChange() -{ - Matrix34 localRefFrame; - if (!GetSelectionReferenceFrame(localRefFrame)) - { - GetIEditor()->ShowTransformManipulator(false); - } - else - { - ITransformManipulator* pManipulator = GetIEditor()->ShowTransformManipulator(true); - - // In local space orient axis gizmo by first object. - localRefFrame = m_pSubObjCache->worldTM * localRefFrame; - - Matrix34 parentTM = m_pSubObjCache->worldTM; - Matrix34 userTM = GetIEditor()->GetViewManager()->GetGrid()->GetMatrix(); - parentTM.SetTranslation(localRefFrame.GetTranslation()); - userTM.SetTranslation(localRefFrame.GetTranslation()); - //tm.SetTranslation( m_selectionCenter ); - pManipulator->SetTransformation(COORDS_LOCAL, localRefFrame); - pManipulator->SetTransformation(COORDS_PARENT, parentTM); - pManipulator->SetTransformation(COORDS_USERDEFINED, userTM); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CEdMesh::GetSelectionReferenceFrame(Matrix34& refFrame) -{ - if (!m_pSubObjCache) - { - return false; - } - - bool bAnySelected = false; - - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - Vec3 normal(0, 0, 0); - - refFrame.SetIdentity(); - - if (triMesh.selectionType == SO_ELEM_VERTEX) - { - // Average all selected vertex normals. - int numNormals = 0; - int nFaces = triMesh.GetFacesCount(); - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - if (triMesh.vertSel[i]) - { - bAnySelected = true; - int nVertexIndex = i; - for (int j = 0; j < nFaces; j++) - { - CTriFace& face = triMesh.pFaces[j]; - for (int k = 0; k < 3; k++) - { - if (face.v[k] == nVertexIndex) - { - normal += face.n[k]; - numNormals++; - } - } - } - } - } - if (numNormals > 0) - { - normal = normal / numNormals; - if (!normal.IsZero()) - { - normal.Normalize(); - } - } - } - else if (triMesh.selectionType == SO_ELEM_EDGE) - { - int nNormals = 0; - // Average face normals of a the selected edges. - for (int i = 0; i < triMesh.GetEdgeCount(); i++) - { - if (triMesh.edgeSel[i]) - { - bAnySelected = true; - CTriEdge& edge = triMesh.pEdges[i]; - for (int j = 0; j < 2; j++) - { - if (edge.face[j] >= 0) - { - normal = normal + triMesh.pFaces[edge.face[j]].normal; - nNormals++; - } - } - } - } - if (nNormals > 0) - { - normal = normal / nNormals; - if (!normal.IsZero()) - { - normal.Normalize(); - } - } - } - else if (triMesh.selectionType == SO_ELEM_FACE) - { - // Average all face normals. - int nNormals = 0; - for (int i = 0; i < triMesh.GetFacesCount(); i++) - { - if (triMesh.faceSel[i]) - { - bAnySelected = true; - CTriFace& face = triMesh.pFaces[i]; - normal = normal + face.normal; - nNormals++; - } - } - if (nNormals > 0) - { - normal = normal / nNormals; - if (!normal.IsZero()) - { - normal.Normalize(); - } - } - } - - if (bAnySelected) - { - Vec3 pos(0, 0, 0); - int numSel = 0; - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - if (triMesh.pWeights[i] == 1.0f) - { - pos = pos + triMesh.pVertices[i].pos; - numSel++; - } - } - if (numSel > 0) - { - pos = pos / numSel; // Average position. - } - refFrame.SetTranslation(pos); - - if (!normal.IsZero()) - { - Vec3 xAxis(1, 0, 0), yAxis(0, 1, 0), zAxis(0, 0, 1); - if (normal.IsEquivalent(zAxis) || normal.IsEquivalent(-zAxis)) - { - zAxis = xAxis; - } - xAxis = normal.Cross(zAxis).GetNormalized(); - yAxis = xAxis.Cross(normal).GetNormalized(); - refFrame.SetFromVectors(xAxis, yAxis, normal, pos); - } - } - - return bAnySelected; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::ModifySelection(SSubObjSelectionModifyContext& modCtx, [[maybe_unused]] bool isUndo) -{ - if (!m_pSubObjCache) - { - return; - } - - IIndexedMesh* pIndexedMesh = GetIndexedMesh(); - if (!pIndexedMesh) - { - return; - } - - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - - if (modCtx.type == SO_MODIFY_UNSELECT) - { - IUndoObject* pUndoObj = NULL; - if (CUndo::IsRecording()) - { - pUndoObj = new CUndoEdMesh(this, CTriMesh::COPY_VERT_SEL | CTriMesh::COPY_WEIGHTS, "Move Vertices"); - } - bool bChanged = triMesh.ClearSelection(); - if (bChanged) - { - OnSelectionChange(); - } - if (CUndo::IsRecording() && bChanged) - { - CUndo::Record(pUndoObj); - } - else if (pUndoObj) - { - pUndoObj->Release(); - } - return; - } - - Matrix34 worldTM = m_pSubObjCache->worldTM; - Matrix34 invTM = worldTM.GetInverted(); - - // Change modify reference frame to object space. - Matrix34 modRefFrame = invTM * modCtx.worldRefFrame; - Matrix34 modRefFrameInverse = modCtx.worldRefFrame.GetInverted() * worldTM; - - if (modCtx.type == SO_MODIFY_MOVE) - { - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoEdMesh(this, CTriMesh::COPY_VERTICES, "Move Vertices")); - } - - Vec3 vOffset = modCtx.vValue; - vOffset = modCtx.worldRefFrame.GetInverted().TransformVector(vOffset); // Offset in local space. - - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - CTriVertex& vtx = triMesh.pVertices[i]; - if (triMesh.pWeights[i] != 0) - { - Matrix34 tm = modRefFrame * Matrix34::CreateTranslationMat(vOffset * triMesh.pWeights[i]) * modRefFrameInverse; - vtx.pos = tm.TransformPoint(vtx.pos); - } - } - OnSelectionChange(); - } - else if (modCtx.type == SO_MODIFY_ROTATE) - { - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoEdMesh(this, CTriMesh::COPY_VERTICES, "Rotate Vertices")); - } - - Ang3 angles = Ang3(modCtx.vValue); - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - CTriVertex& vtx = triMesh.pVertices[i]; - if (triMesh.pWeights[i] != 0) - { - Matrix34 tm = modRefFrame * Matrix33::CreateRotationXYZ(angles * triMesh.pWeights[i]) * modRefFrameInverse; - vtx.pos = tm.TransformPoint(vtx.pos); - } - } - } - else if (modCtx.type == SO_MODIFY_SCALE) - { - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoEdMesh(this, CTriMesh::COPY_VERTICES, "Scale Vertices")); - } - - Vec3 vScale = modCtx.vValue; - for (int i = 0; i < triMesh.GetVertexCount(); i++) - { - CTriVertex& vtx = triMesh.pVertices[i]; - if (triMesh.pWeights[i] != 0) - { - Vec3 scl = Vec3(1.0f, 1.0f, 1.0f) * (1.0f - triMesh.pWeights[i]) + vScale * triMesh.pWeights[i]; - Matrix34 tm = modRefFrame * Matrix33::CreateScale(scl) * modRefFrameInverse; - vtx.pos = tm.TransformPoint(vtx.pos); - } - } - } - - SetModified(); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::CopyToMesh(CTriMesh& toMesh, int nCopyFlags) -{ - if (!m_pSubObjCache) - { - return; - } - - toMesh.Copy(*m_pSubObjCache->pTriMesh, nCopyFlags); -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::CopyFromMesh(CTriMesh& fromMesh, int nCopyFlags, bool bUndo) -{ - if (m_pSubObjCache) - { - m_pSubObjCache->pTriMesh->Copy(fromMesh, nCopyFlags); - } - else - { - /* - CMesh mesh; - CTriMesh triMesh; - triMesh.Copy( fromMesh ); - trimesh.void CopyToMeshFast( CMesh &mesh ); - */ - } - if (bUndo) - { - UpdateIndexedMeshFromCache(true); - OnSelectionChange(); - } - - if (m_pSubObjCache) - { - UpdateSubObjCache(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::SaveToCGF(const char* sFilename, CPakFile* pPakFile, _smart_ptr pMaterial) -{ - if (m_pStatObj) - { - // Save this EdMesh to CGF file. - m_filename = Path::MakeGamePath(sFilename); - - _smart_ptr pOriginalMaterial = m_pStatObj->GetMaterial(); - if (pMaterial) - { - m_pStatObj->SetMaterial(pMaterial); - } - - if (!pPakFile) - { - m_pStatObj->SaveToCGF(sFilename); - } - else - { - IChunkFile* pChunkFile = NULL; - if (m_pStatObj->SaveToCGF(sFilename, &pChunkFile)) - { - void* pMemFile = NULL; - int nFileSize = 0; - - pChunkFile->WriteToMemoryBuffer(&pMemFile, &nFileSize); - pPakFile->UpdateFile(sFilename, pMemFile, nFileSize, true, AZ::IO::INestedArchive::LEVEL_FASTER); - pChunkFile->Release(); - } - } - - // Restore original material. - if (pMaterial) - { - m_pStatObj->SetMaterial(pOriginalMaterial); - } - } -} - -////////////////////////////////////////////////////////////////////////// -CTriMesh* CEdMesh::GetMesh() -{ - if (m_pSubObjCache) - { - return m_pSubObjCache->pTriMesh; - } - return 0; -} - -////////////////////////////////////////////////////////////////////////// -CEdMesh* CEdMesh::CreateMesh(const char* name) -{ - IStatObj* pStatObj = gEnv->p3DEngine->CreateStatObj(); - if (pStatObj) - { - CEdMesh* pEdMesh = new CEdMesh; - pEdMesh->m_pStatObj = pStatObj; - pEdMesh->m_pStatObj->AddRef(); - - // Force create of indexed mesh. - pEdMesh->m_pStatObj->GetIndexedMesh(true); - - // Not found, Make new. - pEdMesh->m_filename = name; - - if (!pEdMesh->m_pSubObjCache) - { - pEdMesh->m_pSubObjCache = new SubObjCache; - pEdMesh->m_pSubObjCache->pTriMesh = new CTriMesh; - pEdMesh->m_pSubObjCache->worldTM.SetIdentity(); - pEdMesh->m_pSubObjCache->invWorldTM.SetIdentity(); - } - return pEdMesh; - } - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::InvalidateMesh() -{ - if (m_pSubObjCache) - { - UpdateIndexedMeshFromCache(false); - } - if (m_pStatObj) - { - m_pStatObj->Invalidate(true); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::SetWorldTM(const Matrix34& worldTM) -{ - if (!m_pSubObjCache) - { - return; - } - - m_pSubObjCache->worldTM = worldTM; - m_pSubObjCache->invWorldTM = worldTM.GetInverted(); - - ////////////////////////////////////////////////////////////////////////// - // Transform vertices and normals to world space and store in cached mesh. - ////////////////////////////////////////////////////////////////////////// - CTriMesh& triMesh = *m_pSubObjCache->pTriMesh; - int nVerts = triMesh.GetVertexCount(); - triMesh.ReallocStream(CTriMesh::WS_POSITIONS, nVerts); - for (int i = 0; i < nVerts; i++) - { - triMesh.pWSVertices[i] = worldTM.TransformPoint(triMesh.pVertices[i].pos); - } -} - -////////////////////////////////////////////////////////////////////////// -void CEdMesh::DebugDraw(const SGeometryDebugDrawInfo& info, float fExtrdueScale) -{ - if (m_pStatObj) - { - m_pStatObj->DebugDraw(info, fExtrdueScale); - } -} diff --git a/Code/Sandbox/Editor/Geometry/EdMesh.h b/Code/Sandbox/Editor/Geometry/EdMesh.h deleted file mode 100644 index 52dc1fc25d..0000000000 --- a/Code/Sandbox/Editor/Geometry/EdMesh.h +++ /dev/null @@ -1,194 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Editor structure that wraps access to IStatObj - - -#ifndef CRYINCLUDE_EDITOR_GEOMETRY_EDMESH_H -#define CRYINCLUDE_EDITOR_GEOMETRY_EDMESH_H -#pragma once - -#include "EdGeometry.h" -#include "Objects/SubObjSelection.h" -#include "TriMesh.h" - -// Flags that can be set on CEdMesh. -enum CEdMeshFlags -{ -}; - -////////////////////////////////////////////////////////////////////////// -// Description: -// CEdMesh is a Geometry kind representing simple mesh. -// Holds IStatObj interface from the 3D Engine. -////////////////////////////////////////////////////////////////////////// -class CRYEDIT_API CEdMesh - : public CEdGeometry -{ -public: - ////////////////////////////////////////////////////////////////////////// - // CEdGeometry implementation. - ////////////////////////////////////////////////////////////////////////// - virtual EEdGeometryType GetType() const { return GEOM_TYPE_MESH; }; - virtual void Serialize(CObjectArchive& ar); - - virtual void GetBounds(AABB& box); - virtual CEdGeometry* Clone(); - virtual IIndexedMesh* GetIndexedMesh(size_t idx = 0); - virtual void GetTM(Matrix34* pTM, size_t idx = 0); - virtual void SetModified(bool bModified = true); - virtual bool IsModified() const { return m_bModified; }; - virtual bool StartSubObjSelection(const Matrix34& nodeWorldTM, int elemType, int nFlags); - virtual void EndSubObjSelection(); - virtual void Display(DisplayContext& dc); - virtual bool HitTest(HitContext& hit); - bool GetSelectionReferenceFrame(Matrix34& refFrame); - virtual void ModifySelection(SSubObjSelectionModifyContext& modCtx, bool isUndo = true); - virtual void AcceptModifySelection(); - ////////////////////////////////////////////////////////////////////////// - - ~CEdMesh(); - - // Return filename of mesh. - const QString& GetFilename() const { return m_filename; }; - void SetFilename(const QString& filename); - - //! Reload geometry of mesh. - void ReloadGeometry(); - void AddUser(); - void RemoveUser(); - int GetUserCount() const { return m_nUserCount; }; - - ////////////////////////////////////////////////////////////////////////// - void SetFlags(int nFlags) { m_nFlags = nFlags; }; - int GetFlags() { return m_nFlags; } - ////////////////////////////////////////////////////////////////////////// - - //! Access stored IStatObj. - IStatObj* GetIStatObj() const { return m_pStatObj; } - - //! Returns true if filename and geomname refer to the same object as this one. - bool IsSameObject(const char* filename); - - //! RenderMesh. - void Render(SRendParams& rp, const SRenderingPassInfo& passInfo); - - //! Make new CEdMesh, if same IStatObj loaded, and CEdMesh for this IStatObj is allocated. - //! This instance of CEdMesh will be returned. - static CEdMesh* LoadMesh(const char* filename); - - // Creates a new mesh not from a file. - // Create a new StatObj and IndexedMesh. - static CEdMesh* CreateMesh(const char* name); - - //! Reload all geometries. - static void ReloadAllGeometries(); - static void ReleaseAll(); - - //! Check if default object was loaded. - bool IsDefaultObject(); - - ////////////////////////////////////////////////////////////////////////// - // Copy EdMesh data to the specified mesh. - void CopyToMesh(CTriMesh& toMesh, int nCopyFlags); - // Copy EdMesh data from the specified mesh. - void CopyFromMesh(CTriMesh& fromMesh, int nCopyFlags, bool bUndo); - - // Retrieve mesh class. - CTriMesh* GetMesh(); - - ////////////////////////////////////////////////////////////////////////// - void InvalidateMesh(); - void SetWorldTM(const Matrix34& worldTM); - - // Save mesh into the file. - // Optionally can provide pointer to the pak file where to save files into. - void SaveToCGF(const char* sFilename, CPakFile* pPakFile = NULL, _smart_ptr pMaterial = NULL); - - // Draw debug representation of this mesh. - void DebugDraw(const SGeometryDebugDrawInfo& info, float fExtrdueScale = 0.01f); - -private: - ////////////////////////////////////////////////////////////////////////// - CEdMesh(IStatObj* pGeom); - CEdMesh(); - void UpdateSubObjCache(); - void UpdateIndexedMeshFromCache(bool bFast); - void OnSelectionChange(); - - ////////////////////////////////////////////////////////////////////////// - struct SSubObjHitTestEnvironment - { - Vec3 vWSCameraPos; - Vec3 vWSCameraVector; - Vec3 vOSCameraVector; - - bool bHitTestNearest; - bool bHitTestSelected; - bool bSelectOnHit; - bool bAdd; - bool bRemove; - bool bSelectValue; - bool bHighlightOnly; - bool bIgnoreBackfacing; - }; - struct SSubObjHitTestResult - { - CTriMesh::EStream stream; // To What stream of the TriMesh this result apply. - MeshElementsArray elems; // List of hit elements. - float minDistance; // Minimal distance to the hit. - SSubObjHitTestResult() { minDistance = FLT_MAX; } - }; - bool HitTestVertex(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result); - bool HitTestEdge(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result); - bool HitTestFace(HitContext& hit, SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result); - - // Return`s true if selection changed. - bool SelectSubObjElements(SSubObjHitTestEnvironment& env, SSubObjHitTestResult& result); - bool IsHitTestResultSelected(SSubObjHitTestResult& result); - - ////////////////////////////////////////////////////////////////////////// - //! CGF filename. - QString m_filename; - IStatObj* m_pStatObj; - int m_nUserCount; - int m_nFlags; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - typedef std::map > MeshMap; - static MeshMap m_meshMap; - - // This cache is created when sub object selection is needed. - struct SubObjCache - { - // Cache of data in geometry. - // World space mesh. - CTriMesh* pTriMesh; - Matrix34 worldTM; - Matrix34 invWorldTM; - CBitArray m_tempBitArray; - bool bNoDisplay; - - SubObjCache() - : pTriMesh(0) - , bNoDisplay(false) {}; - }; - SubObjCache* m_pSubObjCache; - bool m_bModified; - - std::vector m_tempIndexedMeshes; - std::vector m_tempMatrices; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // CRYINCLUDE_EDITOR_GEOMETRY_EDMESH_H diff --git a/Code/Sandbox/Editor/IEditor.h b/Code/Sandbox/Editor/IEditor.h index c03b99e128..f11beacf10 100644 --- a/Code/Sandbox/Editor/IEditor.h +++ b/Code/Sandbox/Editor/IEditor.h @@ -85,7 +85,6 @@ namespace WinWidget } struct ISystem; -struct I3DEngine; struct IRenderer; struct AABB; struct IEventLoopHook; @@ -137,7 +136,6 @@ enum EEditorNotifyEvent eNotify_OnEndLayerExport, // Sent after a layer have been exported. eNotify_OnCloseScene, // Send when the document is about to close. eNotify_OnSceneClosed, // Send when the document is closed. - eNotify_OnMissionChange, // Send when the current mission changes. eNotify_OnBeginLoad, // Sent when the document is start to load. eNotify_OnEndLoad, // Sent when the document loading is finished @@ -180,8 +178,6 @@ enum EEditorNotifyEvent eNotify_OnDisplayRenderUpdate, // Sent when editor finish terrain texture generation. - eNotify_OnTimeOfDayChange, // Time of day parameters where modified. - eNotify_OnDataBaseUpdate, // DataBase Library was modified. eNotify_OnLayerImportBegin, //layer import was started @@ -241,8 +237,6 @@ struct IDocListener virtual void OnLoadDocument() = 0; //! Called when document is being closed. virtual void OnCloseDocument() = 0; - //! Called when mission changes. - virtual void OnMissionChange() = 0; }; //! Derive from this class if you want to register for getting global editor notifications. @@ -431,7 +425,6 @@ struct IEditor virtual void DeleteThis() = 0; //! Access to Editor ISystem interface. virtual ISystem* GetSystem() = 0; - virtual I3DEngine* Get3DEngine() = 0; virtual IRenderer* GetRenderer() = 0; //! Access to class factory. virtual IEditorClassFactory* GetClassFactory() = 0; @@ -739,8 +732,6 @@ struct IEditor typedef AZStd::function TContextMenuExtensionFunc; virtual void RegisterObjectContextMenuExtension(TContextMenuExtensionFunc func) = 0; - virtual void SetCurrentMissionTime(float time) = 0; - virtual SSystemGlobalEnvironment* GetEnv() = 0; virtual IImageUtil* GetImageUtil() = 0; // Vladimir@conffx virtual SEditorSettings* GetEditorSettings() = 0; diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index ff9ece339a..53a2c120c4 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -71,7 +71,6 @@ AZ_POP_DISABLE_WARNING #include "BackgroundTaskManager.h" #include "BackgroundScheduleManager.h" #include "EditorFileMonitor.h" -#include "Mission.h" #include "MainStatusBar.h" #include "SettingsBlock.h" @@ -441,15 +440,6 @@ ISystem* CEditorImpl::GetSystem() return m_pSystem; } -I3DEngine* CEditorImpl::Get3DEngine() -{ - if (gEnv) - { - return gEnv->p3DEngine; - } - return nullptr; -} - IRenderer* CEditorImpl::GetRenderer() { if (gEnv) @@ -1716,13 +1706,6 @@ void CEditorImpl::RegisterObjectContextMenuExtension(TContextMenuExtensionFunc f m_objectContextMenuExtensions.push_back(func); } -void CEditorImpl::SetCurrentMissionTime(float time) -{ - if (CMission* pMission = GetIEditor()->GetDocument()->GetCurrentMission()) - { - pMission->SetTime(time); - } -} // Vladimir@Conffx SSystemGlobalEnvironment* CEditorImpl::GetEnv() { diff --git a/Code/Sandbox/Editor/IEditorImpl.h b/Code/Sandbox/Editor/IEditorImpl.h index d17a94807f..bbef338cb2 100644 --- a/Code/Sandbox/Editor/IEditorImpl.h +++ b/Code/Sandbox/Editor/IEditorImpl.h @@ -116,7 +116,6 @@ public: bool IsInitialized() const{ return m_bInitialized; } bool SaveDocument(); ISystem* GetSystem(); - I3DEngine* Get3DEngine(); IRenderer* GetRenderer(); void WriteToConsole(const char* string) { CLogFile::WriteLine(string); }; void WriteToConsole(const QString& string) { CLogFile::WriteLine(string); }; @@ -321,7 +320,6 @@ public: void OnObjectContextMenuOpened(QMenu* pMenu, const CBaseObject* pObject); virtual void RegisterObjectContextMenuExtension(TContextMenuExtensionFunc func) override; - virtual void SetCurrentMissionTime(float time); virtual SSystemGlobalEnvironment* GetEnv() override; virtual IBaseLibraryManager* GetMaterialManagerLibrary() override; // Vladimir@Conffx virtual IEditorMaterialManager* GetIEditorMaterialManager() override; // Vladimir@Conffx diff --git a/Code/Sandbox/Editor/IconManager.cpp b/Code/Sandbox/Editor/IconManager.cpp index 828a7cdfcc..e06b89b38e 100644 --- a/Code/Sandbox/Editor/IconManager.cpp +++ b/Code/Sandbox/Editor/IconManager.cpp @@ -25,6 +25,7 @@ #include "Util/Image.h" #include "Util/ImageUtil.h" +#include #define HELPER_MATERIAL "Objects/Helper" @@ -76,12 +77,11 @@ void CIconManager::Done() ////////////////////////////////////////////////////////////////////////// void CIconManager::Reset() { - I3DEngine* pEngine = GetIEditor()->Get3DEngine(); // Do not unload objects. but clears them. int i; for (i = 0; i < sizeof(m_objects) / sizeof(m_objects[0]); i++) { - if (m_objects[i] && pEngine) + if (m_objects[i]) { m_objects[i]->Release(); } @@ -130,39 +130,10 @@ int CIconManager::GetIconTexture(EIcon icon) return m_icons[icon]; } - ////////////////////////////////////////////////////////////////////////// -_smart_ptr CIconManager::GetHelperMaterial() +IStatObj* CIconManager::GetObject(EStatObject) { - if (!m_pHelperMtl) - { - m_pHelperMtl = GetIEditor()->Get3DEngine()->GetMaterialManager()->LoadMaterial(HELPER_MATERIAL); - } - return m_pHelperMtl; -}; - -////////////////////////////////////////////////////////////////////////// -IStatObj* CIconManager::GetObject(EStatObject object) -{ - assert(object >= 0 && object < eStatObject_COUNT); - - if (m_objects[object]) - { - return m_objects[object]; - } - - // Try to load this object. - m_objects[object] = GetIEditor()->Get3DEngine()->LoadStatObjUnsafeManualRef(g_ObjectNames[object], NULL, NULL, false); - if (!m_objects[object]) - { - CLogFile::FormatLine("Error: Load Failed: %s", g_ObjectNames[object]); - } - m_objects[object]->AddRef(); - if (GetHelperMaterial()) - { - m_objects[object]->SetMaterial(GetHelperMaterial()); - } - return m_objects[object]; + return nullptr; } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/IconManager.h b/Code/Sandbox/Editor/IconManager.h index 641e3f70a7..6c86627f3a 100644 --- a/Code/Sandbox/Editor/IconManager.h +++ b/Code/Sandbox/Editor/IconManager.h @@ -51,7 +51,6 @@ public: virtual IStatObj* GetObject(EStatObject object); virtual int GetIconTexture(const char* iconName); - virtual _smart_ptr GetHelperMaterial(); ////////////////////////////////////////////////////////////////////////// // Icon bitmaps. @@ -64,14 +63,11 @@ public: virtual void OnNewDocument() { Reset(); }; virtual void OnLoadDocument() { Reset(); }; virtual void OnCloseDocument() { Reset(); }; - virtual void OnMissionChange() { Reset(); }; ////////////////////////////////////////////////////////////////////////// private: StdMap m_textures; - _smart_ptr m_pHelperMtl; - IStatObj* m_objects[eStatObject_COUNT]; int m_icons[eIcon_COUNT]; diff --git a/Code/Sandbox/Editor/Include/IIconManager.h b/Code/Sandbox/Editor/Include/IIconManager.h index 115d998be3..15ef37e23b 100644 --- a/Code/Sandbox/Editor/Include/IIconManager.h +++ b/Code/Sandbox/Editor/Include/IIconManager.h @@ -61,7 +61,6 @@ struct IIconManager virtual IStatObj* GetObject(EStatObject object) = 0; virtual int GetIconTexture(EIcon icon) = 0; virtual int GetIconTexture(const char* iconName) = 0; - virtual _smart_ptr GetHelperMaterial() = 0; virtual QImage* GetIconBitmap(const char* filename, bool& haveAlpha, uint32 effects = 0) = 0; // Register an Icon for the specific command virtual void RegisterCommandIcon([[maybe_unused]] const char* filename, [[maybe_unused]] int nCommandId) {} diff --git a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h index 6659e41122..4a20bd6b60 100644 --- a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h @@ -32,7 +32,6 @@ public: public: MOCK_METHOD0(DeleteThis, void()); MOCK_METHOD0(GetSystem, ISystem*()); - MOCK_METHOD0(Get3DEngine, I3DEngine* ()); MOCK_METHOD0(GetRenderer, IRenderer* ()); MOCK_METHOD0(GetClassFactory, IEditorClassFactory* ()); MOCK_METHOD0(GetCommandManager, CEditorCommandManager*()); @@ -191,7 +190,6 @@ public: MOCK_METHOD0(GetBackgroundScheduleManager, struct IBackgroundScheduleManager* ()); MOCK_METHOD1(ShowStatusText, void(bool )); MOCK_METHOD1(RegisterObjectContextMenuExtension, void(TContextMenuExtensionFunc )); - MOCK_METHOD1(SetCurrentMissionTime, void(float )); MOCK_METHOD0(GetEnv, SSystemGlobalEnvironment* ()); MOCK_METHOD0(GetImageUtil, IImageUtil* ()); MOCK_METHOD0(GetEditorSettings, SEditorSettings* ()); diff --git a/Code/Sandbox/Editor/LyViewPaneNames.h b/Code/Sandbox/Editor/LyViewPaneNames.h index fdbf8bf90c..e95191ce06 100644 --- a/Code/Sandbox/Editor/LyViewPaneNames.h +++ b/Code/Sandbox/Editor/LyViewPaneNames.h @@ -44,7 +44,6 @@ namespace LyViewPane static const char* const TerrainTool = "Terrain Tool"; static const char* const TerrainTextureLayers = "Terrain Texture Layers"; static const char* const ParticleEditor = "Particle Editor"; - static const char* const TimeOfDayEditor = "Time Of Day"; static const char* const AudioControlsEditor = "Audio Controls Editor"; static const char* const SubstanceEditor = "Substance Editor"; static const char* const VegetationEditor = "Vegetation Editor"; diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index c54c31c5d5..895df4214f 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -90,7 +90,6 @@ AZ_POP_DISABLE_WARNING #include "TrackView/TrackViewDialog.h" #include "ErrorReportDialog.h" -#include "TimeOfDayDialog.h" #include "Dialogs/PythonScriptsDialog.h" #include "EngineSettingsManager.h" @@ -1078,8 +1077,6 @@ void MainWindow::InitActions() // Tools actions am->AddAction(ID_RELOAD_TEXTURES, tr("Reload Textures/Shaders")) .SetStatusTip(tr("Reload all textures.")); - am->AddAction(ID_RELOAD_GEOMETRY, tr("Reload Geometry")) - .SetStatusTip(tr("Reload all geometries.")); am->AddAction(ID_TOOLS_ENABLEFILECHANGEMONITORING, tr("Enable File Change Monitoring")); am->AddAction(ID_CLEAR_REGISTRY, tr("Clear Registry Data")) .SetStatusTip(tr("Clear Registry Data")); @@ -1352,12 +1349,6 @@ void MainWindow::InitEnvironmentModeMenu(CVarMenu* environmentModeMenu) environmentModeMenu->AddCVarToggleItem({ "r_ssdo", tr("Hide Screen Space Directional Occlusion"), 0, 1 }); environmentModeMenu->AddCVarToggleItem({ "e_DynamicLights", tr("Hide All Dynamic Lights"), 0, 1 }); environmentModeMenu->AddSeparator(); - environmentModeMenu->AddCVarValuesItem("e_TimeOfDay", tr("Time of Day"), - { - {tr("Day (1:00 pm)"), 13}, - {tr("Night (9:00 pm)"), 21} - }, 9); - environmentModeMenu->AddSeparator(); environmentModeMenu->AddCVarToggleItem({ "e_Entities", tr("Hide Entities"), 0, 1 }); environmentModeMenu->AddSeparator(); environmentModeMenu->AddCVarToggleItem({ "e_Vegetation", tr("Hide Vegetation"), 0, 1 }); diff --git a/Code/Sandbox/Editor/Mission.cpp b/Code/Sandbox/Editor/Mission.cpp deleted file mode 100644 index b9668f1c80..0000000000 --- a/Code/Sandbox/Editor/Mission.cpp +++ /dev/null @@ -1,364 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : CMission class implementation. - -#include "EditorDefs.h" - -#include "Mission.h" - -// cryCommon -#include -#include - -// Editor -#include "CryEditDoc.h" -#include "GameEngine.h" -#include "Include/IObjectManager.h" - - -namespace -{ - const char* kTimeOfDayFile = "TimeOfDay.xml"; - const char* kTimeOfDayRoot = "TimeOfDay"; - const char* kEnvironmentFile = "Environment.xml"; - const char* kEnvironmentRoot = "Environment"; -}; - - -////////////////////////////////////////////////////////////////////////// -CMission::CMission(CCryEditDoc* doc) -{ - m_doc = doc; - m_objects = XmlHelpers::CreateXmlNode("Objects"); - m_layers = XmlHelpers::CreateXmlNode("ObjectLayers"); - //m_exportData = XmlNodeRef( "ExportData" ); - m_timeOfDay = XmlHelpers::CreateXmlNode("TimeOfDay"); - m_environment = XmlHelpers::CreateXmlNode("Environment"); - CXmlTemplate::SetValues(m_doc->GetEnvironmentTemplate(), m_environment); - - m_time = 12; // 12 PM by default. - - m_numCGFObjects = 0; - - m_reentrancyProtector = false; -} - -////////////////////////////////////////////////////////////////////////// -CMission::~CMission() -{ -} - -////////////////////////////////////////////////////////////////////////// -CMission* CMission::Clone() -{ - CMission* m = new CMission(m_doc); - m->SetName(m_name); - m->SetDescription(m_description); - m->m_objects = m_objects->clone(); - m->m_layers = m_layers->clone(); - m->m_environment = m_environment->clone(); - m->m_time = m_time; - return m; -} - -////////////////////////////////////////////////////////////////////////// -void CMission::Serialize(CXmlArchive& ar, bool bParts) -{ - if (ar.bLoading) - { - // Load. - ar.root->getAttr("Name", m_name); - ar.root->getAttr("Description", m_description); - - XmlNodeRef objects = ar.root->findChild("Objects"); - if (objects) - { - m_objects = objects; - } - - XmlNodeRef layers = ar.root->findChild("ObjectLayers"); - if (layers) - { - m_layers = layers; - } - - SerializeTimeOfDay(ar); - - m_Animations = ar.root->findChild("MovieData"); - - SerializeEnvironment(ar); - } - else - { - ar.root->setAttr("Name", m_name.toUtf8().data()); - ar.root->setAttr("Description", m_description.toUtf8().data()); - - QString timeStr; - int nHour = floor(m_time); - int nMins = (m_time - floor(m_time)) * 60.0f; - timeStr = QStringLiteral("%1:%2").arg(nHour, 2, 10, QLatin1Char('0')).arg(nMins, 2, 10, QLatin1Char('0')); - ar.root->setAttr("MissionTime", timeStr.toUtf8().data()); - - // Saving. - XmlNodeRef layers = m_layers->clone(); - layers->setTag("ObjectLayers"); - ar.root->addChild(layers); - - ///XmlNodeRef objects = m_objects->clone(); - m_objects->setTag("Objects"); - ar.root->addChild(m_objects); - - if (bParts) - { - SerializeTimeOfDay(ar); - SerializeEnvironment(ar); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMission::Export(XmlNodeRef& root, XmlNodeRef& objectsNode) -{ - // Also save exported objects data. - root->setAttr("Name", m_name.toUtf8().data()); - root->setAttr("Description", m_description.toUtf8().data()); - - QString timeStr; - int nHour = floor(m_time); - int nMins = (m_time - floor(m_time)) * 60.0f; - timeStr = QStringLiteral("%1:%2").arg(nHour, 2, 10, QLatin1Char('0')).arg(nMins, 2, 10, QLatin1Char('0')); - root->setAttr("Time", timeStr.toUtf8().data()); - - // Saving. - //XmlNodeRef objects = m_exportData->clone(); - //objects->setTag( "Objects" ); - //root->addChild( objects ); - - XmlNodeRef envNode = m_environment->clone(); - root->addChild(envNode); - - m_timeOfDay->setAttr("Time", m_time); - root->addChild(m_timeOfDay); - - IObjectManager* pObjMan = GetIEditor()->GetObjectManager(); - - ////////////////////////////////////////////////////////////////////////// - // Serialize objects. - ////////////////////////////////////////////////////////////////////////// - QString path = QDir::toNativeSeparators(QFileInfo(m_doc->GetLevelPathName()).absolutePath()); - if (!path.endsWith(QDir::separator())) - path += QDir::separator(); - - objectsNode = root->newChild("Objects"); - pObjMan->Export(path, objectsNode, true); // Export shared. - pObjMan->Export(path, objectsNode, false); // Export not shared. -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SyncContent(bool bRetrieve, bool bIgnoreObjects, [[maybe_unused]] bool bSkipLoadingAI /* = false */) -{ - // The function may take a longer time when executing objMan->Serialize, which uses CWaitProgress internally - // Adding a sync flag to prevent the function from being re-entered after the data is modified by OnEnvironmentChange - if (m_reentrancyProtector) - { - return; - } - m_reentrancyProtector = true; - - // Save data from current Document to Mission. - IObjectManager* objMan = GetIEditor()->GetObjectManager(); - if (bRetrieve) - { - // Activating this mission. - CGameEngine* gameEngine = GetIEditor()->GetGameEngine(); - - if (!bIgnoreObjects) - { - // Retrieve data from Mission and put to document. - XmlNodeRef root = XmlHelpers::CreateXmlNode("Root"); - root->addChild(m_objects); - root->addChild(m_layers); - objMan->Serialize(root, true, SERIALIZE_ONLY_NOTSHARED); - } - - m_doc->GetFogTemplate() = m_environment; - - CXmlTemplate::GetValues(m_doc->GetEnvironmentTemplate(), m_environment); - - gameEngine->ReloadEnvironment(); - - objMan->SendEvent(EVENT_MISSION_CHANGE); - m_doc->ChangeMission(); - - if (GetIEditor()->Get3DEngine()) - { - m_numCGFObjects = GetIEditor()->Get3DEngine()->GetLoadedObjectCount(); - - // Load time of day. - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_timeOfDay, true); - } - } - else - { - // Save time of day. - if (GetIEditor()->Get3DEngine()) - { - m_timeOfDay = XmlHelpers::CreateXmlNode("TimeOfDay"); - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_timeOfDay, false); - } - - if (!bIgnoreObjects) - { - XmlNodeRef root = XmlHelpers::CreateXmlNode("Root"); - objMan->Serialize(root, false, SERIALIZE_ONLY_NOTSHARED); - m_objects = root->findChild("Objects"); - XmlNodeRef layers = root->findChild("ObjectLayers"); - if (layers) - { - m_layers = layers; - } - } - } - - m_reentrancyProtector = false; -} - -////////////////////////////////////////////////////////////////////////// -void CMission::OnEnvironmentChange() -{ - // Only execute the reload function if there is no ongoing SyncContent. - if (m_reentrancyProtector) - { - return; - } - m_reentrancyProtector = true; - m_environment = XmlHelpers::CreateXmlNode("Environment"); - CXmlTemplate::SetValues(m_doc->GetEnvironmentTemplate(), m_environment); - m_reentrancyProtector = false; -} - -////////////////////////////////////////////////////////////////////////// -void CMission::AddObjectsNode(XmlNodeRef& node) -{ - for (int i = 0; i < node->getChildCount(); i++) - { - m_objects->addChild(node->getChild(i)->clone()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SetLayersNode(XmlNodeRef& node) -{ - m_layers = node->clone(); -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SaveParts() -{ - // Save Time of Day - { - CTempFileHelper helper((GetIEditor()->GetLevelDataFolder() + kTimeOfDayFile).toUtf8().data()); - - m_timeOfDay->saveToFile(helper.GetTempFilePath().toUtf8().data()); - - if (!helper.UpdateFile(false)) - { - return; - } - } - - - // Save Environment - { - CTempFileHelper helper((GetIEditor()->GetLevelDataFolder() + kEnvironmentFile).toUtf8().data()); - - XmlNodeRef root = m_environment->clone(); - root->setTag(kEnvironmentRoot); - root->saveToFile(helper.GetTempFilePath().toUtf8().data()); - - if (!helper.UpdateFile(false)) - { - return; - } - } -} - - -////////////////////////////////////////////////////////////////////////// -void CMission::LoadParts() -{ - // Load Time of Day - { - QString filename = GetIEditor()->GetLevelDataFolder() + kTimeOfDayFile; - XmlNodeRef root = XmlHelpers::LoadXmlFromFile(filename.toUtf8().data()); - if (root && !_stricmp(root->getTag(), kTimeOfDayRoot)) - { - m_timeOfDay = root; - m_timeOfDay->getAttr("Time", m_time); - } - } - - // Load Environment - { - QString filename = GetIEditor()->GetLevelDataFolder() + kEnvironmentFile; - XmlNodeRef root = XmlHelpers::LoadXmlFromFile(filename.toUtf8().data()); - if (root && !_stricmp(root->getTag(), kEnvironmentRoot)) - { - m_environment = root; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SerializeTimeOfDay(CXmlArchive& ar) -{ - if (ar.bLoading) - { - XmlNodeRef todNode = ar.root->findChild("TimeOfDay"); - if (todNode) - { - m_timeOfDay = todNode; - todNode->getAttr("Time", m_time); - } - else - { - m_timeOfDay = XmlHelpers::CreateXmlNode("TimeOfDay"); - } - } - else - { - m_timeOfDay->setAttr("Time", m_time); - ar.root->addChild(m_timeOfDay); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMission::SerializeEnvironment(CXmlArchive& ar) -{ - if (ar.bLoading) - { - XmlNodeRef env = ar.root->findChild("Environment"); - if (env) - { - m_environment = env; - } - } - else - { - XmlNodeRef env = m_environment->clone(); - env->setTag("Environment"); - ar.root->addChild(env); - } -} - diff --git a/Code/Sandbox/Editor/Mission.h b/Code/Sandbox/Editor/Mission.h deleted file mode 100644 index f0773a0be7..0000000000 --- a/Code/Sandbox/Editor/Mission.h +++ /dev/null @@ -1,105 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Mission class definition. - -#pragma once - - -/*! - CMission represent single Game Mission on same map. - Multiple Missions share same map, and stored in one .cry or .ly file. - - */ -class CMission -{ -public: - //! Ctor of mission. - CMission(CCryEditDoc* doc); - //! Dtor of mission. - virtual ~CMission(); - - void SetName(const QString& name) { m_name = name; } - const QString& GetName() const { return m_name; } - - void SetDescription(const QString& dsc) { m_description = dsc; } - const QString& GetDescription() const { return m_description; } - - XmlNodeRef GetEnvironment() { return m_environment; }; - - void SetTime(float time) { m_time = time; }; - float GetTime() const { return m_time; }; - - //! Called when this mission must be synchonized with current data in Document. - //! if bRetrieve is true, data is retrieved from Mission to global structures. - void SyncContent(bool bRetrieve, bool bIgnoreObjects, bool bSkipLoadingAI = false); - - //! Create clone of this mission. - CMission* Clone(); - - //! Serialize mission. - void Serialize(CXmlArchive& ar, bool bParts = true); - - //! Serialize time of day - void SerializeTimeOfDay(CXmlArchive& ar); - - //! Serialize environment - void SerializeEnvironment(CXmlArchive& ar); - - //! Save some elements of mission to separate files - void SaveParts(); - - //! Load some elements of mission from separate files - void LoadParts(); - - //! Export mission to game. - void Export(XmlNodeRef& root, XmlNodeRef& objectsNode); - - //! Add shared objects to mission objects. - void AddObjectsNode(XmlNodeRef& node); - void SetLayersNode(XmlNodeRef& node); - - void OnEnvironmentChange(); - int GetNumCGFObjects() const { return m_numCGFObjects; }; - -private: - //! Document owner of this mission. - CCryEditDoc* m_doc; - - QString m_name; - QString m_description; - - //! Mission time; - float m_time; - - //! Root node of objects defined only in this mission. - XmlNodeRef m_objects; - - //! Object layers. - XmlNodeRef m_layers; - - //! Exported data of this mission. - XmlNodeRef m_exportData; - - //! Environment settings of this mission. - XmlNodeRef m_environment; - - XmlNodeRef m_Animations; // backward compatibility. - - XmlNodeRef m_timeOfDay; - - int m_numCGFObjects; - - bool m_reentrancyProtector; -}; - diff --git a/Code/Sandbox/Editor/ModelViewport.cpp b/Code/Sandbox/Editor/ModelViewport.cpp deleted file mode 100644 index 2e00adb4fc..0000000000 --- a/Code/Sandbox/Editor/ModelViewport.cpp +++ /dev/null @@ -1,961 +0,0 @@ - -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "ModelViewport.h" - -// Qt -#include -#include - -// CryCommon -#include - -#include "CryPhysicsDeprecation.h" - - -// Editor -#include "ThumbnailGenerator.h" // for CThumbnailGenerator -#include "FileTypeUtils.h" // for IsPreviewableFileType -#include "ErrorRecorder.h" - - - - - -uint32 g_ypos = 0; - -#define SKYBOX_NAME "InfoRedGal" - -///////////////////////////////////////////////////////////////////////////// -// CModelViewport - -CModelViewport::CModelViewport(const char* settingsPath, QWidget* parent) - : CRenderViewport(tr("Model View"), parent) -{ - m_settingsPath = QString::fromLatin1(settingsPath); - - m_bPaused = false; - - m_Camera.SetFrustum(800, 600, 3.14f / 4.0f, 0.02f, 10000); - - m_bInRotateMode = false; - m_bInMoveMode = false; - - m_object = 0; - - - m_weaponModel = 0; - - m_camRadius = 10; - - m_moveSpeed = 0.1f; - m_LightRotationRadian = 0.0f; - - m_weaponIK = false; - - m_pRESky = 0; - m_pSkyboxName = 0; - m_pSkyBoxShader = NULL; - - m_attachBone = QStringLiteral("weapon_bone"); - - // Init variable. - mv_objectAmbientColor = Vec3(0.25f, 0.25f, 0.25f); - mv_backgroundColor = Vec3(0.25f, 0.25f, 0.25f); - - mv_lightDiffuseColor = Vec3(0.70f, 0.70f, 0.70f); - mv_lightMultiplier = 3.0f; - mv_lightOrbit = 15.0f; - mv_lightRadius = 400.0f; - mv_lightSpecMultiplier = 1.0f; - - mv_showPhysics = false; - - m_GridOrigin = Vec3(ZERO); - m_arrAnimatedCharacterPath.resize(0x200, ZERO); - m_arrSmoothEntityPath.resize(0x200, ZERO); - - m_arrRunStrafeSmoothing.resize(0x100); - SetPlayerPos(); - - // cache all the variable callbacks, must match order of enum defined in header - m_onSetCallbacksCache.push_back(AZStd::bind(&CModelViewport::OnCharPhysics, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CModelViewport::OnLightColor, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CModelViewport::OnLightMultiplier, this, AZStd::placeholders::_1)); - m_onSetCallbacksCache.push_back(AZStd::bind(&CModelViewport::OnShowShaders, this, AZStd::placeholders::_1)); - - //-------------------------------------------------- - // Register variables. - //-------------------------------------------------- - m_vars.AddVariable(mv_showPhysics, "Display Physics"); - m_vars.AddVariable(mv_useCharPhysics, "Use Character Physics", &m_onSetCallbacksCache[VariableCallbackIndex::OnCharPhysics]); - mv_useCharPhysics = true; - m_vars.AddVariable(mv_showGrid, "ShowGrid"); - mv_showGrid = true; - m_vars.AddVariable(mv_showBase, "ShowBase"); - mv_showBase = false; - m_vars.AddVariable(mv_showLocator, "ShowLocator"); - mv_showLocator = 0; - m_vars.AddVariable(mv_InPlaceMovement, "InPlaceMovement"); - mv_InPlaceMovement = false; - m_vars.AddVariable(mv_StrafingControl, "StrafingControl"); - mv_StrafingControl = false; - - m_vars.AddVariable(mv_lighting, "Lighting"); - mv_lighting = true; - m_vars.AddVariable(mv_animateLights, "AnimLights"); - - m_vars.AddVariable(mv_backgroundColor, "BackgroundColor", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightColor], IVariable::DT_COLOR); - m_vars.AddVariable(mv_objectAmbientColor, "ObjectAmbient", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightColor], IVariable::DT_COLOR); - - m_vars.AddVariable(mv_lightDiffuseColor, "LightDiffuse", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightColor], IVariable::DT_COLOR); - m_vars.AddVariable(mv_lightMultiplier, "Light Multiplier", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightMultiplier], IVariable::DT_SIMPLE); - m_vars.AddVariable(mv_lightSpecMultiplier, "Light Specular Multiplier", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightMultiplier], IVariable::DT_SIMPLE); - m_vars.AddVariable(mv_lightRadius, "Light Radius", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightMultiplier], IVariable::DT_SIMPLE); - m_vars.AddVariable(mv_lightOrbit, "Light Orbit", &m_onSetCallbacksCache[VariableCallbackIndex::OnLightMultiplier], IVariable::DT_SIMPLE); - - m_vars.AddVariable(mv_showWireframe1, "ShowWireframe1"); - m_vars.AddVariable(mv_showWireframe2, "ShowWireframe2"); - m_vars.AddVariable(mv_showTangents, "ShowTangents"); - m_vars.AddVariable(mv_showBinormals, "ShowBinormals"); - m_vars.AddVariable(mv_showNormals, "ShowNormals"); - - m_vars.AddVariable(mv_showSkeleton, "ShowSkeleton"); - m_vars.AddVariable(mv_showJointNames, "ShowJointNames"); - m_vars.AddVariable(mv_showJointsValues, "ShowJointsValues"); - m_vars.AddVariable(mv_showStartLocation, "ShowInvStartLocation"); - m_vars.AddVariable(mv_showMotionParam, "ShowMotionParam"); - m_vars.AddVariable(mv_printDebugText, "PrintDebugText"); - - m_vars.AddVariable(mv_UniformScaling, "UniformScaling"); - mv_UniformScaling = 1.0f; - mv_UniformScaling.SetLimits(0.01f, 2.0f); - m_vars.AddVariable(mv_forceLODNum, "ForceLODNum"); - mv_forceLODNum = 0; - mv_forceLODNum.SetLimits(0, 10); - m_vars.AddVariable(mv_showShaders, "ShowShaders", &m_onSetCallbacksCache[VariableCallbackIndex::OnShowShaders]); - m_vars.AddVariable(mv_AttachCamera, "AttachCamera"); - - m_vars.AddVariable(mv_fov, "FOV"); - mv_fov = 60; - mv_fov.SetLimits(1, 120); - - RestoreDebugOptions(); - - m_camRadius = 10; - - //YPR_Angle = Ang3(0,-1.0f,0); - //SetViewTM( Matrix34(CCamera::CreateOrientationYPR(YPR_Angle), Vec3(0,-m_camRadius,0)) ); - Vec3 camPos = Vec3(10, 10, 10); - Matrix34 tm = Matrix33::CreateRotationVDir((Vec3(0, 0, 0) - camPos).GetNormalized()); - tm.SetTranslation(camPos); - SetViewTM(tm); - - - m_AABB.Reset(); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::SaveDebugOptions() const -{ - QSettings settings; - for (auto g : m_settingsPath.split('\\')) - settings.beginGroup(g); - - CVarBlock* vb = GetVarObject()->GetVarBlock(); - int32 vbCount = vb->GetNumVariables(); - - settings.setValue("iDebugOptionCount", vbCount); - - char keyType[64], keyValue[64]; - for (int32 i = 0; i < vbCount; ++i) - { - IVariable* var = vb->GetVariable(i); - IVariable::EType vType = var->GetType(); - sprintf_s(keyType, "DebugOption_%s_type", var->GetName().toUtf8().data()); - sprintf_s(keyValue, "DebugOption_%s_value", var->GetName().toUtf8().data()); - switch (vType) - { - case IVariable::UNKNOWN: - { - break; - } - case IVariable::INT: - { - int32 value = 0; - var->Get(value); - settings.setValue(keyType, IVariable::INT); - settings.setValue(keyValue, value); - - break; - } - case IVariable::BOOL: - { - bool value = 0; - var->Get(value); - settings.setValue(keyType, IVariable::BOOL); - settings.setValue(keyValue, value); - break; - } - case IVariable::FLOAT: - { - f32 value = 0; - var->Get(value); - settings.setValue(keyType, IVariable::FLOAT); - settings.setValue(keyValue, value); - break; - } - case IVariable::VECTOR: - { - Vec3 value; - var->Get(value); - f32 valueArray[3]; - valueArray[0] = value.x; - valueArray[1] = value.y; - valueArray[2] = value.z; - settings.setValue(keyType, IVariable::VECTOR); - settings.setValue(keyValue, QByteArray(reinterpret_cast(&value), 3 * sizeof(f32))); - - break; - } - case IVariable::QUAT: - { - Quat value; - var->Get(value); - f32 valueArray[4]; - valueArray[0] = value.w; - valueArray[1] = value.v.x; - valueArray[2] = value.v.y; - valueArray[3] = value.v.z; - - settings.setValue(keyType, IVariable::QUAT); - settings.setValue(keyValue, QByteArray(reinterpret_cast(&value), 4 * sizeof(f32))); - - break; - } - case IVariable::STRING: - { - QString value; - var->Get(value); - settings.setValue(keyType, IVariable::STRING); - settings.setValue(keyValue, value); - - break; - } - case IVariable::ARRAY: - { - break; - } - default: - break; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::RestoreDebugOptions() -{ - QSettings settings; - for (auto g : m_settingsPath.split('\\')) - settings.beginGroup(g); - - QString strRead = ""; - int32 iRead = 0; - BOOL bRead = FALSE; - f32 fRead = .0f; - QByteArray pbtData; - - CVarBlock* vb = m_vars.GetVarBlock(); - int32 vbCount = vb->GetNumVariables(); - - char keyType[64], keyValue[64]; - for (int32 i = 0; i < vbCount; ++i) - { - IVariable* var = vb->GetVariable(i); - sprintf_s(keyType, "DebugOption_%s_type", var->GetName().toUtf8().data()); - - int32 iType = settings.value(keyType, 0).toInt(); - - sprintf_s(keyValue, "DebugOption_%s_value", var->GetName().toUtf8().data()); - switch (iType) - { - case IVariable::UNKNOWN: - { - break; - } - case IVariable::INT: - { - iRead = settings.value(keyValue, 0).toInt(); - var->Set(iRead); - break; - } - case IVariable::BOOL: - { - bRead = settings.value(keyValue, FALSE).toBool(); - var->Set(bRead); - break; - } - case IVariable::FLOAT: - { - fRead = settings.value(keyValue).toDouble(); - var->Set(fRead); - break; - } - case IVariable::VECTOR: - { - pbtData = settings.value(keyValue).toByteArray(); - assert(pbtData.count() == 3 * sizeof(f32)); - f32* pfRead = reinterpret_cast(pbtData.data()); - - Vec3 vecRead(pfRead[0], pfRead[1], pfRead[2]); - var->Set(vecRead); - break; - } - case IVariable::QUAT: - { - pbtData = settings.value(keyValue).toByteArray(); - assert(pbtData.count() == 4 * sizeof(f32)); - f32* pfRead = reinterpret_cast(pbtData.data()); - - Quat valueRead(pfRead[0], pfRead[1], pfRead[2], pfRead[3]); - var->Set(valueRead); - break; - } - case IVariable::STRING: - { - strRead = settings.value(keyValue, "").toString(); - var->Set(strRead); - break; - } - case IVariable::ARRAY: - { - break; - } - default: - break; - } - } -} - -////////////////////////////////////////////////////////////////////////// -CModelViewport::~CModelViewport() -{ - OnDestroy(); - ReleaseObject(); - - GetIEditor()->FlushUndo(); - - SaveDebugOptions(); - - // helper offset?? - CRY_PHYSICS_REPLACEMENT_ASSERT(); - GetIEditor()->SetConsoleVar("ca_UsePhysics", 1); -} - -///////////////////////////////////////////////////////////////////////////// -// CModelViewport message handlers -///////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -void CModelViewport::ReleaseObject() -{ - if (m_object) - { - m_object->Release(); - m_object = NULL; - } - - if (m_weaponModel) - { - m_weaponModel->Release(); - m_weaponModel = NULL; - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::LoadObject(const QString& fileName, [[maybe_unused]] float scale) -{ - m_bPaused = false; - - // Load object. - QString file = Path::MakeGamePath(fileName); - - bool reload = false; - if (m_loadedFile == file) - { - reload = true; - } - m_loadedFile = file; - - SetName(tr("Model View - %1").arg(file)); - - ReleaseObject(); - - // Enables display of warning after model have been loaded. - CErrorsRecorder errRecorder; - - if (IsPreviewableFileType(file.toUtf8().data())) - { - const QString fileExt = QFileInfo(file).completeSuffix(); - // Try Load character. - const bool isSKEL = (0 == fileExt.compare(CRY_SKEL_FILE_EXT, Qt::CaseInsensitive)); - const bool isSKIN = (0 == fileExt.compare(CRY_SKIN_FILE_EXT, Qt::CaseInsensitive)); - const bool isCGA = (0 == fileExt.compare(CRY_ANIM_GEOMETRY_FILE_EXT, Qt::CaseInsensitive)); - const bool isCDF = (0 == fileExt.compare(CRY_CHARACTER_DEFINITION_FILE_EXT, Qt::CaseInsensitive)); - if (isSKEL || isSKIN || isCGA || isCDF) - { - } - else - { - LoadStaticObject(file); - } - } - else - { - QMessageBox::warning(this, tr("Preview Error"), tr("Preview of this file type not supported.")); - return; - } - - //-------------------------------------------------------------------------------- - - if (!reload) - { - Vec3 v = m_AABB.max - m_AABB.min; - float radius = v.GetLength() / 2.0f; - m_camRadius = radius * 2; - } - - if (GetIEditor()->IsInPreviewMode()) - { - Physicalize(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::LoadStaticObject(const QString& file) -{ - if (m_object) - { - m_object->Release(); - } - - // Load Static object. - m_object = m_engine->LoadStatObjUnsafeManualRef(file.toUtf8().data(), 0, 0, false); - - if (!m_object) - { - CLogFile::WriteLine("Loading of object failed."); - return; - } - m_object->AddRef(); - - // Generate thumbnail for this cgf. - CThumbnailGenerator thumbGen; - thumbGen.GenerateForFile(file); - - m_AABB.min = m_object->GetBoxMin(); - m_AABB.max = m_object->GetBoxMax(); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnRender() -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - const QRect rc = contentsRect(); - ProcessKeys(); - if (m_renderer) - { - PreWidgetRendering(); - - m_Camera.SetFrustum(m_Camera.GetViewSurfaceX(), m_Camera.GetViewSurfaceZ(), m_Camera.GetFov(), 0.02f, 10000, m_Camera.GetPixelAspectRatio()); - const int w = rc.width(); - const int h = rc.height(); - m_Camera.SetFrustum(w, h, DEG2RAD(mv_fov), 0.0101f, 10000.0f); - - if (GetIEditor()->IsInPreviewMode()) - { - GetISystem()->SetViewCamera(m_Camera); - } - - Vec3 clearColor = mv_backgroundColor; - m_renderer->SetClearColor(clearColor); - m_renderer->SetCamera(m_Camera); - - auto colorf = ColorF(clearColor, 1.0f); - m_renderer->ClearTargetsImmediately(FRT_CLEAR | FRT_CLEAR_IMMEDIATE, colorf); - m_renderer->ResetToDefault(); - - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_Camera, SRenderingPassInfo::DEFAULT_FLAGS, true); - - { - CScopedWireFrameMode scopedWireFrame(m_renderer, mv_showWireframe1 ? R_WIREFRAME_MODE : R_SOLID_MODE); - DrawModel(passInfo); - } - - PostWidgetRendering(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::DrawSkyBox(const SRenderingPassInfo& passInfo) -{ - CRenderObject* pObj = m_renderer->EF_GetObject_Temp(passInfo.ThreadID()); - pObj->m_II.m_Matrix.SetTranslationMat(GetViewTM().GetTranslation()); - - if (m_pSkyboxName) - { - SShaderItem skyBoxShaderItem(m_pSkyBoxShader); - m_renderer->EF_AddEf(m_pRESky, skyBoxShaderItem, pObj, passInfo, EFSLIST_GENERAL, 1, SRendItemSorter::CreateRendItemSorter(passInfo)); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimBack() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimFastBack() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimFastForward() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimFront() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnAnimPlay() -{ - // TODO: Add your command handler code here -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::mouseDoubleClickEvent(QMouseEvent* event) -{ - // TODO: Add your message handler code here and/or call default - - CRenderViewport::mouseDoubleClickEvent(event); - if (event->button() != Qt::LeftButton) - { - return; - } - Matrix34 tm; - tm.SetIdentity(); - SetViewTM(tm); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnLightColor([[maybe_unused]] IVariable* var) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnShowNormals([[maybe_unused]] IVariable* var) -{ - bool enable = mv_showNormals; - GetIEditor()->SetConsoleVar("r_ShowNormals", (enable) ? 1 : 0); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnShowTangents([[maybe_unused]] IVariable* var) -{ - bool enable = mv_showTangents; - GetIEditor()->SetConsoleVar("r_ShowTangents", (enable) ? 1 : 0); -} - - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnCharPhysics([[maybe_unused]] IVariable* var) -{ - bool enable = mv_useCharPhysics; - GetIEditor()->SetConsoleVar("ca_UsePhysics", enable); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnShowShaders([[maybe_unused]] IVariable* var) -{ - bool bEnable = mv_showShaders; - GetIEditor()->SetConsoleVar("r_ProfileShaders", bEnable); -} - -void CModelViewport::OnDestroy() -{ - ReleaseObject(); - if (m_pRESky) - { - m_pRESky->Release(false); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnActivate() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnDeactivate() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::Update() -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - CRenderViewport::Update(); - - DrawInfo(); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::DrawInfo() const -{ - if (GetIEditor()->Get3DEngine()) - { - ICVar* pDisplayInfo = gEnv->pConsole->GetCVar("r_DisplayInfo"); - if (pDisplayInfo && pDisplayInfo->GetIVal() != 0) - { - const float fps = gEnv->pTimer->GetFrameRate(); - const float x = (float)gEnv->pRenderer->GetWidth() - 5.0f; - - gEnv->p3DEngine->DrawTextRightAligned(x, 1, "FPS: %.2f", fps); - - int nPolygons, nShadowVolPolys; - gEnv->pRenderer->GetPolyCount(nPolygons, nShadowVolPolys); - int nDrawCalls = gEnv->pRenderer->GetCurrentNumberOfDrawCalls(); - gEnv->p3DEngine->DrawTextRightAligned(x, 20, "Tris:%2d,%03d - DP:%d", nPolygons / 1000, nPolygons % 1000, nDrawCalls); - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CModelViewport::CanDrop([[maybe_unused]] const QPoint& point, IDataBaseItem* pItem) -{ - if (!pItem) - { - return false; - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::Drop([[maybe_unused]] const QPoint& point, [[maybe_unused]] IDataBaseItem* pItem) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::Physicalize() -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::RePhysicalize() -{ - Physicalize(); -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::SetPaused(bool bPaused) -{ - //return; - if (m_bPaused != bPaused) - { - m_bPaused = bPaused; - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::DrawModel(const SRenderingPassInfo& passInfo) -{ - FUNCTION_PROFILER(GetIEditor()->GetSystem(), PROFILE_EDITOR); - - m_vCamPos = GetCamera().GetPosition(); - const QRect rc = contentsRect(); - //GetISystem()->SetViewCamera( m_Camera ); - IRenderAuxGeom* pAuxGeom = m_renderer->GetIRenderAuxGeom(); - m_renderer->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID()); - m_renderer->BeginSpawningShadowGeneratingRendItemJobs(passInfo.ThreadID()); - m_renderer->EF_ClearSkinningDataPool(); - m_renderer->EF_StartEf(passInfo); - - ////////////////////////////////////////////////////////////////////////// - // Draw lights. - ////////////////////////////////////////////////////////////////////////// - if (mv_lighting == true) - { - pAuxGeom->DrawSphere(m_VPLight.m_Origin, 0.2f, ColorB(255, 255, 0, 255)); - } - - gEnv->pConsole->GetCVar("ca_DrawWireframe")->Set(mv_showWireframe2); - gEnv->pConsole->GetCVar("ca_DrawTangents")->Set(mv_showTangents); - gEnv->pConsole->GetCVar("ca_DrawBinormals")->Set(mv_showBinormals); - gEnv->pConsole->GetCVar("ca_DrawNormals")->Set(mv_showNormals); - - DrawLights(passInfo); - - - //----------------------------------------------------------------------------- - //----- Render Static Object (handled by 3DEngine) ---- - //----------------------------------------------------------------------------- - // calculate LOD - - f32 fDistance = GetViewTM().GetTranslation().GetLength(); - SRendParams rp; - rp.fDistance = fDistance; - - Matrix34 tm; - tm.SetIdentity(); - rp.pMatrix = &tm; - rp.pPrevMatrix = &tm; - - Vec3 vAmbient; - mv_objectAmbientColor.Get(vAmbient); - - rp.AmbientColor.r = vAmbient.x * mv_lightMultiplier; - rp.AmbientColor.g = vAmbient.y * mv_lightMultiplier; - rp.AmbientColor.b = vAmbient.z * mv_lightMultiplier; - rp.AmbientColor.a = 1; - - rp.nDLightMask = 7; - if (mv_lighting == false) - { - rp.nDLightMask = 0; - } - - rp.dwFObjFlags = 0; - - //----------------------------------------------------------------------------- - //----- Render Static Object (handled by 3DEngine) ---- - //----------------------------------------------------------------------------- - if (m_object) - { - m_object->Render(rp, passInfo); - if (mv_showGrid) - { - DrawFloorGrid(Quat(IDENTITY), Vec3(ZERO), Matrix33(IDENTITY)); - } - - if (mv_showBase) - { - DrawCoordSystem(IDENTITY, 10.0f); - } - } - - m_renderer->EF_EndEf3D(SHDF_STREAM_SYNC, -1, -1, passInfo); -} - - -void CModelViewport::DrawLights(const SRenderingPassInfo& passInfo) -{ - if (mv_animateLights) - { - m_LightRotationRadian += m_AverageFrameTime; - } - - if (m_LightRotationRadian > gf_PI) - { - m_LightRotationRadian = -gf_PI; - } - - Matrix33 LightRot33 = Matrix33::CreateRotationZ(m_LightRotationRadian); - - Vec3 LPos0 = Vec3(-mv_lightOrbit, mv_lightOrbit, mv_lightOrbit); - m_VPLight.SetPosition(LightRot33 * LPos0 + m_PhysicalLocation.t); - Vec3 d = mv_lightDiffuseColor; - m_VPLight.SetLightColor(ColorF(d.x * mv_lightMultiplier, d.y * mv_lightMultiplier, d.z * mv_lightMultiplier, 0)); - m_VPLight.SetSpecularMult(mv_lightSpecMultiplier); - m_VPLight.m_fRadius = mv_lightRadius; - m_VPLight.m_Flags = DLF_SUN | DLF_DIRECTIONAL; - - if (mv_lighting == true) - { - m_renderer->EF_ADDDlight(&m_VPLight, passInfo); - } -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::PlayAnimation([[maybe_unused]] const char* szName) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::DrawFloorGrid(const Quat& m33, const Vec3& vPhysicalLocation, const Matrix33& rGridRot) -{ - if (!m_renderer) - { - return; - } - - float XR = 45; - float YR = 45; - - - - - - IRenderAuxGeom* pAuxGeom = m_renderer->GetIRenderAuxGeom(); - pAuxGeom->SetRenderFlags(e_Def3DPublicRenderflags); - - Vec3 axis = m33.GetColumn0(); - - Matrix33 SlopeMat33 = rGridRot; - uint32 GroundAlign = 1; - if (GroundAlign == 0) - { - SlopeMat33 = Matrix33::CreateRotationAA(m_absCurrentSlope, axis); - } - - - m_GridOrigin = Vec3(floorf(vPhysicalLocation.x), floorf(vPhysicalLocation.y), vPhysicalLocation.z); - - - Matrix33 ScaleMat33 = IDENTITY; - Vec3 rh = Matrix33::CreateRotationY(m_absCurrentSlope) * Vec3(1.0f, 0.0f, 0.0f); - if (rh.x) - { - Vec3 xback = SlopeMat33.GetRow(0); - Vec3 yback = SlopeMat33.GetRow(1); - f32 ratiox = 1.0f / Vec3(xback.x, xback.y, 0.0f).GetLength(); - f32 ratioy = 1.0f / Vec3(yback.x, yback.y, 0.0f).GetLength(); - - f32 ratio = 1.0f / rh.x; - // Vec3 h=Vec3((m_GridOrigin.x-vPhysicalLocation.x)*ratiox,(m_GridOrigin.y-vPhysicalLocation.y)*ratioy,0.0f); - Vec3 h = Vec3(m_GridOrigin.x - vPhysicalLocation.x, m_GridOrigin.y - vPhysicalLocation.y, 0.0f); - Vec3 nh = SlopeMat33 * h; - m_GridOrigin.z += nh.z * ratio; - - ScaleMat33 = Matrix33::CreateScale(Vec3(ratiox, ratioy, 0.0f)); - - // float color1[4] = {0,1,0,1}; - // m_renderer->Draw2dLabel(12,g_ypos,1.6f,color1,false,"h: %f %f %f h.z: %f ratio: %f ratiox: %f ratioy: %f",h.x,h.y,h.z, nh.z,ratio,ratiox,ratioy); - // g_ypos+=18; - } - - Matrix33 _m33; - _m33.SetIdentity(); - AABB aabb1 = AABB(Vec3(-0.03f, -YR, -0.001f), Vec3(0.03f, YR, 0.001f)); - OBB _obb1 = OBB::CreateOBBfromAABB(SlopeMat33, aabb1); - AABB aabb2 = AABB(Vec3(-XR, -0.03f, -0.001f), Vec3(XR, 0.03f, 0.001f)); - OBB _obb2 = OBB::CreateOBBfromAABB(SlopeMat33, aabb2); - - SlopeMat33 = SlopeMat33 * ScaleMat33; - // Draw grid. - float step = 0.25f; - for (float x = -XR; x < XR; x += step) - { - Vec3 p0 = Vec3(x, -YR, 0); - Vec3 p1 = Vec3(x, YR, 0); - //pAuxGeom->DrawLine( SlopeMat33*p0,RGBA8(0x7f,0x7f,0x7f,0x00), SlopeMat33*p1,RGBA8(0x7f,0x7f,0x7f,0x00) ); - int32 intx = int32(x); - if (fabsf(intx - x) < 0.001f) - { - pAuxGeom->DrawOBB(_obb1, SlopeMat33 * Vec3(x, 0.0f, 0.0f) + m_GridOrigin, 1, RGBA8(0x9f, 0x9f, 0x9f, 0x00), eBBD_Faceted); - } - else - { - pAuxGeom->DrawLine(SlopeMat33 * p0 + m_GridOrigin, RGBA8(0x7f, 0x7f, 0x7f, 0x00), SlopeMat33 * p1 + m_GridOrigin, RGBA8(0x7f, 0x7f, 0x7f, 0x00)); - } - } - - for (float y = -YR; y < YR; y += step) - { - Vec3 p0 = Vec3(-XR, y, 0); - Vec3 p1 = Vec3(XR, y, 0); - // pAuxGeom->DrawLine( SlopeMat33*p0,RGBA8(0x7f,0x7f,0x7f,0x00), SlopeMat33*p1,RGBA8(0x7f,0x7f,0x7f,0x00) ); - int32 inty = int32(y); - if (fabsf(inty - y) < 0.001f) - { - pAuxGeom->DrawOBB(_obb2, SlopeMat33 * Vec3(0.0f, y, 0.0f) + m_GridOrigin, 1, RGBA8(0x9f, 0x9f, 0x9f, 0x00), eBBD_Faceted); - } - else - { - pAuxGeom->DrawLine(SlopeMat33 * p0 + m_GridOrigin, RGBA8(0x7f, 0x7f, 0x7f, 0x00), SlopeMat33 * p1 + m_GridOrigin, RGBA8(0x7f, 0x7f, 0x7f, 0x00)); - } - } - - // TODO - the grid should probably be an IRenderNode at some point - // flushing grid geometry now so it will not override transparent - // objects later in the render pipeline. - pAuxGeom->Commit(); -} - - -//-------------------------------------------------------------------------------------- -//-------------------------------------------------------------------------------------- -//-------------------------------------------------------------------------------------- -void CModelViewport::DrawCoordSystem(const QuatT& location, f32 length) -{ - IRenderAuxGeom* pAuxGeom = m_renderer->GetIRenderAuxGeom(); - SAuxGeomRenderFlags renderFlags(e_Def3DPublicRenderflags); - pAuxGeom->SetRenderFlags(renderFlags); - - Vec3 absAxisX = location.q.GetColumn0(); - Vec3 absAxisY = location.q.GetColumn1(); - Vec3 absAxisZ = location.q.GetColumn2(); - - const f32 scale = 3.0f; - const f32 size = 0.009f; - AABB xaabb = AABB(Vec3(-length * scale, -size * scale, -size * scale), Vec3(length * scale, size * scale, size * scale)); - AABB yaabb = AABB(Vec3(-size * scale, -length * scale, -size * scale), Vec3(size * scale, length * scale, size * scale)); - AABB zaabb = AABB(Vec3(-size * scale, -size * scale, -length * scale), Vec3(size * scale, size * scale, length * scale)); - - OBB obb; - obb = OBB::CreateOBBfromAABB(Matrix33(location.q), xaabb); - pAuxGeom->DrawOBB(obb, location.t, 1, RGBA8(0xff, 0x00, 0x00, 0xff), eBBD_Extremes_Color_Encoded); - pAuxGeom->DrawCone(location.t + absAxisX * length * scale, absAxisX, 0.03f * scale, 0.15f * scale, RGBA8(0xff, 0x00, 0x00, 0xff)); - - obb = OBB::CreateOBBfromAABB(Matrix33(location.q), yaabb); - pAuxGeom->DrawOBB(obb, location.t, 1, RGBA8(0x00, 0xff, 0x00, 0xff), eBBD_Extremes_Color_Encoded); - pAuxGeom->DrawCone(location.t + absAxisY * length * scale, absAxisY, 0.03f * scale, 0.15f * scale, RGBA8(0x00, 0xff, 0x00, 0xff)); - - obb = OBB::CreateOBBfromAABB(Matrix33(location.q), zaabb); - pAuxGeom->DrawOBB(obb, location.t, 1, RGBA8(0x00, 0x00, 0xff, 0xff), eBBD_Extremes_Color_Encoded); - pAuxGeom->DrawCone(location.t + absAxisZ * length * scale, absAxisZ, 0.03f * scale, 0.15f * scale, RGBA8(0x00, 0x00, 0xff, 0xff)); -} - - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::OnLightMultiplier([[maybe_unused]] IVariable* var) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CModelViewport::SetSelected(bool const bSelect) -{ - // If a modelviewport gets activated, and listeners will be activated, disable the main viewport listener and re-enable when you lose focus. - if (gEnv->pSystem) - { - IViewSystem* const pIViewSystem = gEnv->pSystem->GetIViewSystem(); - - if (pIViewSystem) - { - pIViewSystem->SetControlAudioListeners(!bSelect); - } - } -} - -#include diff --git a/Code/Sandbox/Editor/ModelViewport.h b/Code/Sandbox/Editor/ModelViewport.h deleted file mode 100644 index a5d1ac2a26..0000000000 --- a/Code/Sandbox/Editor/ModelViewport.h +++ /dev/null @@ -1,258 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -//////////////////////////////////////////////////////////////////////////// -// -// Crytek Engine Source File. -// Copyright (C), Crytek Studios, 2001. -// ------------------------------------------------------------------------- -// File name: ModelViewport.h -// Version: v1.00 -// Created: 8/10/2001 by Timur. -// Compilers: Visual C++ 6.0 -// Description: -// ------------------------------------------------------------------------- -// History: -// -//////////////////////////////////////////////////////////////////////////// -#ifndef CRYINCLUDE_EDITOR_MODELVIEWPORT_H -#define CRYINCLUDE_EDITOR_MODELVIEWPORT_H - -#if !defined(Q_MOC_RUN) -#include "RenderViewport.h" -#include "Util/Variable.h" -#endif - -struct IPhysicalEntity; - -///////////////////////////////////////////////////////////////////////////// -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -// CModelViewport window -class SANDBOX_API CModelViewport - : public CRenderViewport -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - Q_OBJECT - // Construction -public: - CModelViewport(const char* settingsPath = "Settings\\CharacterEditorUserOptions", QWidget* parent = nullptr); - virtual ~CModelViewport(); - - virtual EViewportType GetType() const { return ET_ViewportModel; } - virtual void SetType([[maybe_unused]] EViewportType type) { assert(type == ET_ViewportModel); }; - - virtual void LoadObject(const QString& obj, float scale); - - virtual void OnActivate(); - virtual void OnDeactivate(); - - virtual bool CanDrop(const QPoint& point, IDataBaseItem* pItem); - virtual void Drop(const QPoint& point, IDataBaseItem* pItem); - - virtual void SetSelected(bool const bSelect); - - // Callbacks. - void OnShowShaders(IVariable* var); - void OnShowNormals(IVariable* var); - void OnShowTangents(IVariable* var); - - void OnShowPortals(IVariable* var); - void OnShowShadowVolumes(IVariable* var); - void OnShowTextureUsage(IVariable* var); - void OnCharPhysics(IVariable* var); - void OnShowOcclusion(IVariable* var); - - void OnLightColor(IVariable* var); - void OnLightMultiplier(IVariable* var); - void OnDisableVisibility(IVariable* var); - - IStatObj* GetStaticObject(){ return m_object; } - - void GetOnDisableVisibility(IVariable* var); - - const CVarObject* GetVarObject() const { return &m_vars; } - CVarObject* GetVarObject() { return &m_vars; } - - virtual void Update(); - - - void UseWeaponIK([[maybe_unused]] bool val) { m_weaponIK = true; } - - void ReleaseObject(); - void RePhysicalize(); - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Vec3 m_GridOrigin; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - void SetPaused(bool bPaused); - bool GetPaused() {return m_bPaused; } - - bool IsCameraAttached() const{ return mv_AttachCamera; } - - virtual void PlayAnimation(const char* szName); - - const QString& GetLoadedFileName() const { return m_loadedFile; } - - void Physicalize(); - -protected: - - void LoadStaticObject(const QString& file); - - // Called to render stuff. - virtual void OnRender(); - - virtual void DrawFloorGrid(const Quat& tmRotation, const Vec3& MotionTranslation, const Matrix33& rGridRot); - void DrawCoordSystem(const QuatT& q, f32 length); - - void SaveDebugOptions() const; - void RestoreDebugOptions(); - - virtual void DrawModel(const SRenderingPassInfo& passInfo); - virtual void DrawLights(const SRenderingPassInfo& passInfo); - virtual void DrawSkyBox(const SRenderingPassInfo& passInfo); - - void DrawInfo() const; - - void SetConsoleVar(const char* var, int value); - - void OnEditorNotifyEvent(EEditorNotifyEvent event) - { - if (event != eNotify_OnBeginGameMode) - { - // the base class responds to this by forcing itself to be the current context. - // we don't want that to be the case for previewer viewports. - CRenderViewport::OnEditorNotifyEvent(event); - } - } - - IStatObj* m_object; - IStatObj* m_weaponModel; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - - QString m_attachBone; - AABB m_AABB; - - struct BBox - { - OBB obb; - Vec3 pos; - ColorB col; - }; - std::vector m_arrBBoxes; - - // Camera control. - float m_camRadius; - - // True to show grid. - bool m_bGrid; - bool m_bBase; - - QString m_settingsPath; - - bool m_weaponIK; - - QString m_loadedFile; - CDLight m_VPLight; - - f32 m_LightRotationRadian; - - class CRESky* m_pRESky; - struct ICVar* m_pSkyboxName; - IShader* m_pSkyBoxShader; - - //--------------------------------------------------- - //--- debug options --- - //--------------------------------------------------- - CVariable mv_showGrid; - CVariable mv_showBase; - CVariable mv_showLocator; - CVariable mv_InPlaceMovement; - CVariable mv_StrafingControl; - - CVariable mv_showWireframe1; //draw wireframe instead of solid-geometry. - CVariable mv_showWireframe2; //this one is software-wireframe rendered on top of the solid geometry - CVariable mv_showTangents; - CVariable mv_showBinormals; - CVariable mv_showNormals; - - CVariable mv_showSkeleton; - CVariable mv_showJointNames; - CVariable mv_showJointsValues; - CVariable mv_showStartLocation; - CVariable mv_showMotionParam; - CVariable mv_UniformScaling; - - CVariable mv_printDebugText; - CVariable mv_AttachCamera; - - CVariable mv_showShaders; - - CVariable mv_lighting; - CVariable mv_animateLights; - - CVariable mv_backgroundColor; - CVariable mv_objectAmbientColor; - - CVariable mv_lightDiffuseColor; - CVariable mv_lightMultiplier; - CVariable mv_lightSpecMultiplier; - CVariable mv_lightRadius; - CVariable mv_lightOrbit; - - CVariable mv_fov; - CVariable mv_showPhysics; - CVariable mv_useCharPhysics; - CVariable mv_showPhysicsTetriders; - CVariable mv_forceLODNum; - - CVariableArray mv_advancedTable; - - CVarObject m_vars; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -public slots: - virtual void OnAnimPlay(); - virtual void OnAnimBack(); - virtual void OnAnimFastBack(); - virtual void OnAnimFastForward(); - virtual void OnAnimFront(); -protected: - bool m_bPaused; - - void OnDestroy(); - void mouseDoubleClickEvent(QMouseEvent* event) override; - -private: - struct VariableCallbackIndex - { - enum : unsigned char - { - OnCharPhysics = 0, - OnLightColor, - OnLightMultiplier, - OnShowShaders, - - // must be at the end - Count, - }; - }; -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - AZStd::fixed_vector< IVariable::OnSetCallback, VariableCallbackIndex::Count > m_onSetCallbacksCache; -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // CRYINCLUDE_EDITOR_MODELVIEWPORT_H diff --git a/Code/Sandbox/Editor/ModelViewportDC.cpp b/Code/Sandbox/Editor/ModelViewportDC.cpp deleted file mode 100644 index 9424a12c0c..0000000000 --- a/Code/Sandbox/Editor/ModelViewportDC.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - - - - - - - - - - diff --git a/Code/Sandbox/Editor/Objects/BaseObject.cpp b/Code/Sandbox/Editor/Objects/BaseObject.cpp index 109b28798f..3ec505172e 100644 --- a/Code/Sandbox/Editor/Objects/BaseObject.cpp +++ b/Code/Sandbox/Editor/Objects/BaseObject.cpp @@ -37,6 +37,8 @@ #include "ViewManager.h" #include "IEditorImpl.h" #include "GameEngine.h" +#include +#include // To use the Andrew's algorithm in order to make convex hull from the points, this header is needed. #include "Util/GeometryUtil.h" @@ -821,9 +823,8 @@ void CBaseObject::GetLocalBounds(AABB& box) } ////////////////////////////////////////////////////////////////////////// -void CBaseObject::SetModified(bool boModifiedTransformOnly) +void CBaseObject::SetModified(bool) { - ((CObjectManager*)GetObjectManager())->OnObjectModified(this, false, boModifiedTransformOnly); } void CBaseObject::DrawDefault(DisplayContext& dc, const QColor& labelColor) diff --git a/Code/Sandbox/Editor/Objects/BaseObject.h b/Code/Sandbox/Editor/Objects/BaseObject.h index 44df1e5757..5d6f800a58 100644 --- a/Code/Sandbox/Editor/Objects/BaseObject.h +++ b/Code/Sandbox/Editor/Objects/BaseObject.h @@ -35,7 +35,6 @@ class CUndoBaseObject; class CObjectManager; class CGizmo; class CObjectArchive; -class CEdGeometry; struct SSubObjSelectionModifyContext; struct SRayHitInfo; class ISubObjectSelectionReferenceFrameCalculator; @@ -580,10 +579,6 @@ public: virtual void ModifySubObjSelection([[maybe_unused]] SSubObjSelectionModifyContext& modCtx) {}; virtual void AcceptSubObjectModify() {}; - // Request a geometry pointer from the object. - // Return NULL if geometry can not be retrieved or object does not support geometries. - virtual CEdGeometry* GetGeometry() { return 0; }; - //! In This function variables of the object must be initialized. virtual void InitVariables() {}; diff --git a/Code/Sandbox/Editor/Objects/DisplayContext.h b/Code/Sandbox/Editor/Objects/DisplayContext.h index a8181e1d1b..13363a923e 100644 --- a/Code/Sandbox/Editor/Objects/DisplayContext.h +++ b/Code/Sandbox/Editor/Objects/DisplayContext.h @@ -33,7 +33,6 @@ struct IDisplayViewport; struct IRenderer; struct IRenderAuxGeom; struct IIconManager; -struct I3DEngine; class CDisplaySettings; class CCamera; @@ -70,7 +69,6 @@ struct SANDBOX_API DisplayContext IRenderer* renderer; IRenderAuxGeom* pRenderAuxGeom; IIconManager* pIconManager; - I3DEngine* engine; CCamera* camera; AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING AABB box; // Bounding box of volume that need to be repainted. diff --git a/Code/Sandbox/Editor/Objects/DisplayContextShared.inl b/Code/Sandbox/Editor/Objects/DisplayContextShared.inl index dd5c248357..4d284faea7 100644 --- a/Code/Sandbox/Editor/Objects/DisplayContextShared.inl +++ b/Code/Sandbox/Editor/Objects/DisplayContextShared.inl @@ -18,8 +18,6 @@ #include "Include/IIconManager.h" #include "Include/IDisplayViewport.h" -#include - #include #include @@ -32,7 +30,6 @@ DisplayContext::DisplayContext() { view = 0; renderer = 0; - engine = 0; flags = 0; settings = 0; pIconManager = 0; @@ -981,27 +978,8 @@ void DisplayContext::RenderObject(int objectType, const Vec3& pos, float scale) } ////////////////////////////////////////////////////////////////////////// -void DisplayContext::RenderObject(int objectType, const Matrix34& tm) +void DisplayContext::RenderObject(int, const Matrix34&) { - IStatObj* object = pIconManager ? pIconManager->GetObject((EStatObject)objectType) : 0; - if (object) - { - float color[4]; - color[0] = m_color4b.r * (1.0f / 255.0f); - color[1] = m_color4b.g * (1.0f / 255.0f); - color[2] = m_color4b.b * (1.0f / 255.0f); - color[3] = m_color4b.a * (1.0f / 255.0f); - - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(GetIEditor()->GetSystem()->GetViewCamera()); - - Matrix34 xform = m_matrixStack[m_currentMatrix] * tm; - SRendParams rp; - rp.pMatrix = &xform; - rp.AmbientColor = ColorF(color[0], color[1], color[2], 1); - rp.fAlpha = color[3]; - - object->Render(rp, passInfo); - } } ///////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/Objects/EntityObject.cpp b/Code/Sandbox/Editor/Objects/EntityObject.cpp index 0b2627091c..17e9fdda5c 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.cpp +++ b/Code/Sandbox/Editor/Objects/EntityObject.cpp @@ -32,6 +32,8 @@ #include "HitContext.h" #include "Objects/SelectionGroup.h" +#include +#include ////////////////////////////////////////////////////////////////////////// //! Undo Entity Link @@ -1926,55 +1928,6 @@ void CEntityObject::OnContextMenu(QMenu* pMenu) CBaseObject::OnContextMenu(pMenu); } -////////////////////////////////////////////////////////////////////////// -IOpticsElementBasePtr CEntityObject::GetOpticsElement() -{ - CDLight* pLight = GetLightProperty(); - if (pLight == NULL) - { - return NULL; - } - return pLight->GetLensOpticsElement(); -} - -////////////////////////////////////////////////////////////////////////// -void CEntityObject::SetOpticsName(const QString& opticsFullName) -{ - if (opticsFullName.isEmpty()) - { - CDLight* pLight = GetLightProperty(); - if (pLight) - { - pLight->SetLensOpticsElement(NULL); - } - } -} - -////////////////////////////////////////////////////////////////////////// -CDLight* CEntityObject::GetLightProperty() const -{ - const PodArray* pLightEntities = GetIEditor()->Get3DEngine()->GetLightEntities(); - if (pLightEntities == NULL) - { - return NULL; - } - for (int i = 0, iLightSize(pLightEntities->Count()); i < iLightSize; ++i) - { - ILightSource* pLightSource = pLightEntities->GetAt(i); - if (pLightSource == NULL) - { - continue; - } - CDLight& lightProperty = pLightSource->GetLightProperties(); - if (GetName() != lightProperty.m_sName) - { - continue; - } - return &lightProperty; - } - return NULL; -} - ////////////////////////////////////////////////////////////////////////// void CEntityObject::PreInitLightProperty() { diff --git a/Code/Sandbox/Editor/Objects/EntityObject.h b/Code/Sandbox/Editor/Objects/EntityObject.h index a287cd8828..85368f7804 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.h +++ b/Code/Sandbox/Editor/Objects/EntityObject.h @@ -214,8 +214,6 @@ public: QString GetLightAnimation() const; IVariable* GetLightVariable(const char* name) const; - IOpticsElementBasePtr GetOpticsElement(); - void SetOpticsName(const QString& opticsFullName); void PreInitLightProperty(); void UpdateLightProperty(); @@ -230,8 +228,6 @@ public: void RegisterListener(IEntityObjectListener* pListener); void UnregisterListener(IEntityObjectListener* pListener); - CDLight* GetLightProperty() const; - protected: template void SetEntityProperty(const char* name, T value); diff --git a/Code/Sandbox/Editor/Objects/ObjectManager.cpp b/Code/Sandbox/Editor/Objects/ObjectManager.cpp index 39174774be..d383fb0e1b 100644 --- a/Code/Sandbox/Editor/Objects/ObjectManager.cpp +++ b/Code/Sandbox/Editor/Objects/ObjectManager.cpp @@ -400,8 +400,6 @@ void CObjectManager::DeleteObject(CBaseObject* obj) CUndo::Record(new CUndoBaseObjectDelete(obj)); } - OnObjectModified(obj, true, false); - AABB objAAB; obj->GetBoundBox(objAAB); GetIEditor()->GetGameEngine()->OnAreaModified(objAAB); @@ -2477,17 +2475,6 @@ IGizmoManager* CObjectManager::GetGizmoManager() return m_gizmoManager; } -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -void CObjectManager::OnObjectModified(CBaseObject* pObject, [[maybe_unused]] bool bDelete, [[maybe_unused]] bool boModifiedTransformOnly) -{ - if (IRenderNode* pRenderNode = pObject->GetEngineNode()) - { - GetIEditor()->Get3DEngine()->OnObjectModified(pRenderNode, pRenderNode->GetRndFlags()); - } -} - ////////////////////////////////////////////////////////////////////////// bool CObjectManager::IsLightClass(CBaseObject* pObject) { diff --git a/Code/Sandbox/Editor/Objects/ObjectManager.h b/Code/Sandbox/Editor/Objects/ObjectManager.h index 26905c47cd..4939fdeefc 100644 --- a/Code/Sandbox/Editor/Objects/ObjectManager.h +++ b/Code/Sandbox/Editor/Objects/ObjectManager.h @@ -326,9 +326,6 @@ public: // Gathers all resources used by all objects. void GatherUsedResources(CUsedResources& resources); - // Called when object gets modified. - void OnObjectModified(CBaseObject* pObject, bool bDelete, bool boModifiedTransformOnly); - virtual bool IsLightClass(CBaseObject* pObject); virtual void FindAndRenameProperty2(const char* property2Name, const QString& oldValue, const QString& newValue); diff --git a/Code/Sandbox/Editor/Objects/SelectionGroup.cpp b/Code/Sandbox/Editor/Objects/SelectionGroup.cpp index 08abf8f763..98e00645ee 100644 --- a/Code/Sandbox/Editor/Objects/SelectionGroup.cpp +++ b/Code/Sandbox/Editor/Objects/SelectionGroup.cpp @@ -22,6 +22,7 @@ #include "ViewManager.h" #include "Include/IObjectManager.h" +#include ////////////////////////////////////////////////////////////////////////// CSelectionGroup::CSelectionGroup() diff --git a/Code/Sandbox/Editor/PanelPreview.cpp b/Code/Sandbox/Editor/PanelPreview.cpp deleted file mode 100644 index fe5ea7be9b..0000000000 --- a/Code/Sandbox/Editor/PanelPreview.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "PanelPreview.h" - -// Qt -#include - -// CPanelPreview dialog - -CPanelPreview::CPanelPreview(QWidget* pParent /*=nullptr*/) - : QWidget(pParent) - , m_previewCtrl(new CPreviewModelCtrl(this)) -{ - QBoxLayout* layout = new QHBoxLayout; - layout->setMargin(0); - layout->addWidget(m_previewCtrl); - setLayout(layout); -} - -////////////////////////////////////////////////////////////////////////// -void CPanelPreview::LoadFile(const QString& filename) -{ - if (!filename.isEmpty()) - { - m_previewCtrl->EnableUpdate(false); - m_previewCtrl->LoadFile(filename, false); - } -} - diff --git a/Code/Sandbox/Editor/PanelPreview.h b/Code/Sandbox/Editor/PanelPreview.h deleted file mode 100644 index d2c951ba4e..0000000000 --- a/Code/Sandbox/Editor/PanelPreview.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_PANELPREVIEW_H -#define CRYINCLUDE_EDITOR_PANELPREVIEW_H -#pragma once - -// CPanelPreview dialog - -#include "Controls/PreviewModelCtrl.h" - - -class CPanelPreview - : public QWidget -{ -public: - CPanelPreview(QWidget* pParent = nullptr); // standard constructor - - void LoadFile(const QString& filename); - - QSize sizeHint() const override - { - return QSize(130, 240); - } - -protected: - CPreviewModelCtrl* m_previewCtrl; -}; - -#endif // CRYINCLUDE_EDITOR_PANELPREVIEW_H diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index 325779a401..d24f569047 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -55,7 +55,6 @@ // CryCommon -#include #include // AzFramework @@ -89,6 +88,10 @@ #include +#include +#include +#include + AZ_CVAR( bool, ed_visibility_use, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Enable/disable using the new IVisibilitySystem for Entity visibility determination"); @@ -249,10 +252,6 @@ CRenderViewport::~CRenderViewport() ////////////////////////////////////////////////////////////////////////// int CRenderViewport::OnCreate() { - m_renderer = GetIEditor()->GetRenderer(); - m_engine = GetIEditor()->Get3DEngine(); - assert(m_engine); - CreateRenderContext(); return 0; @@ -1033,7 +1032,7 @@ void CRenderViewport::Update() return; } - if (!m_renderer || !m_engine || m_rcClient.isEmpty() || GetIEditor()->IsInMatEditMode()) + if (!m_renderer || m_rcClient.isEmpty() || GetIEditor()->IsInMatEditMode()) { return; } @@ -1156,9 +1155,6 @@ void CRenderViewport::Update() m_renderer->SetClearColor(Vec3(0.4f, 0.4f, 0.4f)); - // 3D engine stats - GetIEditor()->GetSystem()->RenderBegin(); - InitDisplayContext(); OnRender(); @@ -1184,8 +1180,6 @@ void CRenderViewport::Update() } } - GetIEditor()->GetSystem()->RenderEnd(m_bRenderStats); - gEnv->pSystem->SetViewCamera(CurCamera); } @@ -1421,8 +1415,6 @@ void CRenderViewport::OnRender() // This is necessary so that automated editor tests using the null renderer to test systems like dynamic vegetation // are still able to manipulate the current logical camera position, even if nothing is rendered. GetIEditor()->GetSystem()->SetViewCamera(m_Camera); - GetIEditor()->GetRenderer()->SetCamera(gEnv->pSystem->GetViewCamera()); - m_engine->RenderWorld(0, SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_Camera), __FUNCTION__); return; } @@ -1495,7 +1487,7 @@ void CRenderViewport::OnRender() } } - m_Camera.SetFrustum(w, h, fov, fNearZ, gEnv->p3DEngine->GetMaxViewDistance()); + m_Camera.SetFrustum(w, h, fov, fNearZ); } GetIEditor()->GetSystem()->SetViewCamera(m_Camera); @@ -1556,11 +1548,6 @@ void CRenderViewport::OnRender() m_renderer->ClearTargetsLater(FRT_CLEAR_COLOR, viewportBackgroundColor); DrawBackground(); } - - if (!m_renderer->IsStereoEnabled()) - { - GetIEditor()->GetSystem()->RenderStatistics(); - } } ////////////////////////////////////////////////////////////////////////// @@ -1590,7 +1577,6 @@ void CRenderViewport::InitDisplayContext() displayContext.settings = GetIEditor()->GetDisplaySettings(); displayContext.view = this; displayContext.renderer = m_renderer; - displayContext.engine = m_engine; displayContext.box.min = Vec3(-100000.0f, -100000.0f, -100000.0f); displayContext.box.max = Vec3(100000.0f, 100000.0f, 100000.0f); displayContext.camera = &m_Camera; @@ -2467,7 +2453,6 @@ void CRenderViewport::ToggleCameraObject() { if (m_viewSourceType == ViewSourceType::SequenceCamera) { - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); ResetToViewSourceType(ViewSourceType::LegacyCamera); } else @@ -2789,11 +2774,6 @@ void CRenderViewport::SetViewTM(const Matrix34& viewTM, bool bMoveOnly) ////////////////////////////////////////////////////////////////////////// void CRenderViewport::RenderSelectedRegion() { - if (!m_engine) - { - return; - } - AABB box; GetIEditor()->GetSelectedRegion(box); if (box.IsEmpty()) @@ -3385,19 +3365,9 @@ bool CRenderViewport::AdjustObjectPosition(const ray_hit& hit, Vec3& outNormal, } ////////////////////////////////////////////////////////////////////////// -bool CRenderViewport::RayRenderMeshIntersection(IRenderMesh* pRenderMesh, const Vec3& vInPos, const Vec3& vInDir, Vec3& vOutPos, Vec3& vOutNormal) const +bool CRenderViewport::RayRenderMeshIntersection(IRenderMesh*, const Vec3&, const Vec3&, Vec3&, Vec3&) const { - SRayHitInfo hitInfo; - hitInfo.bUseCache = false; - hitInfo.bInFirstHit = false; - hitInfo.inRay.origin = vInPos; - hitInfo.inRay.direction = vInDir.GetNormalized(); - hitInfo.inReferencePoint = vInPos; - hitInfo.fMaxHitDistance = 0; - bool bRes = GetIEditor()->Get3DEngine()->RenderMeshRayIntersection(pRenderMesh, hitInfo, nullptr); - vOutPos = hitInfo.vHitPos; - vOutNormal = hitInfo.vHitNormal; - return bRes; + return false; } ////////////////////////////////////////////////////////////////////////// @@ -3682,7 +3652,6 @@ void CRenderViewport::SetDefaultCamera() return; } ResetToViewSourceType(ViewSourceType::None); - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); GetViewManager()->SetCameraObjectId(m_cameraObjectId); SetName(m_defaultViewName); SetViewTM(m_defaultViewTM); @@ -3861,23 +3830,8 @@ void CRenderViewport::SetViewAndMovementLockFromEntityPerspective(const AZ::Enti bool CRenderViewport::GetActiveCameraPosition(AZ::Vector3& cameraPos) { - if (m_pPrimaryViewport == this) - { - if (GetIEditor()->IsInGameMode()) - { - const Vec3 camPos = m_engine->GetRenderingCamera().GetPosition(); - cameraPos = LYVec3ToAZVec3(camPos); - } - else - { - // Use viewTM, which is synced with the camera and guaranteed to be up-to-date - cameraPos = LYVec3ToAZVec3(m_viewTM.GetTranslation()); - } - - return true; - } - - return false; + cameraPos = LYVec3ToAZVec3(m_viewTM.GetTranslation()); + return true; } bool CRenderViewport::GetActiveCameraState(AzFramework::CameraState& cameraState) @@ -3886,9 +3840,7 @@ bool CRenderViewport::GetActiveCameraState(AzFramework::CameraState& cameraState { if (GetIEditor()->IsInGameMode()) { - const auto& renderingCamera = m_engine->GetRenderingCamera(); - cameraState = CameraStateFromCCamera( - renderingCamera, renderingCamera.GetFov(), m_rcClient.width(), m_rcClient.height()); + return false; } else { diff --git a/Code/Sandbox/Editor/RenderViewport.h b/Code/Sandbox/Editor/RenderViewport.h index 9985408d25..d70dd59b98 100644 --- a/Code/Sandbox/Editor/RenderViewport.h +++ b/Code/Sandbox/Editor/RenderViewport.h @@ -438,7 +438,6 @@ protected: //! Assigned renderer. IRenderer* m_renderer = nullptr; - I3DEngine* m_engine = nullptr; bool m_bRenderContextCreated = false; bool m_bInRotateMode = false; bool m_bInMoveMode = false; @@ -525,10 +524,6 @@ protected: OBB m_GroundOBB; Vec3 m_GroundOBBPos; - //------------------------------------------- - // Render options. - bool m_bRenderStats = true; - // Index of camera objects. mutable GUID m_cameraObjectId = GUID_NULL; mutable AZ::EntityId m_viewEntityId; diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index d9fdb42c0b..ea8ec828cf 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -75,7 +75,6 @@ #define IDC_PLATFORM_SALEM 2759 #define IDC_GROUPBOX_GLOBALTAGS 2916 #define IDC_GROUPBOX_FRAGMENTTAGS 2917 -#define ID_RESOURCES_GENERATECGFTHUMBNAILS 32894 #define ID_RESOURCES_REDUCEWORKINGSET 32896 #define ID_EDIT_HIDE 32898 #define ID_EDIT_UNHIDEALL 32899 @@ -133,7 +132,6 @@ #define ID_FILE_EDITEDITORINI 33543 #define ID_FILE_EDITLOGFILE 33544 #define ID_PREFERENCES 33546 -#define ID_RELOAD_GEOMETRY 33549 #define ID_REDO 33550 #define ID_SWITCH_PHYSICS 33555 #define ID_REF_COORDS_SYS 33556 diff --git a/Code/Sandbox/Editor/Settings.cpp b/Code/Sandbox/Editor/Settings.cpp index 99a801eedc..15d3e793a5 100644 --- a/Code/Sandbox/Editor/Settings.cpp +++ b/Code/Sandbox/Editor/Settings.cpp @@ -252,8 +252,6 @@ SEditorSettings::SEditorSettings() gui.hSystemFontBold = QFont("Ms Shell Dlg 2", lfHeight, QFont::Bold); gui.hSystemFontItalic = QFont("Ms Shell Dlg 2", lfHeight, QFont::Normal, true); - bForceSkyUpdate = true; - backgroundUpdatePeriod = 0; g_TemporaryLevelName = nullptr; @@ -647,8 +645,6 @@ void SEditorSettings::Save() SaveValue("Settings\\ObjectColors", "GeometryAlpha", objectColorSettings.fGeomAlpha); SaveValue("Settings\\ObjectColors", "ChildGeometryAlpha", objectColorSettings.fChildGeomAlpha); - SaveValue("Settings", "ForceSkyUpdate", gSettings.bForceSkyUpdate); - ////////////////////////////////////////////////////////////////////////// // Smart file open settings ////////////////////////////////////////////////////////////////////////// @@ -873,8 +869,6 @@ void SEditorSettings::Load() LoadValue("Settings\\ObjectColors", "GeometryAlpha", objectColorSettings.fGeomAlpha); LoadValue("Settings\\ObjectColors", "ChildGeometryAlpha", objectColorSettings.fChildGeomAlpha); - LoadValue("Settings", "ForceSkyUpdate", gSettings.bForceSkyUpdate); - ////////////////////////////////////////////////////////////////////////// // Smart file open settings ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/Settings.h b/Code/Sandbox/Editor/Settings.h index 511bbb9bbe..93e61bc1ed 100644 --- a/Code/Sandbox/Editor/Settings.h +++ b/Code/Sandbox/Editor/Settings.h @@ -467,8 +467,6 @@ AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING bool bSettingsManagerMode; - bool bForceSkyUpdate; - bool bAutoSaveTagPoints; bool bNavigationContinuousUpdate; diff --git a/Code/Sandbox/Editor/ThumbnailGenerator.cpp b/Code/Sandbox/Editor/ThumbnailGenerator.cpp deleted file mode 100644 index c2f03a1944..0000000000 --- a/Code/Sandbox/Editor/ThumbnailGenerator.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "ThumbnailGenerator.h" - -// Editor -#include "Util/Image.h" -#include "Util/ImageUtil.h" // for CUmageUtil -#include "WaitProgress.h" // for CWaitProgress - -#if defined(AZ_PLATFORM_MAC) || defined(AZ_PLATFORM_LINUX) -#include -#include -#endif - - - -CThumbnailGenerator::CThumbnailGenerator(void) -{ -} - -CThumbnailGenerator::~CThumbnailGenerator(void) -{ -} - -// Get directory contents. -static bool scan_directory(const QString& root, const QString& path, const QString& file, QStringList& files, bool recursive) -{ - QString fullPath = root + path + file; - QDirIterator::IteratorFlags flags = QDirIterator::NoIteratorFlags; - if (recursive) - { - flags = QDirIterator::Subdirectories; - } - QDirIterator dirIterator(fullPath, {file}, QDir::Files, flags); - if (!dirIterator.hasNext()) - { - return false; - } - else - { - // Find the rest of the .c files. - while (dirIterator.hasNext()) - { - files.push_back(dirIterator.next()); - //FileInfo fi; - //fi.attrib = c_file.attrib; - //fi.name = path + c_file.name; - /* - // Add . after file name without extension. - if (fi.name.find('.') == CString::npos) { - fi.name.append( "." ); - } - */ - //fi.size = c_file.size; - //fi.time = c_file.time_write; - //files.push_back( fi ); - } - } - return true; -} - -#if defined(AZ_PLATFORM_WINDOWS) -#define FileTimeType FILETIME - -inline void GetThumbFileTime(const char* fileName, FILETIME& time) -{ - HANDLE hFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (INVALID_HANDLE_VALUE != hFile) - { - GetFileTime(hFile, NULL, NULL, &time); - CloseHandle(hFile); - } -} - -inline void SetThumbFileTime(const char* fileName, FILETIME& time) -{ - HANDLE hFile = CreateFile(fileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (INVALID_HANDLE_VALUE != hFile) - { - SetFileTime(hFile, NULL, NULL, &time); - CloseHandle(hFile); - } -} - -inline bool ThumbFileTimeIsEqual(const FILETIME& ft1, const FILETIME& ft2) -{ - return ft1.dwHighDateTime == ft2.dwHighDateTime && ft1.dwLowDateTime == ft2.dwLowDateTime; -} -#elif defined(AZ_PLATFORM_MAC) || defined(AZ_PLATFORM_LINUX) -#define FileTimeType utimbuf - -inline void GetThumbFileTime(const char* fileName, utimbuf& times) -{ - struct stat sb; - if (stat(fileName, &sb) == 0) - { - times.actime = sb.st_atime; - times.modtime = sb.st_mtime; - } -} - -inline void SetThumbFileTime(const char* fileName, const utimbuf& times) -{ - utime(fileName, ×); -} - -inline bool ThumbFileTimeIsEqual(const utimbuf& ft1, const utimbuf& ft2) -{ - return ft1.modtime == ft2.modtime; -} -#endif - -void CThumbnailGenerator::GenerateForDirectory(const QString& path) -{ - return; - - ////////////////////////////////////////////////////////////////////////// - QStringList files; - //CString dir = GetIEditor()->GetPrimaryCDFolder(); - QString dir = path; - scan_directory(dir, "", "*.*", files, true); - - I3DEngine* engine = GetIEditor()->Get3DEngine(); - - int thumbSize = 128; - CImageEx image; - image.Allocate(thumbSize, thumbSize); - - char drive[_MAX_DRIVE]; - char fdir[_MAX_DIR]; - char fname[_MAX_FNAME]; - char fext[_MAX_EXT]; - char bmpFile[1024]; - - GetIEditor()->ShowConsole(true); - CWaitProgress wait("Generating CGF Thumbnails"); - for (int i = 0; i < files.size(); i++) - { - QString file = dir + files[i]; - _splitpath_s(file.toUtf8().data(), drive, fdir, fname, fext); - - //if (_stricmp(fext,".cgf") != 0 && _stricmp(fext,".bld") != 0) - if (_stricmp(fext, ".cgf") != 0) - { - continue; - } - - if (!wait.Step(100 * i / files.size())) - { - break; - } - - _makepath_s(bmpFile, drive, fdir, fname, ".tmb"); - - FileTimeType ft1, ft2; - GetThumbFileTime(file.toUtf8().data(), ft1); - GetThumbFileTime(bmpFile, ft2); - // Both cgf and bmp have same time stamp. - if (ThumbFileTimeIsEqual(ft1, ft2)) - { - continue; - } - - //CLogFile::FormatLine( "Generating thumbnail for %s...",file ); - - _smart_ptr obj = engine->LoadStatObjAutoRef(file.toUtf8().data(), NULL, NULL, false); - if (obj) - { - assert(!"IStatObj::MakeObjectPicture does not exist anymore"); - // obj->MakeObjectPicture( (unsigned char*)image.GetData(),thumbSize ); - - CImageUtil::SaveBitmap(bmpFile, image); - SetThumbFileTime(bmpFile, ft1); -#if defined(AZ_PLATFORM_WINDOWS) - SetFileAttributes(bmpFile, FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_NOT_CONTENT_INDEXED); -#endif - obj->Release(); - } - } - //GetIEditor()->ShowConsole( false ); -} - -void CThumbnailGenerator::GenerateForFile([[maybe_unused]] const QString& fileName) -{ -} diff --git a/Code/Sandbox/Editor/ThumbnailGenerator.h b/Code/Sandbox/Editor/ThumbnailGenerator.h deleted file mode 100644 index ef5a833e60..0000000000 --- a/Code/Sandbox/Editor/ThumbnailGenerator.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_THUMBNAILGENERATOR_H -#define CRYINCLUDE_EDITOR_THUMBNAILGENERATOR_H - -#pragma once - - -class CThumbnailGenerator -{ -public: - CThumbnailGenerator(void); - ~CThumbnailGenerator(void); - - void GenerateForDirectory(const QString& path); - void GenerateForFile(const QString& fileName); -}; - -#endif // CRYINCLUDE_EDITOR_THUMBNAILGENERATOR_H diff --git a/Code/Sandbox/Editor/TimeOfDay.qrc b/Code/Sandbox/Editor/TimeOfDay.qrc deleted file mode 100644 index 7f45cf485f..0000000000 --- a/Code/Sandbox/Editor/TimeOfDay.qrc +++ /dev/null @@ -1,34 +0,0 @@ - - - TimeOfDay/main-00.png - TimeOfDay/main-01.png - TimeOfDay/main-02.png - TimeOfDay/main-03.png - TimeOfDay/main-04.png - TimeOfDay/main-05.png - TimeOfDay/main-06.png - TimeOfDay/main-07.png - TimeOfDay/main-08.png - TimeOfDay/main-09.png - TimeOfDay/main-10.png - TimeOfDay/main-11.png - TimeOfDay/main-12.png - Common/spline_edit-00.png - Common/spline_edit-01.png - Common/spline_edit-02.png - Common/spline_edit-03.png - Common/spline_edit-04.png - Common/spline_edit-05.png - Common/spline_edit-06.png - Common/spline_edit-07.png - Common/spline_edit-08.png - Common/spline_edit-09.png - Common/spline_edit-10.png - Common/spline_edit-11.png - Common/spline_edit-12.png - Common/spline_edit-13.png - Common/spline_edit-14.png - Common/spline_edit-15.png - Common/spline_edit-16.png - - diff --git a/Code/Sandbox/Editor/TimeOfDayDialog.cpp b/Code/Sandbox/Editor/TimeOfDayDialog.cpp deleted file mode 100644 index 80aa4d5172..0000000000 --- a/Code/Sandbox/Editor/TimeOfDayDialog.cpp +++ /dev/null @@ -1,1443 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "TimeOfDayDialog.h" - -// Qt -#include - -// AzToolsFramework -#include - -// CryCommon -#include - -// Editor -#include "Settings.h" -#include "Controls/CurveEditorCtrl.h" -#include "Mission.h" -#include "CryEditDoc.h" -#include "Clipboard.h" -#include "QtViewPaneManager.h" -#include "Undo/Undo.h" -#include "LyViewPaneNames.h" - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -#define PANE_LAYOUT_SECTION _T("DockingPaneLayouts\\TimeOfDay") -#define PANE_LAYOUT_VERSION_ENTRY _T("PaneLayoutVersion") - -namespace TimeOfDayDetails -{ - const float kEpsilon = 0.00001f; - - const int kTimeOfDayDialogLayoutVersion = 0x0002; // bump this up on every substantial pane layout change - - static void SetKeyTangentType(ISplineInterpolator* pSpline, int key, ESplineKeyTangentType type) - { - int flags = (pSpline->GetKeyFlags(key) & ~SPLINE_KEY_TANGENT_IN_MASK) & ~SPLINE_KEY_TANGENT_OUT_MASK; - pSpline->SetKeyFlags(key, flags | (type << SPLINE_KEY_TANGENT_IN_SHIFT) | (type << SPLINE_KEY_TANGENT_OUT_SHIFT)); - } - - static QTime qTimeFromFloat(float time) - { - // The float time goes from 0.0 - 23.98 (since max time is 23:59), so - // convert this to seconds so we can construct a QTime object from that - int seconds = (time * 60.0f) * 60; - return QTime(0, 0).addSecs(seconds); - } - - static float floatFromQTime(const QTime& time) - { - return static_cast(time.msecsSinceStartOfDay() / 60000) / 60.0; - } - - AZ_INLINE static bool SkipUserInterface(int value) - { - // Check for obsolete parameters that we still want to keep around to migrate legacy data to new data - // but don't want to display in the UI - const ITimeOfDay::ETimeOfDayParamID enumValue = static_cast(value); - - // Split the check into two parts to try to keep the logic clear. - // The First set of parameters are always checked... - bool skipParameter = (enumValue == ITimeOfDay::PARAM_HDR_DYNAMIC_POWER_FACTOR) || - (enumValue == ITimeOfDay::PARAM_TERRAIN_OCCL_MULTIPLIER) || - (enumValue == ITimeOfDay::PARAM_SUN_COLOR_MULTIPLIER); - - return skipParameter; - } -} - -CHDRPane::CHDRPane(CTimeOfDayDialog* pTODDlg) - : QWidget(pTODDlg) - , m_pTODDlg(pTODDlg) - , m_pVars(new CVarBlock) -{ - assert(m_pTODDlg); -#if !defined(NDEBUG) - bool ok = -#endif - Init(); - assert(ok); -} - -bool CHDRPane::Init() -{ - m_filmCurveCtrl = new CCurveEditorCtrl(this); - m_filmCurveCtrl->SetControlPointCount(21); - m_filmCurveCtrl->SetMouseEnable(false); - m_filmCurveCtrl->SetPadding(16); - m_filmCurveCtrl->SetFlags( - CCurveEditorCtrl::eFlag_ShowVerticalRuler | - CCurveEditorCtrl::eFlag_ShowHorizontalRuler | - CCurveEditorCtrl::eFlag_ShowCursorAlways | - CCurveEditorCtrl::eFlag_ShowVerticalRulerText | - CCurveEditorCtrl::eFlag_ShowHorizontalRulerText | - CCurveEditorCtrl::eFlag_ShowPaddingBorder); - m_filmCurveCtrl->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - - m_propsCtrl = new ReflectedPropertyControl(this); - m_propsCtrl->Setup(); - - QVBoxLayout* l = new QVBoxLayout; - l->setMargin(0); - l->addWidget(m_filmCurveCtrl); - l->addWidget(m_propsCtrl); - setLayout(l); - - m_propsCtrl->SetSelChangeCallback(AZStd::bind(&CHDRPane::OnPropertySelected, this, AZStd::placeholders::_1)); - - return true; -} - -void CHDRPane::OnPropertySelected(IVariable *pVar) -{ - if (pVar && pVar->GetType() == IVariable::ARRAY) - { - pVar = nullptr; - } - - emit propertySelected(pVar); -} - -bool CHDRPane::GetFilmCurveParams(float& shoulderScale, float& midScale, float& toeScale, float& whitePoint) const -{ - int checked = 0; - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - - for (int i = 0; pTimeOfDay->GetVariableCount(); ++i) - { - ITimeOfDay::SVariableInfo varInfo; - bool ok = pTimeOfDay->GetVariableInfo(i, varInfo); - if (ok == false) - { - continue; - } - if (TimeOfDayDetails::SkipUserInterface(varInfo.nParamId)) - { - continue; - } - - switch (varInfo.nParamId) - { - case ITimeOfDay::PARAM_HDR_FILMCURVE_SHOULDER_SCALE: - shoulderScale = varInfo.fValue[0]; - ++checked; - break; - case ITimeOfDay::PARAM_HDR_FILMCURVE_LINEAR_SCALE: - midScale = varInfo.fValue[0]; - ++checked; - break; - case ITimeOfDay::PARAM_HDR_FILMCURVE_TOE_SCALE: - toeScale = varInfo.fValue[0]; - ++checked; - break; - case ITimeOfDay::PARAM_HDR_FILMCURVE_WHITEPOINT: - whitePoint = varInfo.fValue[0]; - ++checked; - break; - } - - if (checked == 4) - { - return true; - } - } - - return false; -} - -static float EvalFilmCurve(float x, float ss, float ms, float ts) -{ - return (x * (ss * 6.2f * x + 0.5f * ms)) / max((x * (ss * 6.2f * x + 1.7f) + ts * 0.06f), TimeOfDayDetails::kEpsilon); -} - -void CHDRPane::UpdateFilmCurve() -{ - float shoulderScale = 0, midScale = 0, toeScale = 0, whitePoint = 0; -#if !defined(NDEBUG) - bool ok = -#endif - GetFilmCurveParams(shoulderScale, midScale, toeScale, whitePoint); - assert(ok); - const float minX = -4.0f, minY = 0.0f, maxX = 4.0f; - float maxY = 1.0f, stepY = 0.1f; - - int numSamplePoints = m_filmCurveCtrl->GetControlPointCount(); - - for (int i = 0; i < numSamplePoints; ++i) - { - float t = static_cast(i) / (numSamplePoints - 1); - float logX = minX + ((maxX - minX) * t); - float x = powf(10.0f, logX); // Conventionally, the x domain is logarithmic. - - float v = EvalFilmCurve(x, shoulderScale, midScale, toeScale) / - max(EvalFilmCurve(whitePoint, shoulderScale, midScale, toeScale), TimeOfDayDetails::kEpsilon); - v = powf(v, 2.2f); // converting to a linear space - - // Update the maximum Y so that a proper domain can be set later. - if (v > maxY) - { - maxY = ceil(v / stepY) * stepY; - } - - m_filmCurveCtrl->SetControlPoint(i, Vec2(logX, v)); - } - - // maxY is not fixed, so adjust Y grid count properly according to it. - const UINT gridX = 4; // X grid is fixed. - UINT gridY = static_cast(maxY / stepY); - while (gridY > 20) // > 20 means too many, so reduce the count properly. - { - gridY = (gridY + 9) / 10; - stepY *= 10.0f; - } - maxY = stepY * gridY; - // Also prepare labels for the grid since the default labeling is improper - // especially for the X axis due to its log scale. - QStringList labelsX, labelsY; - for (int i = 0; i <= gridX; ++i) - { - QString label; - label.asprintf("%.4g", powf(10.0f, minX + (maxX - minX) * static_cast(i) / gridX)); - labelsX.push_back(label); - } - for (int i = 0; i <= gridY; ++i) - { - QString label; - label.asprintf("%.1f", i * stepY); - labelsY.push_back(label); - } - m_filmCurveCtrl->SetGrid(gridX, gridY, labelsX, labelsY); - m_filmCurveCtrl->MarkY(1.0f); // Mark the output of 1 so that users can quickly recognize where the clamping happens. - m_filmCurveCtrl->SetDomainBounds(minX, minY, maxX, maxY); - - m_filmCurveCtrl->update(); -} -////////////////////////////////////////////////////////////////////////// - -////////////////////////////////////////////////////////////////////////// -// Adapter for Multi element interpolators that allow to split it to several -// different interpolators for each element separately. -////////////////////////////////////////////////////////////////////////// -class CMultiElementSplineInterpolatorAdapter - : public ISplineInterpolator -{ -public: - CMultiElementSplineInterpolatorAdapter() - : m_pInterpolator(0) - , m_element(0) {} - CMultiElementSplineInterpolatorAdapter(ISplineInterpolator* pSpline, int element) - { - m_pInterpolator = pSpline; - m_element = element; - } - // Dimension of the spline from 0 to 3, number of parameters used in ValueType. - virtual int GetNumDimensions() { return m_pInterpolator->GetNumDimensions(); } - virtual int InsertKey(float time, ValueType value) - { - ValueType v = {0, 0, 0, 0}; - v[m_element] = value[0]; - return m_pInterpolator->InsertKey(time, v); - }; - virtual void RemoveKey(int key) { m_pInterpolator->RemoveKey(key); }; - - virtual void FindKeysInRange(float startTime, float endTime, int& firstFoundKey, int& numFoundKeys) - { m_pInterpolator->FindKeysInRange(startTime, endTime, firstFoundKey, numFoundKeys); } - virtual void RemoveKeysInRange(float startTime, float endTime) { m_pInterpolator->RemoveKeysInRange(startTime, endTime); } - - virtual int GetKeyCount() { return m_pInterpolator->GetKeyCount(); } - virtual void SetKeyTime(int key, float time) { return m_pInterpolator->SetKeyTime(key, time); }; - virtual float GetKeyTime(int key) { return m_pInterpolator->GetKeyTime(key); } - - virtual void SetKeyValue(int key, ValueType value) - { - ValueType v = {0, 0, 0, 0}; - m_pInterpolator->GetKeyValue(key, v); - v[m_element] = value[0]; - m_pInterpolator->SetKeyValue(key, v); - } - virtual bool GetKeyValue(int key, ValueType& value) - { - ValueType v = {0, 0, 0, 0}; - v[m_element] = value[0]; - return m_pInterpolator->GetKeyValue(key, value); - value[0] = v[m_element]; - } - - virtual void SetKeyInTangent([[maybe_unused]] int key, [[maybe_unused]] ValueType tin) {}; - virtual void SetKeyOutTangent([[maybe_unused]] int key, [[maybe_unused]] ValueType tout) {}; - virtual void SetKeyTangents([[maybe_unused]] int key, [[maybe_unused]] ValueType tin, [[maybe_unused]] ValueType tout) {}; - virtual bool GetKeyTangents([[maybe_unused]] int key, [[maybe_unused]] ValueType& tin, [[maybe_unused]] ValueType& tout) { return false; }; - - // Changes key flags, @see ESplineKeyFlags - virtual void SetKeyFlags(int key, int flags) { return m_pInterpolator->SetKeyFlags(key, flags); }; - // Retrieve key flags, @see ESplineKeyFlags - virtual int GetKeyFlags(int key) { return m_pInterpolator->GetKeyFlags(key); } - - virtual void Interpolate(float time, ValueType& value) - { - m_pInterpolator->Interpolate(time, value); - value[0] = value[m_element]; - }; - - virtual void SerializeSpline(XmlNodeRef& node, bool bLoading) { return m_pInterpolator->SerializeSpline(node, bLoading); }; - - virtual ISplineBackup* Backup() { return m_pInterpolator->Backup(); }; - virtual void Restore(ISplineBackup* pBackup) { return m_pInterpolator->Restore(pBackup); }; - -public: - ISplineInterpolator* m_pInterpolator; - int m_element; -}; - -////////////////////////////////////////////////////////////////////////// -class CTimeOfDaySplineSet - : public ISplineSet -{ -public: - void AddSpline(ISplineInterpolator* pSpline) { m_splines.push_back(pSpline); }; - void RemoveAllSplines() { m_splines.clear(); } - - virtual ISplineInterpolator* GetSplineFromID(const string& id) - { - int i = atoi(id.c_str()); - if (i >= 0 && i < (int)m_splines.size()) - { - return m_splines[i]; - } - return 0; - }; - virtual string GetIDFromSpline(ISplineInterpolator* pSpline) - { - for (int i = 0; i < (int)m_splines.size(); i++) - { - if (m_splines[i] == pSpline) - { - string s; - s.Format("%d", i); - return s; - } - } - return ""; - } - virtual int GetSplineCount() const { return (int)m_splines.size(); } - virtual int GetKeyCountAtTime(float time, float threshold) const - { - int count = 0; - for (int i = 0; i < (int)m_splines.size(); i++) - { - if (m_splines[i]->FindKey(time, threshold) > 0) - { - count++; - } - } - return count; - } - -public: - std::vector m_splines; -}; - -////////////////////////////////////////////////////////////////////////// -CTimeOfDayDialog::CTimeOfDayDialog(QWidget* parent /* = nullptr */) - : QMainWindow(parent) - , m_ui(new Ui::TimeOfDayDialog) - , m_timelineCtrl(new TimelineWidget(this)) - , m_pHDRPane(new CHDRPane(this)) -{ - gEnv->pSystem->GetISystemEventDispatcher()->RegisterListener(this); - GetIEditor()->RegisterNotifyListener(this); - - m_ui->setupUi(this); - m_ui->parameters->Setup(); - splitDockWidget(m_ui->hdrPaneDock, m_ui->tasksDock, Qt::Horizontal); - - // Calculate our maximum time from the slider (23:59) - m_maxTime = m_ui->timelineSlider->maximum() / 60.0f; - - Init(); -} - -////////////////////////////////////////////////////////////////////////// -CTimeOfDayDialog::~CTimeOfDayDialog() -{ - m_alive = false; - GetIEditor()->UnregisterNotifyListener(this); - GetIEditor()->GetUndoManager()->RemoveListener(this); - - gEnv->pSystem->GetISystemEventDispatcher()->RemoveListener(this); - - QSettings settings; - settings.beginGroup(QStringLiteral("EnvironmentEditor")); - settings.setValue(QStringLiteral("state"), saveState()); -} - -const GUID& CTimeOfDayDialog::GetClassID() -{ - // {85FB1272-D858-4ca5-ABB4-04D484ABF51E} - static const GUID guid = { - 0x85fb1272, 0xd858, 0x4ca5, { 0xab, 0xb4, 0x4, 0xd4, 0x84, 0xab, 0xf5, 0x1e } - }; - return guid; -} - -void CTimeOfDayDialog::RegisterViewClass() -{ - AzToolsFramework::ViewPaneOptions options; - options.paneRect = QRect(100, 100, 1500, 800); - options.canHaveMultipleInstances = true; - options.isDockable = true; - - AzToolsFramework::RegisterViewPane(LyViewPane::TimeOfDayEditor, LyViewPane::CategoryOther, options); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::UpdateValues() -{ - if (!m_alive) - { - return; - } - - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - - RefreshPropertiesValues(); - - SetTimeRange(advInfo.fStartTime, advInfo.fEndTime, advInfo.fAnimSpeed); - UpdateUI(false); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) -{ - - - switch (event) - { - case ESYSTEM_EVENT_TIME_OF_DAY_SET: - // We update the UI in response to a system event (instead of with direct callbacks in the dialog) because time could be set by any of the dialog, - // e_TimeOfDay cvar, a Flow Graph Node or Track View. - UpdateUI(); - break; - default: - // do nothing - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::Init() -{ - // Load toolbar images for the main toolbar - m_ui->actionUndo->setIcon(QIcon(":/TimeOfDay/main-00.png")); - m_ui->actionRedo->setIcon(QIcon(":/TimeOfDay/main-01.png")); - m_ui->actionImportFile->setIcon(QIcon(":/TimeOfDay/main-02.png")); - m_ui->actionExportFile->setIcon(QIcon(":/TimeOfDay/main-03.png")); - m_ui->actionPlayPause->setIcon(QIcon(":/TimeOfDay/main-04.png")); - m_ui->actionSetTimeTo0000->setIcon(QIcon(":/TimeOfDay/main-05.png")); - m_ui->actionSetTimeTo0600->setIcon(QIcon(":/TimeOfDay/main-06.png")); - m_ui->actionSetTimeTo1200->setIcon(QIcon(":/TimeOfDay/main-07.png")); - m_ui->actionSetTimeTo1800->setIcon(QIcon(":/TimeOfDay/main-08.png")); - m_ui->actionSetTimeTo2400->setIcon(QIcon(":/TimeOfDay/main-09.png")); - m_ui->actionStartStopRecording->setIcon(QIcon(":/TimeOfDay/main-10.png")); - m_ui->actionHold->setIcon(QIcon(":/TimeOfDay/main-11.png")); - m_ui->actionFetch->setIcon(QIcon(":/TimeOfDay/main-12.png")); - - // Load the images for the spline edit toolbar - m_ui->tangentsToAutoButton->setIcon(QIcon(":/Common/spline_edit-00.png")); - m_ui->inTangentToZeroButton->setIcon(QIcon(":/Common/spline_edit-01.png")); - m_ui->inTangentToStepButton->setIcon(QIcon(":/Common/spline_edit-02.png")); - m_ui->inTangentToLinearButton->setIcon(QIcon(":/Common/spline_edit-03.png")); - m_ui->outTangentToZerobutton->setIcon(QIcon(":/Common/spline_edit-04.png")); - m_ui->outTangentToStepButton->setIcon(QIcon(":/Common/spline_edit-05.png")); - m_ui->outTangentToLinearButton->setIcon(QIcon(":/Common/spline_edit-06.png")); - m_ui->fitSplinesHorizontalButton->setIcon(QIcon(":/Common/spline_edit-07.png")); - m_ui->fitSplinesVerticalButton->setIcon(QIcon(":/Common/spline_edit-08.png")); - m_ui->splineSnapGridX->setIcon(QIcon(":/Common/spline_edit-09.png")); - m_ui->splineSnapGridY->setIcon(QIcon(":/Common/spline_edit-10.png")); - m_ui->previousKeyButton->setIcon(QIcon(":/Common/spline_edit-14.png")); - m_ui->nextKeyButton->setIcon(QIcon(":/Common/spline_edit-15.png")); - m_ui->removeAllExceptSelectedButton->setIcon(QIcon(":/Common/spline_edit-16.png")); - - m_timelineCtrl->SetTicksTextScale(24.0f); - m_timelineCtrl->SetTimeRange(Range(0, 1)); - - m_ui->spline->SetDefaultKeyTangentType(SPLINE_KEY_TANGENT_LINEAR); - m_ui->spline->SetTimelineCtrl(m_timelineCtrl); - m_ui->spline->SetTimeRange(Range(0, 1.0f)); - m_ui->spline->SetValueRange(Range(-1.0f, 1.0f)); - m_ui->spline->SetMinTimeEpsilon(0.00001f); - m_ui->spline->SetTooltipValueScale(24, 1); - - m_ui->colorGradient->SetNoZoom(false); - m_ui->colorGradient->SetTimeRange(0, 1.0f); - m_ui->colorGradient->LockFirstAndLastKeys(true); - m_ui->colorGradient->SetTooltipValueScale(24, 1); - - CreateProperties(); - UpdateValues(); - UpdateUI(); - - QSettings settings; - settings.beginGroup(QStringLiteral("EnvironmentEditor")); - QByteArray state = settings.value(QStringLiteral("state")).toByteArray(); - if (!state.isEmpty()) - { - restoreState(state); - } - - ResetSpline(0); - - m_ui->hdrPaneDock->setWidget(m_pHDRPane); - m_pHDRPane->UpdateFilmCurve(); - - QString copyAllLabel(tr("Copy All Parameters")); - QString pasteAllLabel(tr("Paste All Parameters")); - m_ui->parameters->AddCustomPopupMenuItem(copyAllLabel, AZStd::bind(&CTimeOfDayDialog::CopyAllProperties, this)); - m_ui->parameters->AddCustomPopupMenuItem(pasteAllLabel, AZStd::bind(&CTimeOfDayDialog::PasteAllProperties, this)); - m_pHDRPane->properties().AddCustomPopupMenuItem(copyAllLabel, AZStd::bind(&CTimeOfDayDialog::CopyAllProperties, this)); - m_pHDRPane->properties().AddCustomPopupMenuItem(pasteAllLabel, AZStd::bind(&CTimeOfDayDialog::PasteAllProperties, this)); - - m_ui->parameters->SetSelChangeCallback(AZStd::bind(&CTimeOfDayDialog::OnPropertySelected, this, AZStd::placeholders::_1)); - connect(m_pHDRPane, &CHDRPane::propertySelected, this, &CTimeOfDayDialog::HdrPropertySelected); - m_pHDRPane->properties().SetUpdateCallback(AZStd::bind(&CTimeOfDayDialog::OnUpdateProperties, this, AZStd::placeholders::_1)); - m_ui->parameters->SetUpdateCallback(AZStd::bind(&CTimeOfDayDialog::OnUpdateProperties, this, AZStd::placeholders::_1)); - - connect(m_ui->importFromFileClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnImport); - connect(m_ui->exportToFileClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnExport); - connect(m_ui->resetValuesClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnResetToDefaultValues); - connect(m_ui->expandAllClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnExpandAll); - connect(m_ui->collapseAllClickable, &QLabel::linkActivated, this, &CTimeOfDayDialog::OnCollapseAll); - - connect(m_ui->currentTimeEdit, &QTimeEdit::timeChanged, this, [=](const QTime& time) { SetTime(TimeOfDayDetails::floatFromQTime(time)); }); - connect(m_ui->startTimeEdit, &QTimeEdit::timeChanged, this, &CTimeOfDayDialog::StartTimeChanged); - connect(m_ui->endTimeEdit, &QTimeEdit::timeChanged, this, &CTimeOfDayDialog::EndTimeChanged); - auto doubleValueChanged = static_cast(&QDoubleSpinBox::valueChanged); - connect(m_ui->playSpeedDoubleSpinBox, doubleValueChanged, this, &CTimeOfDayDialog::OnChangeTimeAnimSpeed); - - connect(m_ui->playClickable, &QLabel::linkActivated, this, [=]() { m_ui->actionPlayPause->setChecked(true); }); - connect(m_ui->stopClickable, &QLabel::linkActivated, this, [=]() { m_ui->actionPlayPause->setChecked(false); }); - - connect(m_ui->forceSkyUpdateCheckBox, &QCheckBox::stateChanged, this, [=](int state) { gSettings.bForceSkyUpdate = state == Qt::Checked; }); - - connect(m_ui->actionUndo, &QAction::triggered, this, &CTimeOfDayDialog::OnUndo); - connect(m_ui->actionRedo, &QAction::triggered, this, &CTimeOfDayDialog::OnRedo); - connect(m_ui->actionImportFile, &QAction::triggered, this, &CTimeOfDayDialog::OnImport); - connect(m_ui->actionExportFile, &QAction::triggered, this, &CTimeOfDayDialog::OnExport); - - connect(m_ui->actionSetTimeTo0000, &QAction::triggered, this, [=]() { SetTime(0); }); - connect(m_ui->actionSetTimeTo0600, &QAction::triggered, this, [=]() { SetTime(6); }); - connect(m_ui->actionSetTimeTo1200, &QAction::triggered, this, [=]() { SetTime(12); }); - connect(m_ui->actionSetTimeTo1800, &QAction::triggered, this, [=]() { SetTime(18); }); - connect(m_ui->actionSetTimeTo2400, &QAction::triggered, this, [=]() { SetTime(m_maxTime); }); - - connect(m_ui->actionHold, &QAction::triggered, this, &CTimeOfDayDialog::OnHold); - connect(m_ui->actionFetch, &QAction::triggered, this, &CTimeOfDayDialog::OnFetch); - - connect(m_ui->tangentsToAutoButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_AUTO); }); - connect(m_ui->inTangentToZeroButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_IN_ZERO); }); - connect(m_ui->inTangentToStepButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_IN_STEP); }); - connect(m_ui->inTangentToLinearButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_IN_LINEAR); }); - connect(m_ui->outTangentToZerobutton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_OUT_ZERO); }); - connect(m_ui->outTangentToStepButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_OUT_STEP); }); - connect(m_ui->outTangentToLinearButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_TANGENT_OUT_LINEAR); }); - connect(m_ui->fitSplinesHorizontalButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_FIT_X); }); - connect(m_ui->fitSplinesVerticalButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_FIT_Y); }); - connect(m_ui->splineSnapGridX, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_SNAP_GRID_X); }); - connect(m_ui->splineSnapGridY, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_SNAP_GRID_Y); }); - connect(m_ui->previousKeyButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_PREVIOUS_KEY); }); - connect(m_ui->nextKeyButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_NEXT_KEY); }); - connect(m_ui->removeAllExceptSelectedButton, &QAbstractButton::clicked, this, [=]() { m_ui->spline->OnUserCommand(ID_SPLINE_FLATTEN_ALL); }); - - connect(m_ui->timelineSlider, &AzQtComponents::SliderInt::valueChanged, this, [=](int value) { SetTime(value / 60.0f); }); - - connect(m_ui->spline, &SplineWidget::beforeChange, this, &CTimeOfDayDialog::OnBeforeSplineChange); - connect(m_ui->spline, &SplineWidget::change, this, [=]() { OnSplineChange(m_ui->spline); }); - connect(m_ui->spline, &SplineWidget::scrollZoomRequested, this, &CTimeOfDayDialog::OnSplineCtrlScrollZoom); - connect(m_ui->spline, &SplineWidget::timeChange, this, &CTimeOfDayDialog::OnTimelineCtrlChange); - connect(m_ui->spline, &SplineWidget::keySelectionChange, this, [=]() { SetTimeFromActiveKey(); }); - - connect(m_ui->colorGradient, &CColorGradientCtrl::beforeChange, this, &CTimeOfDayDialog::OnBeforeSplineChange); - connect(m_ui->colorGradient, &CColorGradientCtrl::change, this, [=]() { OnSplineChange(m_ui->colorGradient); }); - connect(m_ui->colorGradient, &CColorGradientCtrl::activeKeyChange, this, [=]() { SetTimeFromActiveKey(true); }); - //connect(m_timelineCtrl.data(), &TimelineWidget::startChange, this, &CTimeOfDayDialog::OnBeforeSplineChange); - connect(m_timelineCtrl, &TimelineWidget::change, this, &CTimeOfDayDialog::OnTimelineCtrlChange); - - //ITimeOfDay *pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - //m_ui->currentTimeEdit->setTime(qTimeFromFloat(pTimeOfDay->GetTime())); - - GetIEditor()->GetUndoManager()->AddListener(this); -} - -void CTimeOfDayDialog::HdrPropertySelected(IVariable* v) -{ - if (v) - { - m_ui->parameters->ClearSelection(); - } - ResetSpline(v); -} - -void CTimeOfDayDialog::StartTimeChanged([[maybe_unused]] const QTime& time) -{ - float converted = TimeOfDayDetails::floatFromQTime(m_ui->startTimeEdit->time()); - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - advInfo.fStartTime = converted; - pTimeOfDay->SetAdvancedInfo(advInfo); -} - -void CTimeOfDayDialog::EndTimeChanged([[maybe_unused]] const QTime& time) -{ - float converted = TimeOfDayDetails::floatFromQTime(m_ui->endTimeEdit->time()); - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - advInfo.fEndTime = converted; - pTimeOfDay->SetAdvancedInfo(advInfo); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::CreateProperties() -{ - m_pVars = new CVarBlock; - - std::map groups; - - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - for (int i = 0; i < pTimeOfDay->GetVariableCount(); i++) - { - ITimeOfDay::SVariableInfo varInfo; - if (!pTimeOfDay->GetVariableInfo(i, varInfo)) - { - continue; - } - - if (TimeOfDayDetails::SkipUserInterface(varInfo.nParamId)) - { - continue; - } - - if (!varInfo.pInterpolator) - { - continue; - } - - IVariable* pGroupVar = stl::find_in_map(groups, varInfo.group, 0); - if (!pGroupVar) - { - // Create new group - pGroupVar = new CVariableArray(); - pGroupVar->SetName(varInfo.group); - pGroupVar->SetUserData(-1); - if (strcmp(varInfo.group, "HDR") == 0) // HDR parameters should go into the separate HDR pane. - { - m_pHDRPane->variables()->AddVariable(pGroupVar); - } - else - { - m_pVars->AddVariable(pGroupVar); - } - groups[varInfo.group] = pGroupVar; - } - - IVariable* pVar = 0; - if (varInfo.type == ITimeOfDay::TYPE_COLOR) - { - ////////////////////////////////////////////////////////////////////////// - // Add Var. - pVar = new CVariable(); - pVar->SetDataType(IVariable::DT_COLOR); - pVar->Set(Vec3(varInfo.fValue[0], varInfo.fValue[1], varInfo.fValue[2])); - } - else if (varInfo.type == ITimeOfDay::TYPE_FLOAT) - { - // Add Var. - pVar = new CVariable(); - pVar->Set(varInfo.fValue[0]); - pVar->SetLimits(varInfo.fValue[1], varInfo.fValue[2]); - } - - if (pVar) - { - pVar->SetName(varInfo.name); - pVar->SetHumanName(varInfo.displayName); - pGroupVar->AddVariable(pVar); - pVar->SetUserData(i); - } - } - - m_ui->parameters->AddVarBlock(m_pVars); - m_ui->parameters->ExpandAll(); - m_ui->parameters->EnableNotifyWithoutValueChange(true); - - m_pHDRPane->properties().AddVarBlock(m_pHDRPane->variables()); - m_pHDRPane->properties().ExpandAll(); - m_pHDRPane->properties().EnableNotifyWithoutValueChange(true); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnBeforeSplineChange() -{ - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoTimeOfDayObject()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnSplineChange(const QWidget* source) -{ - RefreshPropertiesValues(); - - if (source == m_ui->spline) - { - // Update the time of day settings on spline changes (e.g. keys being moved) - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - bool bForceUpdate = m_ui->forceSkyUpdateCheckBox->isChecked(); - pTimeOfDay->Update(true, bForceUpdate); - - m_timelineCtrl->update(); - m_ui->colorGradient->update(); - } - else if (source == m_timelineCtrl) - { - m_ui->colorGradient->update(); - m_ui->spline->update(); - } - else - { - m_ui->spline->SplinesChanged(); - m_ui->spline->update(); - m_timelineCtrl->update(); - } - - - if (m_ui->spline->GetSplineCount() > 0) - { - ISplineInterpolator* pSpline = m_ui->spline->GetSpline(0); - if (NULL != pSpline) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - const uint numVars = pTimeOfDay->GetVariableCount(); - for (uint i = 0; i < numVars; ++i) - { - ITimeOfDay::SVariableInfo varInfo; - pTimeOfDay->GetVariableInfo(i, varInfo); - } - } - } -} - -/** - * Update our time based on the currently active key - */ -void CTimeOfDayDialog::SetTimeFromActiveKey(bool useColorGradient) -{ - if (m_ui->spline->GetSplineCount() < 1) - { - return; - } - - ISplineInterpolator* pSpline = m_ui->spline->GetSpline(0); - if (!pSpline) - { - return; - } - - int activeKey = -1; - if (useColorGradient) - { - // If this method was triggered from our color gradient control, then - // retrieve its active key - activeKey = m_ui->colorGradient->GetActiveKey(); - } - else - { - // Otherwise this method was triggered from our main spline control, so - // we need to find the selected key by cycling through its keys - int numKeys = pSpline->GetKeyCount(); - for (int i = 0; i < numKeys; ++i) - { - if (pSpline->IsKeySelectedAtAnyDimension(i)) - { - activeKey = i; - break; - } - } - } - - if (activeKey == -1) - { - return; - } - - SetTime(pSpline->GetKeyTime(activeKey) * m_maxTime); -} - -////////////////////////////////////////////////////////////////////////// -float CTimeOfDayDialog::GetTime() const -{ - // This used to get the time from GetIEditor()->GetDocument()->GetCurrentMission()->GetTime(); but that seems like legacy CryEngine, so we're - // switching to grabbing it from the 3DEngine if possible - float time = .0f; - if (gEnv->p3DEngine->GetTimeOfDay()) - { - time = gEnv->p3DEngine->GetTimeOfDay()->GetTime(); - } - return time; -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::SetTimeRange(float fTimeStart, float fTimeEnd, float fSpeed) -{ - m_ui->startTimeEdit->setTime(TimeOfDayDetails::qTimeFromFloat(fTimeStart)); - m_ui->endTimeEdit->setTime(TimeOfDayDetails::qTimeFromFloat(fTimeEnd)); - - m_ui->playSpeedDoubleSpinBox->setValue(fSpeed); - - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - advInfo.fStartTime = fTimeStart; - advInfo.fEndTime = fTimeEnd; - advInfo.fAnimSpeed = fSpeed; - pTimeOfDay->SetAdvancedInfo(advInfo); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::RefreshPropertiesValues() -{ - m_ui->parameters->EnableUpdateCallback(false); - m_pHDRPane->properties().EnableUpdateCallback(false); - - // Interpolate internal values - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - for (int i = 0, numVars = pTimeOfDay->GetVariableCount(); i < numVars; i++) - { - ITimeOfDay::SVariableInfo varInfo; - if (!pTimeOfDay->GetVariableInfo(i, varInfo)) - { - continue; - } - if (TimeOfDayDetails::SkipUserInterface(varInfo.nParamId)) - { - continue; - } - - IVariable* pVar = FindVariable(varInfo.name); - - if (!pVar) - { - continue; - } - - switch (varInfo.type) - { - case ITimeOfDay::TYPE_FLOAT: - pVar->Set(varInfo.fValue[0]); - break; - case ITimeOfDay::TYPE_COLOR: - pVar->Set(Vec3(varInfo.fValue[0], varInfo.fValue[1], varInfo.fValue[2])); - break; - } - } - m_ui->parameters->EnableUpdateCallback(true); - m_pHDRPane->properties().EnableUpdateCallback(true); - - m_pHDRPane->UpdateFilmCurve(); - - // Notify that time of day values changed. - GetIEditor()->Notify(eNotify_OnTimeOfDayChange); -} - -void CTimeOfDayDialog::UpdateUI(bool updateProperties) -{ - float timeOfDayInHours = GetTime(); - - // update the Current Time edit field and Time Of Day Time Slider - QTime qTime = TimeOfDayDetails::qTimeFromFloat(timeOfDayInHours); - - QSignalBlocker sliderBlocker(m_ui->timelineSlider); - QSignalBlocker editBlocker(m_ui->currentTimeEdit); - - int v = qTime.msecsSinceStartOfDay(); - v /= 60000; - m_ui->timelineSlider->setValue(v); - m_ui->currentTimeEdit->setTime(qTime); - - m_ui->spline->SetTimeMarker(timeOfDayInHours / m_maxTime); - m_ui->colorGradient->SetTimeMarker(timeOfDayInHours / m_maxTime); - - if (updateProperties) - { - RefreshPropertiesValues(); - } - else - { - GetIEditor()->Notify(eNotify_OnTimeOfDayChange); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::SetTime(float time) -{ - const bool bForceUpdate = m_ui->forceSkyUpdateCheckBox->isChecked(); - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - - // This is probably legacy and deprecated, but leaving it here just in case it's needed by some legacy game. - if (GetIEditor()->GetDocument()->GetCurrentMission()) - { - GetIEditor()->GetDocument()->GetCurrentMission()->SetTime(time); - } - - // pTimeOfDay->SetTime will trigger a ESYSTEM_EVENT_TIME_OF_DAY_SET, which in turn will result in UpdateUI() being called - pTimeOfDay->SetTime(time, bForceUpdate); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnCloseScene: - case eNotify_OnBeginNewScene: - case eNotify_OnBeginSceneOpen: - { - // prevent crash during redraw which can happen before eNotify_OnEndSceneOpen - m_ui->spline->RemoveAllSplines(); - m_ui->colorGradient->SetSpline(0); - } - break; - case eNotify_OnEndSceneOpen: - case eNotify_OnEndNewScene: - { - UpdateValues(); - - m_pHDRPane->properties().ClearSelection(); - if (ReflectedPropertyItem* pSelectedItem = m_ui->parameters->GetSelectedItem()) - { - if (IVariable* pVar = pSelectedItem->GetVariable()) - { - ResetSpline(pVar); - } - } - } - break; - - case eNotify_OnIdleUpdate: - if (m_ui->actionPlayPause->isChecked()) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - float fHour = pTimeOfDay->GetTime(); - - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - // get the TOD cycle speed from UI - advInfo.fAnimSpeed = m_ui->playSpeedDoubleSpinBox->value(); - float dt = gEnv->pTimer->GetFrameTime(); - float fTime = fHour + dt * advInfo.fAnimSpeed; - if (fTime > advInfo.fEndTime) - { - fTime = advInfo.fStartTime; - } - if (fTime < advInfo.fStartTime) - { - fTime = advInfo.fEndTime; - } - SetTime(fTime); - } - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnTimelineCtrlChange() -{ - float fTime = m_timelineCtrl->GetTimeMarker(); - SetTime(fTime * m_maxTime); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnChangeTimeAnimSpeed(double value) -{ - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - // set current speed based on if we animating it currently or not - advInfo.fAnimSpeed = value; - pTimeOfDay->SetAdvancedInfo(advInfo); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnSplineCtrlScrollZoom() -{ - if (m_ui->spline && m_ui->colorGradient) - { - m_ui->colorGradient->SetZoom(m_ui->spline->GetZoom().x); - m_ui->colorGradient->SetOrigin(m_ui->spline->GetScrollOffset().x); - m_ui->colorGradient->update(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnImport() -{ - char szFilters[] = "Time Of Day Settings (*.xml);;Time Of Day Settings Old (*.tod)"; - QString fileName; - - if (CFileUtil::SelectFile(szFilters, GetIEditor()->GetLevelFolder(), fileName)) - { - XmlNodeRef root = GetISystem()->LoadXmlFromFile(fileName.toStdString().c_str()); - if (root) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - float fTime = GetTime(); - pTimeOfDay->Serialize(root, true); - pTimeOfDay->SetTime(fTime, true); - - UpdateValues(); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnExport() -{ - char szFilters[] = "Time Of Day Settings (*.xml)"; - QString fileName; - if (CFileUtil::SelectSaveFile(szFilters, "xml", GetIEditor()->GetLevelFolder(), fileName)) - { - // Write the light settings into the archive - XmlNodeRef node = XmlHelpers::CreateXmlNode("TimeOfDay"); - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - pTimeOfDay->Serialize(node, false); - XmlHelpers::SaveXmlNode(GetIEditor()->GetFileUtil(), node, fileName.toStdString().c_str()); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnExpandAll() -{ - m_ui->parameters->ExpandAll(); - m_pHDRPane->properties().ExpandAll(); -} -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnResetToDefaultValues() -{ - auto answer = QMessageBox::question(QApplication::activeWindow(), "Reset Values", "Are you sure you want to reset all values to their default values?"); - - if (answer == QMessageBox::Yes) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - - // Load the default time of day settings and use those to reset the time of day. - XmlNodeRef root = GetISystem()->LoadXmlFromFile("default_time_of_day.xml"); - if (root) - { - pTimeOfDay->Serialize(root, true); - } - else - { - QMessageBox::warning(QApplication::activeWindow(), "Reset Values", "Unable to read default time of day file (Editor/default_time_of_day.xml), initializing variables to default values.", QMessageBox::Ok); - - // If for some reason the file is missing or corrupted, recreate the variables with their default states. - // Note that these variables may be out of sync with the default_time_of_day.xml file. - pTimeOfDay->ResetVariables(); - } - - ITimeOfDay::SAdvancedInfo advInfo; - pTimeOfDay->GetAdvancedInfo(advInfo); - SetTimeRange(advInfo.fStartTime, advInfo.fEndTime, advInfo.fAnimSpeed); - RefreshPropertiesValues(); - - m_pHDRPane->properties().ClearSelection(); - ReflectedPropertyItem* selectedItem = m_ui->parameters->GetSelectedItem(); - if (selectedItem) - { - IVariable* var = selectedItem->GetVariable(); - if (var) - { - ResetSpline(var); - } - } - } -} -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnCollapseAll() -{ - m_ui->parameters->CollapseAll(); - m_pHDRPane->properties().CollapseAll(); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnUpdateProperties(IVariable* pVar) -{ - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - - int nIndex = -1; - if (pVar) - { - nIndex = pVar->GetUserData().toInt(); - } - - if (nIndex != -1) - { - ITimeOfDay::SVariableInfo varInfo; - if (pTimeOfDay->GetVariableInfo(nIndex, varInfo)) - { - float fTime = GetTime(); - float fSplineTime = fTime / m_maxTime; - - const float cNearestKeySearchEpsilon = 0.00001f; - int nKey = varInfo.pInterpolator->FindKey(fSplineTime, cNearestKeySearchEpsilon); - int nLastKey = varInfo.pInterpolator->GetKeyCount() - 1; - - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoTimeOfDayObject()); - } - - switch (varInfo.type) - { - case ITimeOfDay::TYPE_FLOAT: - { - float fVal = 0; - pVar->Get(fVal); - if (m_ui->actionStartStopRecording->isChecked()) - { - if (nKey < 0) - { - nKey = varInfo.pInterpolator->InsertKeyFloat(fSplineTime, fVal); - } - else - { - varInfo.pInterpolator->SetKeyValueFloat(nKey, fVal); - if (nKey == 0) - { - varInfo.pInterpolator->SetKeyValueFloat(nLastKey, fVal); - } - else if (nKey == nLastKey) - { - varInfo.pInterpolator->SetKeyValueFloat(0, fVal); - } - } - if (m_ui->spline && m_ui->spline->GetDefaultKeyTangentType() != SPLINE_KEY_TANGENT_NONE) - { - TimeOfDayDetails::SetKeyTangentType(varInfo.pInterpolator, nKey, m_ui->spline->GetDefaultKeyTangentType()); - } - } - - float v3[3] = {fVal, varInfo.fValue[1], varInfo.fValue[2]}; - pTimeOfDay->SetVariableValue(nIndex, v3); - } - break; - case ITimeOfDay::TYPE_COLOR: - { - Vec3 vVal; - pVar->Get(vVal); - float v3[3] = {vVal.x, vVal.y, vVal.z}; - if (m_ui->actionStartStopRecording->isChecked()) - { - if (nKey < 0) - { - nKey = varInfo.pInterpolator->InsertKeyFloat3(fSplineTime, v3); - } - else - { - varInfo.pInterpolator->SetKeyValueFloat3(nKey, v3); - if (nKey == 0) - { - varInfo.pInterpolator->SetKeyValueFloat3(nLastKey, v3); - } - else if (nKey == nLastKey) - { - varInfo.pInterpolator->SetKeyValueFloat3(0, v3); - } - } - if (m_ui->spline && m_ui->spline->GetDefaultKeyTangentType() != SPLINE_KEY_TANGENT_NONE) - { - TimeOfDayDetails::SetKeyTangentType(varInfo.pInterpolator, nKey, m_ui->spline->GetDefaultKeyTangentType()); - } - } - pTimeOfDay->SetVariableValue(nIndex, v3); - - m_ui->colorGradient->update(); - } - break; - } - - if (m_ui->spline) - { - m_ui->spline->update(); - } - - if (varInfo.nParamId == ITimeOfDay::PARAM_HDR_FILMCURVE_SHOULDER_SCALE - || varInfo.nParamId == ITimeOfDay::PARAM_HDR_FILMCURVE_LINEAR_SCALE - || varInfo.nParamId == ITimeOfDay::PARAM_HDR_FILMCURVE_TOE_SCALE - || varInfo.nParamId == ITimeOfDay::PARAM_HDR_FILMCURVE_WHITEPOINT) - { - m_pHDRPane->UpdateFilmCurve(); - } - - bool bForceUpdate = m_ui->forceSkyUpdateCheckBox->isChecked(); - pTimeOfDay->Update(false, bForceUpdate); - - GetIEditor()->Notify(eNotify_OnTimeOfDayChange); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnPropertySelected(IVariable *pVar) -{ - if (pVar) - { - m_pHDRPane->properties().ClearSelection(); - } - - if (pVar && pVar->GetType() == IVariable::ARRAY) - { - pVar = nullptr; - } - - ResetSpline(pVar); -} - - -void CTimeOfDayDialog::ResetSpline(IVariable* pVar) -{ - if (pVar) - { - ITimeOfDay* pTimeOfDay = gEnv->p3DEngine->GetTimeOfDay(); - ITimeOfDay::SVariableInfo varInfo; - int index = pVar->GetUserData().toInt(); - if (!pTimeOfDay->GetVariableInfo(index, varInfo)) - { - return; - } - - m_ui->spline->SetTimeRange(Range(0, 1.0f)); - m_ui->spline->RemoveAllSplines(); - - if (varInfo.type == ITimeOfDay::TYPE_COLOR) - { - QColor afColorArray[4]; - afColorArray[0] = QColor(255, 0, 0); - afColorArray[1] = QColor(0, 255, 0); - afColorArray[2] = QColor(0, 0, 255); - afColorArray[3] = QColor(255, 0, 255); //Pink... so you know it's wrong if you see it. - m_ui->spline->AddSpline(varInfo.pInterpolator, 0, afColorArray); - m_ui->spline->SetValueRange(Range(0, 1)); - - m_ui->colorGradient->SetSpline(varInfo.pInterpolator, TRUE); - m_ui->colorGradient->setEnabled(true); - m_ui->colorGradient->update(); - } - else - { - m_ui->colorGradient->setEnabled(false); - m_ui->colorGradient->SetSpline(0); - m_ui->colorGradient->update(); - - m_ui->spline->SetValueRange(Range(varInfo.fValue[1], varInfo.fValue[2])); - m_ui->spline->AddSpline(varInfo.pInterpolator, 0, QColor(0, 255, 0)); - } - m_ui->spline->SetSplineSet(0); - m_ui->spline->FitSplineToViewWidth(); - m_ui->spline->FitSplineHeightToValueRange(); - } - else - { - m_ui->spline->RemoveAllSplines(); - m_ui->colorGradient->setEnabled(false); - m_ui->colorGradient->SetSpline(0); - } - m_ui->spline->update(); -} - - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnHold() -{ - XmlNodeRef node = XmlHelpers::CreateXmlNode("TimeOfDay"); - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(node, false); - node->saveToFile((Path::GetUserSandboxFolder() + "TimeOfDayHold.xml").toUtf8().data()); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnFetch() -{ - XmlNodeRef node = XmlHelpers::LoadXmlFromFile((Path::GetUserSandboxFolder() + "TimeOfDayHold.xml").toUtf8().data()); - if (node) - { - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(node, true); - UpdateValues(); - UpdateUI(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnUndo() -{ - GetIEditor()->Undo(); - m_ui->spline->update(); - m_ui->colorGradient->update(); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::OnRedo() -{ - GetIEditor()->Redo(); - m_ui->spline->update(); - m_ui->colorGradient->update(); -} - -////////////////////////////////////////////////////////////////////////// -IVariable* CTimeOfDayDialog::FindVariable(const char* name) const -{ - IVariable* pVar = m_pVars->FindVariable(name); - if (!pVar) - { - pVar = m_pHDRPane->variables()->FindVariable(name); - } - - return pVar; -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::CopyAllProperties() -{ - CClipboard clipboard(this); - XmlNodeRef collectionNode = XmlHelpers::CreateXmlNode("PropertyCtrls"); - - ReflectedPropertyItem* pRoot = m_ui->parameters->GetRootItem(); - if (pRoot) // Main properties - { - XmlNodeRef rootNode = collectionNode->newChild("PropertyCtrl"); - for (int i = 0; i < pRoot->GetChildCount(); ++i) - { - m_ui->parameters->CopyItem(rootNode, pRoot->GetChild(i), true); - } - } - - pRoot = m_pHDRPane->properties().GetRootItem(); - if (pRoot) // HDR properties - { - XmlNodeRef rootNode = collectionNode->newChild("PropertyCtrl"); - for (int i = 0; i < pRoot->GetChildCount(); ++i) - { - m_pHDRPane->properties().CopyItem(rootNode, pRoot->GetChild(i), true); - } - } - - clipboard.Put(collectionNode); -} - -////////////////////////////////////////////////////////////////////////// -void CTimeOfDayDialog::PasteAllProperties() -{ - CClipboard clipboard(this); - CUndo undo("Paste Properties"); - - XmlNodeRef collectionNode = clipboard.Get(); - if (collectionNode != NULL && collectionNode->isTag("PropertyCtrls") - && collectionNode->getChildCount() == 2) - { - // Main properties - XmlNodeRef rootNode = collectionNode->getChild(0); - m_ui->parameters->SetValuesFromNode(rootNode); - - // HDR properties - rootNode = collectionNode->getChild(1); - m_pHDRPane->properties().SetValuesFromNode(rootNode); - } -} - -void CTimeOfDayDialog::SignalNumUndoRedo(const unsigned int& numUndo, const unsigned int& numRedo) -{ - m_ui->actionUndo->setEnabled(numUndo > 0); - m_ui->actionRedo->setEnabled(numRedo > 0); -} - -void CTimeOfDayDialog::resizeEvent([[maybe_unused]] QResizeEvent* event) -{ - if (m_ui->spline->GetSplineCount() == 0) - { - m_ui->spline->FitSplineToViewWidth(); - m_ui->spline->FitSplineToViewHeight(); - } -} - -CUndoTimeOfDayObject::CUndoTimeOfDayObject() -{ - m_undo = XmlHelpers::CreateXmlNode("Undo"); - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_undo, false); -} - -void CUndoTimeOfDayObject::Undo(bool bUndo) -{ - if (bUndo) - { - m_redo = XmlHelpers::CreateXmlNode("Redo"); - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_redo, false); - } - - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_undo, true); - UpdateTimeOfDayDialog(); -} - -void CUndoTimeOfDayObject::Redo() -{ - GetIEditor()->Get3DEngine()->GetTimeOfDay()->Serialize(m_redo, true); - UpdateTimeOfDayDialog(); -} - -void CUndoTimeOfDayObject::UpdateTimeOfDayDialog() -{ - CTimeOfDayDialog* targetDialog = FindViewPane(CTimeOfDayDialog::ClassName()); - if (targetDialog != nullptr) - { - targetDialog->UpdateValues(); - } -} - -#include diff --git a/Code/Sandbox/Editor/TimeOfDayDialog.h b/Code/Sandbox/Editor/TimeOfDayDialog.h deleted file mode 100644 index 8e9a9e92a8..0000000000 --- a/Code/Sandbox/Editor/TimeOfDayDialog.h +++ /dev/null @@ -1,182 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_TIMEOFDAYDIALOG_H -#define CRYINCLUDE_EDITOR_TIMEOFDAYDIALOG_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "Controls/TimelineCtrl.h" -#include -#include "Undo/IUndoManagerListener.h" -#include "LyViewPaneNames.h" -#include -#endif - -////////////////////////////////////////////////////////////////////////// - -class QResizeEvent; -class CCurveEditorCtrl; -class CHDRPane; - -namespace Ui { - class TimeOfDayDialog; -} - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -////////////////////////////////////////////////////////////////////////// -// Window that holds effector info. -////////////////////////////////////////////////////////////////////////// -class SANDBOX_API CTimeOfDayDialog - : public QMainWindow - , public IEditorNotifyListener - , public ISystemEventListener - , public IUndoManagerListener -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - Q_OBJECT -public: - static const char* ClassName() { return LyViewPane::TimeOfDayEditor; } - static const GUID& GetClassID(); - - CTimeOfDayDialog(QWidget* parent = nullptr); - ~CTimeOfDayDialog(); - - static void RegisterViewClass(); - void UpdateValues(); - - // overrides from ISystemEventListener - void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) override; - -protected: - void OnBeforeSplineChange(); - void OnSplineChange(const QWidget* source); - void OnPlayAnimFrom0(); - void OnChangeTimeAnimSpeed(double speed); - - void OnImport(); - void OnExport(); - void OnExpandAll(); - void OnResetToDefaultValues(); - void OnCollapseAll(); - - void OnHold(); - void OnFetch(); - void OnUndo(); - void OnRedo(); - - void OnPropertySelected(IVariable* node); - void OnSplineCtrlScrollZoom(); - void OnTimelineCtrlChange(); - - void Init(); - - void OnUpdateProperties(IVariable* var); - - void CreateProperties(); - - void SetTime(float time); - void SetTimeRange(float fTimeStart, float fTimeEnd, float fSpeed); - float GetTime() const; - - void RefreshPropertiesValues(); - void ResetSpline(IVariable* var); - - IVariable* FindVariable(const char* name) const; - - void CopyAllProperties(); - void PasteAllProperties(); - - void HdrPropertySelected(IVariable* v); - void StartTimeChanged(const QTime& time); - void EndTimeChanged(const QTime& time); - - ////////////////////////////////////////////////////////////////////////// - // IEditorNotifyListener - ////////////////////////////////////////////////////////////////////////// - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - ////////////////////////////////////////////////////////////////////////// - - // IUndoManagerListener - void SignalNumUndoRedo(const unsigned int& numUndo, const unsigned int& numRedo) override; - - void resizeEvent(QResizeEvent* event) override; - -private: - void UpdateUI(bool updateProperties=true); - void SetTimeFromActiveKey(bool useColorGradient = false); - - bool m_alive = true; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - QScopedPointer m_ui; - - CHDRPane* m_pHDRPane; - CVarBlockPtr m_pVars; - - TimelineWidget* m_timelineCtrl; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - float m_maxTime; -}; - -class CHDRPane - : public QWidget -{ - Q_OBJECT -public: - CHDRPane(CTimeOfDayDialog* pTODDlg); - - ReflectedPropertyControl& properties() { return *m_propsCtrl; } - CVarBlockPtr variables() { return m_pVars; } - - void UpdateFilmCurve(); - -signals: - void propertySelected(IVariable* variable); - -protected: - bool Init(); - void OnPropertySelected(IVariable*); - - bool GetFilmCurveParams(float& shoulderScale, float& midScale, float& toeScale, float& whitePoint) const; - - CTimeOfDayDialog* m_pTODDlg; - CCurveEditorCtrl* m_filmCurveCtrl; - ReflectedPropertyControl* m_propsCtrl; - CVarBlockPtr m_pVars; -}; - -/** Undo object stored when track is modified. -*/ -class CUndoTimeOfDayObject - : public IUndoObject -{ -public: - CUndoTimeOfDayObject(); - -protected: - virtual int GetSize() { return sizeof(*this); } - virtual QString GetDescription() { return "Time of Day"; }; - - virtual void Undo(bool bUndo); - virtual void Redo(); - -private: - void UpdateTimeOfDayDialog(); - - XmlNodeRef m_undo; - XmlNodeRef m_redo; -}; - -#endif // CRYINCLUDE_EDITOR_TIMEOFDAYDIALOG_H diff --git a/Code/Sandbox/Editor/TimeOfDayDialog.ui b/Code/Sandbox/Editor/TimeOfDayDialog.ui deleted file mode 100644 index 35e8e483a0..0000000000 --- a/Code/Sandbox/Editor/TimeOfDayDialog.ui +++ /dev/null @@ -1,980 +0,0 @@ - - - TimeOfDayDialog - - - - 0 - 0 - 1073 - 600 - - - - MainWindow - - - QMainWindow::AllowNestedDocks|QMainWindow::AllowTabbedDocks|QMainWindow::AnimatedDocks - - - - - 2 - - - - - - 1 - 0 - - - - - - - - 2 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Set In/Out Tangents to Auto - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Set In Tangent to Zero - - - - - - - 18 - 18 - - - - true - - - - - - - Set In Tangent to Step - - - - - - - 18 - 18 - - - - true - - - - - - - Set In Tangent to Linear - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Set Out Tangent to Zero - - - - - - - 18 - 18 - - - - true - - - - - - - Set Out Tangent to Step - - - - - - - 18 - 18 - - - - true - - - - - - - Set Out Tangent to Linear - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Fit Splines to the Visible Width - - - - - - - 18 - 18 - - - - true - - - - - - - Fit Splines to the Visible Height - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Snap to time grid - - - - 18 - 18 - - - - true - - - true - - - - - - - Snap to value grid - - - - 18 - 18 - - - - true - - - true - - - - - - - Qt::Vertical - - - - - - - Previous Key - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Vertical - - - - - - - Next Key - - - - - - - 18 - 18 - - - - true - - - - - - - Remove all Keys BUT This - - - - - - - 18 - 18 - - - - true - - - - - - - Qt::Horizontal - - - - 69 - 20 - - - - - - - - - - - - 0 - - - 0 - - - 0 - - - 0 - - - 0 - - - - - Qt::Horizontal - - - QSizePolicy::Fixed - - - - 40 - 20 - - - - - - - - - 0 - 0 - - - - - 0 - 35 - - - - - - - - - - - - 1 - 1 - - - - - - - - - 0 - - - - - Timeline - - - - 6 - - - 0 - - - - - 23:59 - - - Qt::AlignRight|Qt::AlignTop|Qt::AlignTrailing - - - - - - - 00:00 - - - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop - - - - - - - 12:00 - - - Qt::AlignHCenter|Qt::AlignTop - - - - - - - Qt::WheelFocus - - - 1439 - - - - - - - - - - - - - - - - - toolBar - - - - 32 - 32 - - - - false - - - TopToolBarArea - - - false - - - - - - - - - - - - - - - - - - - - - - - 350 - 40 - - - - QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable - - - Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea - - - HDR Settings - - - 1 - - - - - 0 - 0 - - - - - 150 - 0 - - - - - - - - - 0 - 0 - - - - - 450 - 50 - - - - QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable - - - Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea - - - Parameters - - - 2 - - - - - - - - 0 - 0 - - - - - 200 - 0 - - - - - - - - - - QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable - - - Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea - - - Time of Day Tasks - - - 1 - - - - - - - - 0 - 0 - - - - - 0 - - - - - Tasks - - - - - - Import From File - - - - - - - Export To File - - - - - - - Reset Values - - - - - - - Expand All - - - - - - - Collapse All - - - - - - - - - - Time - - - - - - Current Time - - - currentTimeEdit - - - - - - - - - - Start Time - - - startTimeEdit - - - - - - - - - - End Time - - - endTimeEdit - - - - - - - - - - Play Speed - - - playSpeedDoubleSpinBox - - - - - - - 0.001000000000000 - - - - - - - - - - Update Tasks - - - - - - Play - - - - - - - Stop - - - - - - - Force sky update - - - true - - - - - - - - - - Qt::Vertical - - - - 20 - 139 - - - - - - - - - - - - - false - - - Undo - - - Undo - - - - - false - - - Redo - - - Redo - - - - - Import File - - - Import File - - - - - Export File - - - Export File - - - - - true - - - Play/Pause - - - Play/Pause - - - - - 00 - - - Set Time to 00:00 - - - - - 06 - - - Set Time to 06:00 - - - - - 12 - - - Set Time to 12:00 - - - - - 18 - - - Set Time to 18:00 - - - - - 24 - - - Set Time to 23:59 - - - - - true - - - true - - - Start/Stop Recording - - - Start/Stop Recording - - - - - Hold - - - Hold - - - - - Fetch - - - Fetch - - - - - - ReflectedPropertyControl - QWidget -
Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.h
- 1 -
- - QCollapsibleGroupBox - QGroupBox -
QtUI/QCollapsibleGroupBox.h
- 1 -
- - ClickableLabel - QLabel -
QtUI/ClickableLabel.h
-
- - SplineWidget - QWidget -
Controls/SplineCtrlEx.h
- 1 -
- - CColorGradientCtrl - QWidget -
Controls/ColorGradientCtrl.h
- 1 -
- - AzQtComponents::DoubleSpinBox - QDoubleSpinBox -
AzQtComponents/Components/Widgets/SpinBox.h
-
- - TimeOfDaySlider - QWidget -
Controls/TimeOfDaySlider.h
- 1 -
-
- - timelineSlider - - - -
diff --git a/Code/Sandbox/Editor/TrackView/TrackViewDialog.cpp b/Code/Sandbox/Editor/TrackView/TrackViewDialog.cpp index 06184c0fc3..0179b779e8 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewDialog.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewDialog.cpp @@ -1505,12 +1505,6 @@ void CTrackViewDialog::OnEditorNotifyEvent(EEditorNotifyEvent event) m_bIgnoreUpdates = false; OnGameOrSimModeLock(false); break; - case eNotify_OnMissionChange: - if (!m_bIgnoreUpdates) - { - ReloadSequences(); - } - break; case eNotify_OnReloadTrackView: if (!m_bIgnoreUpdates) { diff --git a/Code/Sandbox/Editor/TrackView/TrackViewNodes.cpp b/Code/Sandbox/Editor/TrackView/TrackViewNodes.cpp index 3979bf3cca..0bde26edf1 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewNodes.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewNodes.cpp @@ -832,32 +832,7 @@ void CTrackViewNodesCtrl::UpdateAnimNodeRecord(CRecord* record, CTrackViewAnimNo } else if (nodeType == AnimNodeType::Material) { - // Check if a valid material can be found by the node name. - _smart_ptr pMaterial = nullptr; - QString matName; - int subMtlIndex = GetMatNameAndSubMtlIndexFromName(matName, animNode->GetName()); - pMaterial = gEnv->p3DEngine->GetMaterialManager()->FindMaterial(matName.toUtf8().data()); - if (pMaterial) - { - bool bMultiMat = pMaterial->GetSubMtlCount() > 0; - bool bMultiMatWithoutValidIndex = bMultiMat && (subMtlIndex < 0 || subMtlIndex >= pMaterial->GetSubMtlCount()); - bool bLeafMatWithIndex = !bMultiMat && subMtlIndex != -1; - if (bMultiMatWithoutValidIndex || bLeafMatWithIndex) - { - pMaterial = nullptr; - } - } - - if (!pMaterial) - { - record->setForeground(0, TextColorForInvalidMaterial); - } - else - { - // set to default color from palette - // materials that originally pointed to material groups and are changed to sub-materials need this to reset their color - record->setForeground(0, palette().color(foregroundRole())); - } + record->setForeground(0, TextColorForInvalidMaterial); } // Mark the active director and other directors properly. @@ -2163,43 +2138,6 @@ int CTrackViewNodesCtrl::ShowPopupMenuSingleSelection(SContextMenu& contextMenu, bAppended = true; } - // Sub material menu - if (bOnNode && animNode->GetType() == AnimNodeType::Material) - { - QString matName; - int subMtlIndex = GetMatNameAndSubMtlIndexFromName(matName, animNode->GetName()); - _smart_ptr pMtl = gEnv->p3DEngine->GetMaterialManager()->FindMaterial(matName.toUtf8().data()); - bool bMultMatNode = pMtl ? pMtl->GetSubMtlCount() > 0 : false; - - bool bMatAppended = false; - - if (bMultMatNode) - { - for (int k = 0; k < pMtl->GetSubMtlCount(); ++k) - { - _smart_ptr pSubMaterial = pMtl->GetSubMtl(k); - - if (pSubMaterial) - { - QString subMaterialName = pSubMaterial->GetName(); - - if (!subMaterialName.isEmpty()) - { - AddMenuSeperatorConditional(contextMenu.main, bAppended); - QString subMatName = QString("[%1] %2").arg(k + 1).arg(subMaterialName); - QAction* a = contextMenu.main.addAction(subMatName); - a->setData(eMI_SelectSubmaterialBase + k); - a->setCheckable(true); - a->setChecked(k == subMtlIndex); - bMatAppended = true; - } - } - } - } - - bAppended = bAppended || bMatAppended; - } - // Delete track menu if (bOnTrackNotSub) { diff --git a/Code/Sandbox/Editor/Util/CubemapUtils.cpp b/Code/Sandbox/Editor/Util/CubemapUtils.cpp index a143b7e5ce..bd650abaa8 100644 --- a/Code/Sandbox/Editor/Util/CubemapUtils.cpp +++ b/Code/Sandbox/Editor/Util/CubemapUtils.cpp @@ -30,6 +30,7 @@ #include "Util/ImageTIF.h" #include "Objects/BaseObject.h" +#include class CubemapSizeModel : public QAbstractListModel diff --git a/Code/Sandbox/Editor/Util/FileUtil.cpp b/Code/Sandbox/Editor/Util/FileUtil.cpp index fc5eca1952..8dd379f096 100644 --- a/Code/Sandbox/Editor/Util/FileUtil.cpp +++ b/Code/Sandbox/Editor/Util/FileUtil.cpp @@ -2088,7 +2088,6 @@ void CFileUtil::GatherAssetFilenamesFromLevel(std::set& rOutFilenames, rOutFilenames.clear(); CBaseObjectsArray objArr; CUsedResources usedRes; - IMaterialManager* pMtlMan = GetIEditor()->Get3DEngine()->GetMaterialManager(); GetIEditor()->GetObjectManager()->GetObjects(objArr); @@ -2116,66 +2115,6 @@ void CFileUtil::GatherAssetFilenamesFromLevel(std::set& rOutFilenames, rOutFilenames.insert(tmpStr); } } - - uint32 mtlCount = 0; - - pMtlMan->GetLoadedMaterials(NULL, mtlCount); - - if (mtlCount > 0) - { - AZStd::vector<_smart_ptr> arrMtls; - - arrMtls.resize(mtlCount); - pMtlMan->GetLoadedMaterials(&arrMtls, mtlCount); - - for (size_t i = 0; i < mtlCount; ++i) - { - _smart_ptr pMtl = arrMtls[i]; - - size_t subMtls = pMtl->GetSubMtlCount(); - - // for the main material - IRenderShaderResources* pShaderRes = pMtl->GetShaderItem().m_pShaderResources; - - // add the material filename - rOutFilenames.insert(pMtl->GetName()); - - if (pShaderRes) - { - for ( auto iter= pShaderRes->GetTexturesResourceMap()->begin() ; - iter!= pShaderRes->GetTexturesResourceMap()->end() ; ++iter ) - { - SEfResTexture* pTex = &(iter->second); - // add the texture filename - rOutFilenames.insert(pTex->m_Name.c_str()); - } - } - - // for the submaterials - for (size_t s = 0; s < subMtls; ++s) - { - _smart_ptr pSubMtl = pMtl->GetSubMtl(s); - - // fill up dependencies - if (pSubMtl) - { - IRenderShaderResources* pShaderRes2 = pSubMtl->GetShaderItem().m_pShaderResources; - - rOutFilenames.insert(pSubMtl->GetName()); - - if (pShaderRes2) - { - for (auto iter = pShaderRes2->GetTexturesResourceMap()->begin(); - iter != pShaderRes2->GetTexturesResourceMap()->end(); ++iter) - { - SEfResTexture* pTex = &(iter->second); - rOutFilenames.insert(pTex->m_Name.c_str()); - } - } - } - } - } - } } uint32 CFileUtil::GetAttributes(const char* filename, bool bUseSourceControl /*= true*/) diff --git a/Code/Sandbox/Editor/Util/KDTree.cpp b/Code/Sandbox/Editor/Util/KDTree.cpp index b407305a93..71ec798005 100644 --- a/Code/Sandbox/Editor/Util/KDTree.cpp +++ b/Code/Sandbox/Editor/Util/KDTree.cpp @@ -14,6 +14,8 @@ #include "KDTree.h" +#include + class KDTreeNode { public: diff --git a/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp b/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp deleted file mode 100644 index 206131e5a9..0000000000 --- a/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp +++ /dev/null @@ -1,445 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "EditorDefs.h" - -#include "VariableTypeInfo.h" -#include "TypeInfo_impl.h" -#include "IShader_info.h" - -#ifndef AZ_MONOLITHIC_BUILD -#include "I3DEngine_info.h" -#endif - -#include "Variable.h" -#include "UIEnumsDatabase.h" - -// CryCommon -#include - - -IVariable* CVariableTypeInfo::Create(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault) -{ - pAddress = VarInfo.GetAddress(pAddress); - pAddressDefault = VarInfo.GetAddress(pAddressDefault); - - EType eType = GetType(VarInfo.Type); - if (eType == ARRAY) - { - return new CVariableTypeInfoStruct(VarInfo, pAddress, pAddressDefault); - } - - if (VarInfo.Type.EnumElem(0)) - { - return new CVariableTypeInfoEnum(VarInfo, pAddress, pAddressDefault); - } - - ISplineInterpolator* pSpline = 0; - if (VarInfo.Type.ToValue(pAddress, pSpline)) - { - return new CVariableTypeInfoSpline(VarInfo, pAddress, pAddressDefault, pSpline); - } - - return new CVariableTypeInfo(VarInfo, pAddress, pAddressDefault, eType); -} - -CVariableTypeInfo::EType CVariableTypeInfo::GetType(CTypeInfo const& typeInfo) -{ - // Translation to editor type values is currently done with some clunky type and name testing. - if (typeInfo.HasSubVars()) - { - if (typeInfo.IsType() && !typeInfo.NextSubVar(0)->Type.IsType()) - { - // This is a vector type (and not a sub-classed vector type) - return IVariable::VECTOR; - } - else - { - return IVariable::ARRAY; - } - } - else if (typeInfo.IsType()) - { - return IVariable::BOOL; - } - else if (typeInfo.IsType() || typeInfo.IsType()) - { - return IVariable::INT; - } - else if (typeInfo.IsType()) - { - return IVariable::FLOAT; - } - return IVariable::STRING; -} - -CVariableTypeInfo::CVariableTypeInfo(CTypeInfo::CVarInfo const& VarInfo, - void* pAddress, const void* pAddressDefault, EType eType) - : m_pVarInfo(&VarInfo) - , m_pData(pAddress) - , m_pDefaultData(pAddressDefault) -{ - SetName(SpacedName(VarInfo.GetName())); - SetTypes(VarInfo.Type, eType); - SetFlags(IVariable::UI_UNSORTED | IVariable::UI_HIGHLIGHT_EDITED); - SetDescription(VarInfo.GetComment()); -} - -void CVariableTypeInfo::SetTypes(CTypeInfo const& TypeInfo, EType eType) -{ - m_pTypeInfo = &TypeInfo; - m_eType = eType; - - SetDataType(DT_SIMPLE); - if (m_eType == VECTOR) - { - if (m_name == "Color") - { - SetDataType(DT_COLOR); - } - } - else if (m_eType == STRING) - { - if (m_name == "Texture" || m_name == "Glow Map" || m_name == "Normal Map" || m_name == "Trail Fading") - { - SetDataType(DT_TEXTURE); - } - else if (m_name == "Geometry") - { - SetDataType(DT_OBJECT); - } - else if (m_name == "Start Trigger" || m_name == "Stop Trigger") - { - SetDataType(DT_AUDIO_TRIGGER); - } - else if (m_name == "GeomCache") - { - SetDataType(DT_GEOM_CACHE); - } - } -} - -// IVariable implementation. -CVariableTypeInfo::EType CVariableTypeInfo::GetType() const -{ - return m_eType; -} - -int CVariableTypeInfo::GetSize() const -{ - return m_pTypeInfo->Size; -} - -void CVariableTypeInfo::GetLimits(float& fMin, float& fMax, float& fStep, bool& bHardMin, bool& bHardMax) -{ - // Get hard limits from variable type, or vector element type. - const CTypeInfo* pLimitType = m_pTypeInfo; - if ((m_eType == VECTOR || m_eType == VECTOR2) && m_pTypeInfo->NextSubVar(0)) - { - pLimitType = &m_pTypeInfo->NextSubVar(0)->Type; - } - bHardMin = pLimitType->GetLimit(eLimit_Min, fMin); - bHardMax = pLimitType->GetLimit(eLimit_Max, fMax); - pLimitType->GetLimit(eLimit_Step, fStep); - - // Check var attrs for additional limits. - if (m_pVarInfo->GetAttr("SoftMin", fMin)) - { - bHardMin = false; - } - else if (m_pVarInfo->GetAttr("Min", fMin)) - { - bHardMin = true; - } - - if (m_pVarInfo->GetAttr("SoftMax", fMax)) - { - bHardMax = false; - } - else if (m_pVarInfo->GetAttr("Max", fMax)) - { - bHardMax = true; - } -} - -void CVariableTypeInfo::Set(const char* value) -{ - m_pTypeInfo->FromString(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(const QString& value) -{ - Set(value.toUtf8().data()); -} - -void CVariableTypeInfo::Set(float value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(int value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(bool value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(const Vec2& value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Set(const Vec3& value) -{ - m_pTypeInfo->FromValue(m_pData, value); - OnSetValue(false); -} - -void CVariableTypeInfo::Get(QString& value) const -{ - value = (const char*)m_pTypeInfo->ToString(m_pData); -} - -void CVariableTypeInfo::Get(float& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -void CVariableTypeInfo::Get(int& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -void CVariableTypeInfo::Get(bool& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -void CVariableTypeInfo::Get(Vec2& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -void CVariableTypeInfo::Get(Vec3& value) const -{ - m_pTypeInfo->ToValue(m_pData, value); -} - -bool CVariableTypeInfo::HasDefaultValue() const -{ - return m_pTypeInfo->ValueEqual(m_pData, m_pDefaultData); -} - -void CVariableTypeInfo::ResetToDefault() -{ - QString strVal = m_pTypeInfo->ToString(m_pDefaultData).c_str(); - Set(strVal); -} - -IVariable* CVariableTypeInfo::Clone([[maybe_unused]] bool bRecursive) const -{ - // Simply use a string var for universal conversion. - IVariable* pClone = new CVariable(); - QString str; - Get(str); - pClone->Set(str); - - //add extra information for the clone: Name, DataType - pClone->SetName(GetName()); - pClone->SetDataType(GetDataType()); - //use UserData to save eType since String Variable's GetType always return STRING - pClone->SetUserData(GetType()); - - return pClone; -} - -void CVariableTypeInfo::CopyValue(IVariable* fromVar) -{ - assert(fromVar); - QString str; - fromVar->Get(str); - Set(str); -} - -CVariableTypeInfoEnum::CTypeInfoEnumList::CTypeInfoEnumList(CTypeInfo const& info) - : TypeInfo(info) -{ -} - -QString CVariableTypeInfoEnum::CTypeInfoEnumList::GetItemName(uint index) -{ - return TypeInfo.EnumElem(index); -} - -CVariableTypeInfoEnum::CVariableTypeInfoEnum(CTypeInfo::CVarInfo const& VarInfo, - void* pAddress, const void* pAddressDefault, IVarEnumList* pEnumList) - : CVariableTypeInfo(VarInfo, pAddress, pAddressDefault, UNKNOWN) -{ - // Use custom enum, or enum defined in TypeInfo. - m_enumList = pEnumList ? pEnumList : new CTypeInfoEnumList(VarInfo.Type); -} - -IVarEnumList* CVariableTypeInfoEnum::GetEnumList() const -{ - return m_enumList; -} - -CVariableTypeInfoSpline::CVariableTypeInfoSpline(CTypeInfo::CVarInfo const& VarInfo, - void* pAddress, const void* pAddressDefault, ISplineInterpolator* pSpline) - : CVariableTypeInfo(VarInfo, pAddress, pAddressDefault, STRING) - , m_pSpline(pSpline) -{ - if (m_pSpline && m_pSpline->GetNumDimensions() == 3) - { - SetDataType(DT_CURVE | DT_COLOR); - } - else - { - SetDataType(DT_CURVE | DT_PERCENT); - } -} - -CVariableTypeInfoSpline::~CVariableTypeInfoSpline() -{ - delete m_pSpline; -} - -ISplineInterpolator* CVariableTypeInfoSpline::GetSpline() -{ - //if m_pSpline wasn't created or the data used to create spline was changed, we need create the m_pSpline - int flags = GetFlags(); - if (m_pSpline == nullptr || flags & UI_CREATE_SPLINE) - { - if (m_pSpline != nullptr) - { - delete m_pSpline; - m_pSpline = nullptr; - } - m_pTypeInfo->ToValue(m_pData, m_pSpline); - flags &= ~UI_CREATE_SPLINE; - SetFlags(flags); - } - return m_pSpline; -} - -void CVariableTypeInfoSpline::OnSetValue(bool bRecursive) -{ - m_pTypeInfo->ToValue(m_pData, m_pSpline); - CVariableTypeInfo::OnSetValue(bRecursive); -} - -CVariableTypeInfoStruct::CVariableTypeInfoStruct(CTypeInfo::CVarInfo const& VarInfo, - void* pAddress, const void* pAddressDefault) - : CVariableTypeInfo(VarInfo, pAddress, pAddressDefault, ARRAY) -{ - ProcessSubStruct(VarInfo, pAddress, pAddressDefault); -} - -void CVariableTypeInfoStruct::ProcessSubStruct(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault) -{ - for AllSubVars(pSubVar, VarInfo.Type) - { - if (!*pSubVar->GetName()) - { - EType eType = GetType(pSubVar->Type); - if (eType == ARRAY) - { - // Recursively process nameless or base struct. - ProcessSubStruct(*pSubVar, pSubVar->GetAddress(pAddress), pSubVar->GetAddress(pAddressDefault)); - } - else if (pSubVar == VarInfo.Type.NextSubVar(0)) - { - // Inline edit first sub-var in main field. - SetTypes(pSubVar->Type, eType); - } - } - else - { - IVariable* pVar = CVariableTypeInfo::Create(*pSubVar, pAddress, pAddressDefault); - m_Vars.push_back(pVar); - } - } -} - -QString CVariableTypeInfoStruct::GetDisplayValue() const -{ - return (const char*)m_pTypeInfo->ToString(m_pData); -} - -void CVariableTypeInfoStruct::OnSetValue(bool bRecursive) -{ - CVariableBase::OnSetValue(bRecursive); - if (bRecursive) - { - for (Vars::iterator it = m_Vars.begin(); it != m_Vars.end(); ++it) - { - (*it)->OnSetValue(true); - } - } -} - -void CVariableTypeInfoStruct::SetFlagRecursive(EFlags flag) -{ - CVariableBase::SetFlagRecursive(flag); - for (Vars::iterator it = m_Vars.begin(); it != m_Vars.end(); ++it) - { - (*it)->SetFlagRecursive(flag); - } -} - -void CVariableTypeInfoStruct::CopyValue(IVariable* fromVar) -{ - assert(fromVar); - if (fromVar->GetType() != IVariable::ARRAY) - { - CVariableTypeInfo::CopyValue(fromVar); - } - - int numSrc = fromVar->GetNumVariables(); - int numTrg = m_Vars.size(); - for (int i = 0; i < numSrc && i < numTrg; i++) - { - // Copy Every child variable. - m_Vars[i]->CopyValue(fromVar->GetVariable(i)); - } -} - -int CVariableTypeInfoStruct::GetNumVariables() const -{ - return m_Vars.size(); -} - -IVariable* CVariableTypeInfoStruct::GetVariable(int index) const -{ - return m_Vars[index]; -} - -CUIEnumsDBList::CUIEnumsDBList(CUIEnumsDatabase_SEnum const* pEnumList) - : m_pEnumList(pEnumList) -{ -} - -QString CUIEnumsDBList::GetItemName(uint index) -{ - if (index >= m_pEnumList->strings.size()) - { - return NULL; - } - return m_pEnumList->strings[index]; -} diff --git a/Code/Sandbox/Editor/Util/VariableTypeInfo.h b/Code/Sandbox/Editor/Util/VariableTypeInfo.h deleted file mode 100644 index 1e36d1ca96..0000000000 --- a/Code/Sandbox/Editor/Util/VariableTypeInfo.h +++ /dev/null @@ -1,221 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_UTIL_VARIABLETYPEINFO_H -#define CRYINCLUDE_EDITOR_UTIL_VARIABLETYPEINFO_H -#pragma once - -#include "Variable.h" -#include "UIEnumsDatabase.h" -#include "VariableTypeInfo.h" - -#include - -////////////////////////////////////////////////////////////////////////// -// Adaptors for TypeInfo-defined variables to IVariable - -inline QString SpacedName(const char* sName) -{ - // Split name with spaces. - QString sSpacedName = sName; - for (int i = 1; i < sSpacedName.length(); i++) - { - if (sSpacedName[i].isUpper() && sSpacedName[i - 1].isLower()) - { - sSpacedName.insert(i, ' '); - i++; - } - } - return sSpacedName; -} - -////////////////////////////////////////////////////////////////////////// -// Scalar variable -////////////////////////////////////////////////////////////////////////// - -class EDITOR_CORE_API CVariableTypeInfo - : public CVariableBase -{ -public: - // Dynamic constructor function - static IVariable* Create(CTypeInfo::CVarInfo const& VarInfo, void* pBaseAddress, const void* pBaseAddressDefault); - - static EType GetType(CTypeInfo const& TypeInfo); - - CVariableTypeInfo(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault, EType eType); - - void SetTypes(CTypeInfo const& TypeInfo, EType eType); - - // IVariable implementation. - virtual EType GetType() const; - virtual int GetSize() const; - - virtual void GetLimits(float& fMin, float& fMax, float& fStep, bool& bHardMin, bool& bHardMax); - - ////////////////////////////////////////////////////////////////////////// - // Access operators. - ////////////////////////////////////////////////////////////////////////// - - virtual void Set(const char* value); - - virtual void Set(const QString& value); - - virtual void Set(float value); - - virtual void Set(int value); - - virtual void Set(bool value); - - virtual void Set(const Vec2& value); - - virtual void Set(const Vec3& value); - - virtual void Get(QString& value) const; - - virtual void Get(float& value) const; - - virtual void Get(int& value) const; - - virtual void Get(bool& value) const; - - virtual void Get(Vec2& value) const; - - virtual void Get(Vec3& value) const; - - virtual bool HasDefaultValue() const; - - virtual void ResetToDefault(); - - virtual IVariable* Clone(bool bRecursive) const; - - // To do: This could be more efficient ? - virtual void CopyValue(IVariable* fromVar); - -protected: - CTypeInfo::CVarInfo const* m_pVarInfo; - CTypeInfo const* m_pTypeInfo; // TypeInfo system structure for this var. - void* m_pData; // Existing address in memory. Directly modified. - const void* m_pDefaultData; // Address of default data for this var. - EType m_eType; // Type info for editor. - IEditor* m_pEditor; -}; - -////////////////////////////////////////////////////////////////////////// -// Enum variable -////////////////////////////////////////////////////////////////////////// - -class EDITOR_CORE_API CVariableTypeInfoEnum - : public CVariableTypeInfo -{ - struct CTypeInfoEnumList - : IVarEnumList - { - CTypeInfo const& TypeInfo; - - CTypeInfoEnumList(CTypeInfo const& info); - - virtual QString GetItemName(uint index); - }; - -public: - - // Constructor. - CVariableTypeInfoEnum(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault, IVarEnumList* pEnumList = 0); - - ////////////////////////////////////////////////////////////////////////// - // Additional IVariable implementation. - ////////////////////////////////////////////////////////////////////////// - - IVarEnumList* GetEnumList() const; - -protected: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - TSmartPtr m_enumList; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -////////////////////////////////////////////////////////////////////////// -// Spline variable -////////////////////////////////////////////////////////////////////////// - -class EDITOR_CORE_API CVariableTypeInfoSpline - : public CVariableTypeInfo -{ - -public: - - // Constructor. - CVariableTypeInfoSpline(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault, ISplineInterpolator* pSpline); - - ~CVariableTypeInfoSpline(); - - virtual ISplineInterpolator* GetSpline(); - - //! Overrides CVariableTypeInfo to keep m_pSpline in sync with CVariableTypeInfo::m_pData - //! when Set(value) functions are called - void OnSetValue(bool bRecursive) override; - -private: - ISplineInterpolator* m_pSpline; -}; - -////////////////////////////////////////////////////////////////////////// -// Struct variable -// Inherits implementation from CVariableArray -////////////////////////////////////////////////////////////////////////// - -class EDITOR_CORE_API CVariableTypeInfoStruct - : public CVariableTypeInfo -{ -public: - // Constructor. - CVariableTypeInfoStruct(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault); - - void ProcessSubStruct(CTypeInfo::CVarInfo const& VarInfo, void* pAddress, const void* pAddressDefault); - - ////////////////////////////////////////////////////////////////////////// - // IVariable implementation. - ////////////////////////////////////////////////////////////////////////// - - virtual QString GetDisplayValue() const; - - virtual void OnSetValue(bool bRecursive); - - void SetFlagRecursive(EFlags flag) override; - - void CopyValue(IVariable* fromVar); - - int GetNumVariables() const; - - IVariable* GetVariable(int index) const; - -protected: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - typedef std::vector Vars; - Vars m_Vars; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -struct EDITOR_CORE_API CUIEnumsDBList - : IVarEnumList -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - CUIEnumsDatabase_SEnum const* m_pEnumList; - - CUIEnumsDBList(CUIEnumsDatabase_SEnum const* pEnumList); - - virtual QString GetItemName(uint index); -}; - -#endif // CRYINCLUDE_EDITOR_UTIL_VARIABLETYPEINFO_H diff --git a/Code/Sandbox/Editor/editor_core_files.cmake b/Code/Sandbox/Editor/editor_core_files.cmake index 85db7ec86b..1aecbd03f6 100644 --- a/Code/Sandbox/Editor/editor_core_files.cmake +++ b/Code/Sandbox/Editor/editor_core_files.cmake @@ -54,13 +54,11 @@ set(FILES Util/MemoryBlock.cpp Util/Variable.cpp Util/UndoUtil.cpp - Util/VariableTypeInfo.cpp Util/VariablePropertyType.cpp Clipboard.h Util/MemoryBlock.h Util/Variable.h Util/UndoUtil.h - Util/VariableTypeInfo.h Util/VariablePropertyType.h Util/RefCountBase.h Util/PathUtil.h diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index a0c22c9a14..f6537909e9 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -323,11 +323,6 @@ set(FILES AzAssetBrowser/AzAssetBrowserWindow.cpp AzAssetBrowser/AzAssetBrowserWindow.h AzAssetBrowser/AzAssetBrowserWindow.ui - AzAssetBrowser/Preview/LegacyPreviewer.cpp - AzAssetBrowser/Preview/LegacyPreviewer.h - AzAssetBrowser/Preview/LegacyPreviewer.ui - AzAssetBrowser/Preview/LegacyPreviewerFactory.cpp - AzAssetBrowser/Preview/LegacyPreviewerFactory.h AssetDatabase/AssetDatabaseLocationListener.h AssetDatabase/AssetDatabaseLocationListener.cpp AssetImporter/AssetImporterManager/AssetImporterDragAndDropHandler.cpp @@ -376,8 +371,7 @@ set(FILES Controls/MultiMonHelper.h Controls/NumberCtrl.cpp Controls/NumberCtrl.h - Controls/PreviewModelCtrl.cpp - Controls/PreviewModelCtrl.h + Controls/NumberCtrl.h Controls/SplineCtrl.cpp Controls/SplineCtrl.h Controls/SplineCtrlEx.cpp @@ -386,8 +380,6 @@ set(FILES Controls/TextEditorCtrl.h Controls/TimelineCtrl.cpp Controls/TimelineCtrl.h - Controls/TimeOfDaySlider.cpp - Controls/TimeOfDaySlider.h Controls/WndGridHelper.h Controls/ReflectedPropertyControl/PropertyAnimationCtrl.cpp Controls/ReflectedPropertyControl/PropertyAnimationCtrl.h @@ -460,8 +452,6 @@ set(FILES LevelFileDialog.qrc LevelFileDialog.h LevelFileDialog.ui - PanelPreview.cpp - PanelPreview.h QuickAccessBar.cpp QuickAccessBar.h QuickAccessBar.ui @@ -495,10 +485,6 @@ set(FILES IconListDialog.ui UndoDropDown.cpp UndoDropDown.h - TimeOfDayDialog.cpp - TimeOfDayDialog.h - TimeOfDayDialog.ui - TimeOfDay.qrc DimensionsDialog.cpp DimensionsDialog.h DimensionsDialog.ui @@ -528,11 +514,7 @@ set(FILES GameResourcesExporter.cpp GameExporter.h GameResourcesExporter.h - Geometry/EdGeometry.cpp - Geometry/EdMesh.cpp Geometry/TriMesh.cpp - Geometry/EdGeometry.h - Geometry/EdMesh.h Geometry/TriMesh.h AboutDialog.h AboutDialog.ui @@ -560,8 +542,6 @@ set(FILES LevelIndependentFileMan.h LogFileImpl.cpp LogFileImpl.h - Mission.cpp - Mission.h Objects/ClassDesc.cpp Objects/ClassDesc.h Objects/IEntityObjectListener.h @@ -654,8 +634,6 @@ set(FILES LightmapCompiler/SimpleTriangleRasterizer.cpp ResourceSelectorHost.cpp ResourceSelectorHost.h - ThumbnailGenerator.cpp - ThumbnailGenerator.h ToolBox.cpp TrackViewNewSequenceDialog.cpp TrackViewNewSequenceDialog.ui @@ -687,9 +665,6 @@ set(FILES ShaderEnum.h SurfaceTypeValidator.cpp SurfaceTypeValidator.h - EnvironmentPanel.cpp - EnvironmentPanel.h - EnvironmentPanel.ui TrackView/AtomOutputFrameCapture.cpp TrackView/AtomOutputFrameCapture.h TrackView/TrackViewDialog.qrc @@ -881,9 +856,6 @@ set(FILES Grid.h LayoutWnd.cpp LayoutWnd.h - ModelViewport.cpp - ModelViewport.h - ModelViewportDC.cpp EditorViewportWidget.cpp EditorViewportWidget.h ViewportManipulatorController.cpp diff --git a/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp b/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp index 5aa5301693..5b76ca8804 100644 --- a/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/ManipScene.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include "../EditorCommon/QViewport.h" diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp index 362452a67e..2d9598ba83 100644 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp @@ -17,7 +17,6 @@ #include #include #include -#include #include #include #include @@ -108,114 +107,6 @@ struct QViewport::SPreviousContext bool isMainViewport; }; -static void DrawGridLine(IRenderAuxGeom& aux, ColorB col, const float alpha, const float alphaFalloff, const float slide, const float halfSlide, [[maybe_unused]] const float maxSlide, const Vec3& stepDir, const Vec3& orthoDir, const SViewportState& state, const SViewportGridSettings& gridSettings) -{ - ColorB colEnd = col; - - float weight = 1.0f - (slide / halfSlide); - if (slide > halfSlide) - { - weight = (slide - halfSlide) / halfSlide; - } - - float orthoWeight = 1.0f; - - if (gridSettings.circular) - { - float invWeight = 1.0f - weight; - orthoWeight = sqrtf((invWeight * 2) - (invWeight * invWeight)); - } - else - { - orthoWeight = 1.0f; - } - - col.a = aznumeric_cast((1.0f - (weight * (1.0f - alphaFalloff))) * alpha); - colEnd.a = aznumeric_cast(alphaFalloff * alpha); - - Vec3 orthoStep = state.gridOrigin.q * (orthoDir * halfSlide * orthoWeight); - - Vec3 point = state.gridOrigin * (-(stepDir * halfSlide) + (stepDir * slide)); - Vec3 points[3] = { - point, - point - orthoStep, - point + orthoStep - }; - - aux.DrawLine(points[0], col, points[1], colEnd); - aux.DrawLine(points[0], col, points[2], colEnd); -} - -static void DrawGridLines(IRenderAuxGeom& aux, const uint count, const uint interStepCount, const Vec3& stepDir, const float stepSize, const Vec3& orthoDir, const float offset, const SViewportState& state, const SViewportGridSettings& gridSettings) -{ - const uint countHalf = count / 2; - Vec3 step = stepDir * stepSize; - Vec3 orthoStep = orthoDir * aznumeric_cast(countHalf); - Vec3 maxStep = step * aznumeric_cast(countHalf);// + stepDir*fabs(offset); - const float maxStepLen = count * stepSize; - const float halfStepLen = countHalf * stepSize; - - float interStepSize = interStepCount > 0 ? (stepSize / interStepCount) : stepSize; - const float alphaMulMain = (float)gridSettings.mainColor.a; - const float alphaMulInter = (float)gridSettings.middleColor.a; - const float alphaFalloff = 1.0f - (gridSettings.alphaFalloff / 100.0f); - - for (int i = 0; i < count + 2; i++) - { - float pointSlide = i * stepSize + offset; - if (pointSlide > 0.0f && pointSlide < maxStepLen) - { - DrawGridLine(aux, gridSettings.mainColor, alphaMulMain, alphaFalloff, pointSlide, halfStepLen, maxStepLen, stepDir, orthoDir, state, gridSettings); - } - - for (int d = 1; d < interStepCount; d++) - { - float interSlide = ((i - 1) * stepSize) + offset + (d * interStepSize); - if (interSlide > 0.0f && interSlide < maxStepLen) - { - DrawGridLine(aux, gridSettings.middleColor, alphaMulInter, alphaFalloff, interSlide, halfStepLen, maxStepLen, stepDir, orthoDir, state, gridSettings); - } - } - } -} - -static void DrawGrid(IRenderAuxGeom& aux, const SViewportState& state, const SViewportGridSettings& gridSettings) -{ - const uint count = gridSettings.count * 2; - const float gridSize = gridSettings.spacing * gridSettings.count * 2.0f; - const float halfGridSize = gridSettings.spacing * gridSettings.count; - - const float stepSize = gridSize / count; - DrawGridLines(aux, count, gridSettings.interCount, Vec3(1.0f, 0.0f, 0.0f), stepSize, Vec3(0.0f, 1.0f, 0.0f), state.gridCellOffset.x, state, gridSettings); - DrawGridLines(aux, count, gridSettings.interCount, Vec3(0.0f, 1.0f, 0.0f), stepSize, Vec3(1.0f, 0.0f, 0.0f), state.gridCellOffset.y, state, gridSettings); -} - -static void DrawOrigin(IRenderAuxGeom& aux, const ColorB& col) -{ - const float scale = 0.3f; - const float lineWidth = 4.0f; - aux.DrawLine(Vec3(-scale, 0, 0), col, Vec3(scale, 0, 0), col, lineWidth); - aux.DrawLine(Vec3(0, -scale, 0), col, Vec3(0, scale, 0), col, lineWidth); - aux.DrawLine(Vec3(0, 0, -scale), col, Vec3(0, 0, scale), col, lineWidth); -} - -static void DrawOrigin(IRenderAuxGeom& aux, const int left, const int top, const float scale, const Matrix34 cameraTM) -{ - Vec3 originPos = Vec3(aznumeric_cast(left), aznumeric_cast(top), 0); - Quat originRot = Quat(0.707107f, 0.707107f, 0, 0) * Quat(cameraTM).GetInverted(); - Vec3 x = originPos + originRot * Vec3(1, 0, 0) * scale; - Vec3 y = originPos + originRot * Vec3(0, 1, 0) * scale; - Vec3 z = originPos + originRot * Vec3(0, 0, 1) * scale; - ColorF xCol(1, 0, 0); - ColorF yCol(0, 1, 0); - ColorF zCol(0, 0, 1); - const float lineWidth = 2.0f; - - aux.DrawLine(originPos, xCol, x, xCol, lineWidth); - aux.DrawLine(originPos, yCol, y, yCol, lineWidth); - aux.DrawLine(originPos, zCol, z, zCol, lineWidth); -} - struct QViewport::SPrivate { CDLight m_VPLight0; @@ -494,49 +385,6 @@ void QViewport::Update() { m_averageFrameTime = 0.01f * m_lastFrameTime + 0.99f * m_averageFrameTime; } - - if (GetIEditor()->GetEnv()->pRenderer == 0 || - GetIEditor()->GetEnv()->p3DEngine == 0) - { - return; - } - - if (!isVisible()) - { - return; - } - - if (!m_renderContextCreated) - { - return; - } - - if (m_updating) - { - return; - } - - AutoBool updating(&m_updating); - - if (m_resizeWindowEvent) - { - HWND windowHandle = reinterpret_cast(QWidget::winId()); - AzFramework::WindowNotificationBus::Event(windowHandle, &AzFramework::WindowNotificationBus::Handler::OnWindowResized, m_width, m_height); - m_resizeWindowEvent = false; - } - - if (hasFocus()) - { - ProcessMouse(); - ProcessKeys(); - } - - if ((m_width <= 0) || (m_height <= 0)) - { - return; - } - - RenderInternal(); } void QViewport::CaptureMouse() @@ -860,210 +708,16 @@ void QViewport::PreRender() m_state->lastCameraParentFrame = m_state->cameraParentFrame; m_state->lastCameraTarget = currentTM; - m_camera->SetFrustum(m_width, m_height, fov, m_settings->camera.nearClip, GetIEditor()->GetEnv()->p3DEngine->GetMaxViewDistance()); + m_camera->SetFrustum(m_width, m_height, fov, m_settings->camera.nearClip); m_camera->SetMatrix(Matrix34(m_state->cameraParentFrame * currentTM)); } void QViewport::Render() { - IRenderAuxGeom* aux = GetIEditor()->GetEnv()->pRenderer->GetIRenderAuxGeom(); - SAuxGeomRenderFlags oldFlags = aux->GetRenderFlags(); - - if (m_settings->grid.showGrid) - { - aux->SetRenderFlags(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeNone | e_DepthWriteOff | e_DepthTestOn); - DrawGrid(*aux, *m_state, m_settings->grid); - } - - if (m_settings->grid.origin) - { - aux->SetRenderFlags(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeNone | e_DepthWriteOff | e_DepthTestOn); - DrawOrigin(*aux, m_settings->grid.originColor); - } - - if (m_settings->camera.showViewportOrientation) - { - aux->SetRenderFlags(e_Mode3D | e_AlphaBlended | e_FillModeSolid | e_CullModeNone | e_DepthWriteOn | e_DepthTestOn); - TransformationMatrices backupSceneMatrices; - GetIEditor()->GetEnv()->pRenderer->Set2DMode(m_width, m_height, backupSceneMatrices); - DrawOrigin(*aux, 50, m_height - 50, 20.0f, m_camera->GetMatrix()); - GetIEditor()->GetEnv()->pRenderer->Unset2DMode(backupSceneMatrices); - } - - // Force grid, origin and viewport orientation to render by calling Flush(). This ensures that they are always drawn behind other geometry - aux->Flush(); - aux->SetRenderFlags(oldFlags); - - // wireframe mode - CScopedWireFrameMode scopedWireFrame(GetIEditor()->GetEnv()->pRenderer, m_settings->rendering.wireframe ? R_WIREFRAME_MODE : R_SOLID_MODE); - - SRenderingPassInfo passInfo = SRenderingPassInfo::CreateGeneralPassRenderingInfo(*m_camera, SRenderingPassInfo::DEFAULT_FLAGS, true); - GetIEditor()->GetEnv()->pRenderer->BeginSpawningGeneratingRendItemJobs(passInfo.ThreadID()); - GetIEditor()->GetEnv()->pRenderer->BeginSpawningShadowGeneratingRendItemJobs(passInfo.ThreadID()); - GetIEditor()->GetEnv()->pRenderer->EF_ClearSkinningDataPool(); - GetIEditor()->GetEnv()->pRenderer->EF_StartEf(passInfo); - - SRendParams rp; - - - //--------------------------------------------------------------------------------------- - //---- add light ------------------------------------------------------------- - //--------------------------------------------------------------------------------------- - ///////////////////////////////////////////////////////////////////////////////////// - // Confetti Start - ///////////////////////////////////////////////////////////////////////////////////// - // If time of day enabled, add sun light to preview - Confetti Vera. - if (m_settings->rendering.sunlight) - { - rp.AmbientColor.r = GetIEditor()->Get3DEngine()->GetSunColor().x / 255.0f * m_settings->lighting.m_brightness; - rp.AmbientColor.g = GetIEditor()->Get3DEngine()->GetSunColor().y / 255.0f * m_settings->lighting.m_brightness; - rp.AmbientColor.b = GetIEditor()->Get3DEngine()->GetSunColor().z / 255.0f * m_settings->lighting.m_brightness; - - m_private->m_sun.SetPosition(passInfo.GetCamera().GetPosition() + GetIEditor()->Get3DEngine()->GetSunDir()); - // The radius value respect the sun radius settings in Engine. - // Please refer to the function C3DEngine::UpdateSun(const SRenderingPassInfo &passInfo). -- Vera, Confetti - m_private->m_sun.m_fRadius = 100000000; //Radius of the sun from Engine. - m_private->m_sun.SetLightColor(GetIEditor()->Get3DEngine()->GetSunColor()); - m_private->m_sun.SetSpecularMult(GetIEditor()->Get3DEngine()->GetGlobalParameter(E3DPARAM_SUN_SPECULAR_MULTIPLIER)); - m_private->m_sun.m_Flags |= DLF_DIRECTIONAL | DLF_SUN | DLF_THIS_AREA_ONLY | DLF_LM | DLF_SPECULAROCCLUSION | - ((GetIEditor()->Get3DEngine()->IsSunShadows() && passInfo.RenderShadows()) ? DLF_CASTSHADOW_MAPS : 0); - m_private->m_sun.m_sName = "Sun"; - - GetIEditor()->GetEnv()->pRenderer->EF_ADDDlight(&m_private->m_sun, passInfo); - } - ///////////////////////////////////////////////////////////////////////////////////// - // Confetti End - ///////////////////////////////////////////////////////////////////////////////////// - else // Add directional light - { - rp.AmbientColor.r = m_settings->lighting.m_ambientColor.r / 255.0f * m_settings->lighting.m_brightness; - rp.AmbientColor.g = m_settings->lighting.m_ambientColor.g / 255.0f * m_settings->lighting.m_brightness; - rp.AmbientColor.b = m_settings->lighting.m_ambientColor.b / 255.0f * m_settings->lighting.m_brightness; - - // Directional light - if (m_settings->lighting.m_useLightRotation) - { - m_LightRotationRadian += m_averageFrameTime; - } - if (m_LightRotationRadian > gf_PI) - { - m_LightRotationRadian = -gf_PI; - } - - Matrix33 LightRot33 = Matrix33::CreateRotationZ(m_LightRotationRadian); - - f32 lightMultiplier = m_settings->lighting.m_lightMultiplier; - f32 lightSpecMultiplier = m_settings->lighting.m_lightSpecMultiplier; - - f32 lightOrbit = 15.0f; - Vec3 LPos0 = Vec3(-lightOrbit, lightOrbit, lightOrbit / 2); - m_private->m_VPLight0.SetPosition(LightRot33 * LPos0); - - Vec3 d0; - d0.x = f32(m_settings->lighting.m_directionalLightColor.r) / 255.0f; - d0.y = f32(m_settings->lighting.m_directionalLightColor.g) / 255.0f; - d0.z = f32(m_settings->lighting.m_directionalLightColor.b) / 255.0f; - m_private->m_VPLight0.SetLightColor(ColorF(d0.x * lightMultiplier, d0.y * lightMultiplier, d0.z * lightMultiplier, 0)); - m_private->m_VPLight0.SetSpecularMult(lightSpecMultiplier); - - m_private->m_VPLight0.m_Flags = DLF_SUN | DLF_DIRECTIONAL; - GetIEditor()->GetEnv()->pRenderer->EF_ADDDlight(&m_private->m_VPLight0, passInfo); - } - - //--------------------------------------------------------------------------------------- - - Matrix34 tm(IDENTITY); - rp.pMatrix = &tm; - rp.pPrevMatrix = &tm; - - rp.dwFObjFlags = 0; - - SRenderContext rc; - rc.camera = m_camera.get(); - rc.viewport = this; - rc.passInfo = &passInfo; - rc.renderParams = &rp; - - - for (size_t i = 0; i < m_consumers.size(); ++i) - { - m_consumers[i]->OnViewportRender(rc); - } - SignalRender(rc); - - if ((m_settings->rendering.fps == true) && (m_averageFrameTime != 0.0f)) - { - GetIEditor()->GetEnv()->pRenderer->Draw2dLabel(12.0f, 12.0f, 1.25f, ColorF(1, 1, 1, 1), false, "FPS: %.2f", 1.0f / m_averageFrameTime); - } - - GetIEditor()->GetEnv()->pRenderer->EF_EndEf3D(SHDF_STREAM_SYNC, -1, -1, passInfo); - - if (m_mouseMovementsSinceLastFrame > 0) - { - m_mouseMovementsSinceLastFrame = 0; - - // Make sure we deliver at least last mouse movement event - OnMouseEvent(m_pendingMouseMoveEvent); - } } void QViewport::RenderInternal() { - { - threadID mainThread = 0; - threadID renderThread = 0; - GetIEditor()->GetEnv()->pRenderer->GetThreadIDs(mainThread, renderThread); - const threadID currentThreadId = CryGetCurrentThreadId(); - - // I'm not sure if this criteria is right. It might not be restrictive enough, but it's at least strict enough to prevent - // the crash we encountered. - const uint32 workerThreadId = AZ::JobContext::GetGlobalContext()->GetJobManager().GetWorkerThreadId(); - const bool isValidThread = (workerThreadId != AZ::JobManager::InvalidWorkerThreadId) || mainThread == currentThreadId || renderThread == currentThreadId; - - if (!isValidThread) - { - AZ_Assert(false, "Attempting to render QViewport on unsupported thread %" PRI_THREADID, currentThreadId); - return; - } - } - - - SetCurrentContext(); - GetIEditor()->GetEnv()->pSystem->RenderBegin(); - - ColorF viewportBackgroundColor(m_settings->background.topColor.r / 255.0f, m_settings->background.topColor.g / 255.0f, m_settings->background.topColor.b / 255.0f); - GetIEditor()->GetEnv()->pRenderer->ClearTargetsImmediately(FRT_CLEAR, viewportBackgroundColor); - GetIEditor()->GetEnv()->pRenderer->ResetToDefault(); - - // Call PreRender to interpolate the new camera position - PreRender(); - GetIEditor()->GetEnv()->pRenderer->SetCamera(*m_camera); - - IRenderAuxGeom* aux = GetIEditor()->GetEnv()->pRenderer->GetIRenderAuxGeom(); - SAuxGeomRenderFlags oldFlags = aux->GetRenderFlags(); - - if (m_settings->background.useGradient) - { - Vec3 frustumVertices[8]; - m_camera->GetFrustumVertices(frustumVertices); - Vec3 lt = Vec3::CreateLerp(frustumVertices[0], frustumVertices[4], 0.10f); - Vec3 lb = Vec3::CreateLerp(frustumVertices[1], frustumVertices[5], 0.10f); - Vec3 rb = Vec3::CreateLerp(frustumVertices[2], frustumVertices[6], 0.10f); - Vec3 rt = Vec3::CreateLerp(frustumVertices[3], frustumVertices[7], 0.10f); - aux->SetRenderFlags(e_Mode3D | e_AlphaNone | e_FillModeSolid | e_CullModeNone | e_DepthWriteOff | e_DepthTestOn); - ColorB topColor = m_settings->background.topColor; - ColorB bottomColor = m_settings->background.bottomColor; - aux->DrawTriangle(lt, topColor, rt, topColor, rb, bottomColor); - aux->DrawTriangle(lb, bottomColor, rb, bottomColor, lt, topColor); - aux->Flush(); - } - aux->SetRenderFlags(oldFlags); - - Render(); - - bool renderStats = false; - GetIEditor()->GetEnv()->pSystem->RenderEnd(renderStats, false); - RestorePreviousContext(); } void QViewport::GetImageOffscreen(CImageEx& image, const QSize& customSize) diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.h b/Code/Sandbox/Plugins/EditorCommon/QViewport.h index 2b18724d01..72b2024bc4 100644 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.h +++ b/Code/Sandbox/Plugins/EditorCommon/QViewport.h @@ -28,7 +28,6 @@ struct SRenderingPassInfo; struct SRendParams; struct Ray; struct IRenderer; -struct I3DEngine; struct SSystemGlobalEnvironment; namespace Serialization { class IArchive; diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Previewer/ImagePreviewer.ui b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Previewer/ImagePreviewer.ui index bdb94bd489..a276adeb78 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Previewer/ImagePreviewer.ui +++ b/Gems/Atom/Asset/ImageProcessingAtom/Code/Source/Previewer/ImagePreviewer.ui @@ -127,11 +127,6 @@ - - QWidget -
Controls/PreviewModelCtrl.h
- 1 -
AzToolsFramework::AspectRatioAwarePixmapWidget QWidget diff --git a/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp b/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp index 8011a87ed2..7f3735dacf 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/ATLAudioObject.cpp @@ -26,9 +26,9 @@ #include #include -#include #include #include +#include #include diff --git a/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp b/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp index e472ad57db..040d635bbd 100644 --- a/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp +++ b/Gems/AudioSystem/Code/Source/Engine/ATLComponents.cpp @@ -33,8 +33,8 @@ #include #include -#include #include +#include namespace Audio { diff --git a/Gems/CMakeLists.txt b/Gems/CMakeLists.txt index 3b630cfd2f..8a9a140008 100644 --- a/Gems/CMakeLists.txt +++ b/Gems/CMakeLists.txt @@ -9,7 +9,6 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # -add_subdirectory(ImageProcessing) add_subdirectory(TextureAtlas) add_subdirectory(LmbrCentral) add_subdirectory(LyShine) @@ -23,7 +22,6 @@ add_subdirectory(HttpRequestor) add_subdirectory(Gestures) add_subdirectory(FastNoise) add_subdirectory(GradientSignal) -add_subdirectory(GameEffectSystem) add_subdirectory(AudioSystem) add_subdirectory(AudioEngineWwise) add_subdirectory(GraphCanvas) @@ -45,7 +43,6 @@ add_subdirectory(GameState) add_subdirectory(Vegetation) add_subdirectory(GameStateSamples) add_subdirectory(SliceFavorites) -add_subdirectory(SVOGI) add_subdirectory(Metastream) add_subdirectory(ScriptCanvas) add_subdirectory(ScriptedEntityTweener) diff --git a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp index 0759e1bbe9..b9b512da36 100644 --- a/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp +++ b/Gems/EMotionFX/Code/Tests/UI/LODSkinnedMeshTests.cpp @@ -77,7 +77,6 @@ namespace EMotionFX m_app.RegisterComponentDescriptor(AzFramework::TransformComponent::CreateDescriptor()); m_envPrev = gEnv; - m_env.p3DEngine = nullptr; m_env.pRenderer = &m_data.m_renderer; m_env.pSystem = &m_data.m_system; gEnv = &m_env; diff --git a/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp b/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp index 88b0df6e73..c825ab8834 100644 --- a/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp +++ b/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp @@ -115,7 +115,6 @@ struct MockGlobalEnvironment m_stubEnv.pCryPak = &m_stubPak; m_stubEnv.pConsole = &m_stubConsole; m_stubEnv.pSystem = &m_stubSystem; - m_stubEnv.p3DEngine = nullptr; gEnv = &m_stubEnv; } diff --git a/Gems/GameEffectSystem/Assets/GameEffectsSystem_Dependencies.xml b/Gems/GameEffectSystem/Assets/GameEffectsSystem_Dependencies.xml deleted file mode 100644 index 0e958e3c7d..0000000000 --- a/Gems/GameEffectSystem/Assets/GameEffectsSystem_Dependencies.xml +++ /dev/null @@ -1,3 +0,0 @@ - - - diff --git a/Gems/GameEffectSystem/Assets/seedList.seed b/Gems/GameEffectSystem/Assets/seedList.seed deleted file mode 100644 index b011adc47b..0000000000 --- a/Gems/GameEffectSystem/Assets/seedList.seed +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - diff --git a/Gems/GameEffectSystem/CMakeLists.txt b/Gems/GameEffectSystem/CMakeLists.txt deleted file mode 100644 index 20a680bce9..0000000000 --- a/Gems/GameEffectSystem/CMakeLists.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -add_subdirectory(Code) diff --git a/Gems/GameEffectSystem/Code/CMakeLists.txt b/Gems/GameEffectSystem/Code/CMakeLists.txt deleted file mode 100644 index f5735b5107..0000000000 --- a/Gems/GameEffectSystem/Code/CMakeLists.txt +++ /dev/null @@ -1,37 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -ly_add_target( - NAME GameEffectSystem.Static STATIC - NAMESPACE Gem - FILES_CMAKE - gameeffectsystem_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - include - source - BUILD_DEPENDENCIES - PUBLIC - Legacy::CryCommon -) - -ly_add_target( - NAME GameEffectSystem ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} - NAMESPACE Gem - FILES_CMAKE - gameeffectsystem_shared_files.cmake - INCLUDE_DIRECTORIES - PUBLIC - include - BUILD_DEPENDENCIES - PRIVATE - Gem::GameEffectSystem.Static -) diff --git a/Gems/GameEffectSystem/Code/gameeffectsystem_files.cmake b/Gems/GameEffectSystem/Code/gameeffectsystem_files.cmake deleted file mode 100644 index a8f66da7e0..0000000000 --- a/Gems/GameEffectSystem/Code/gameeffectsystem_files.cmake +++ /dev/null @@ -1,27 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - source/GameEffectSystem_precompiled.cpp - source/GameEffectSystem_precompiled.h - include/GameEffectSystem/IGameEffectSystem.h - include/GameEffectSystem/IGameRenderNode.h - include/GameEffectSystem/GameEffectsSystemDefines.h - include/GameEffectSystem/GameEffects/IGameEffect.h - include/GameEffectSystem/GameEffects/GameEffectBase.h - source/GameEffectsSystem.h - source/GameEffectsSystem.cpp - source/GameEffects/GameEffectSoftCodeLibrary.cpp - source/RenderElements/GameRenderElement.h - source/RenderElements/GameRenderElement.cpp - source/RenderElements/GameRenderElementSoftCodeLibrary.cpp - source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp -) diff --git a/Gems/GameEffectSystem/Code/gameeffectsystem_shared_files.cmake b/Gems/GameEffectSystem/Code/gameeffectsystem_shared_files.cmake deleted file mode 100644 index 565deee4c2..0000000000 --- a/Gems/GameEffectSystem/Code/gameeffectsystem_shared_files.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - source/GameEffectSystemGem.h - source/GameEffectSystemGem.cpp -) - diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/GameEffectBase.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/GameEffectBase.h deleted file mode 100644 index 464c0bcdf0..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/GameEffectBase.h +++ /dev/null @@ -1,213 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _GAMEEFFECTBASE_H_ -#define _GAMEEFFECTBASE_H_ - -#include -#include -#include "TypeLibrary.h" - -// Forward declares -struct SGameEffectParams; - -//================================================================================================== -// Name: Flag macros -// Desc: Flag macros to make code more readable -// Author: James Chilvers -//================================================================================================== -#define SET_FLAG(currentFlags, flag, state) ((state) ? (currentFlags |= flag) : (currentFlags &= ~flag)); -#define IS_FLAG_SET(currentFlags, flag) ((currentFlags & flag) ? true : false) -//-------------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: CGameEffect -// Desc: Game effect - Ideal for handling a specific visual game feature -// Author: James Chilvers -//================================================================================================== -class CGameEffect - : public IGameEffect -{ - DECLARE_TYPE(CGameEffect, IGameEffect); // Exposes this type for SoftCoding - -public: - CGameEffect(); - virtual ~CGameEffect(); - - void Initialize(const SGameEffectParams* gameEffectParams = NULL) override; - void Release() override; - void Update(float frameTime) override; - - void SetActive(bool isActive) override; - - void SetFlag(uint32 flag, bool state) override { SET_FLAG(m_flags, flag, state); } - bool IsFlagSet(uint32 flag) const override { return IS_FLAG_SET(m_flags, flag); } - uint32 GetFlags() const override { return m_flags; } - void SetFlags(uint32 flags) override { m_flags = flags; } - - void GetMemoryUsage(ICrySizer* pSizer) const override { pSizer->AddObject(this, sizeof(*this)); } - - void UnloadData() override { } - -protected: - // General data functions - static _smart_ptr LoadMaterial(const char* pMaterialName); - -private: - IGameEffect* Next() const override { return m_next; } - IGameEffect* Prev() const override { return m_prev; } - void SetNext(IGameEffect* newNext) override { m_next = newNext; } - void SetPrev(IGameEffect* newPrev) override { m_prev = newPrev; } - - IGameEffect* m_prev; - IGameEffect* m_next; - uint16 m_flags; - IGameEffectSystem* m_gameEffectSystem = nullptr; - -#if DEBUG_GAME_FX_SYSTEM - CryFixedStringT<32> m_debugName; -#endif -}; //----------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: CGameEffect -// Desc: Constructor -//-------------------------------------------------------------------------------------------------- -inline CGameEffect::CGameEffect() -{ - m_prev = NULL; - m_next = NULL; - m_flags = 0; - EBUS_EVENT_RESULT(m_gameEffectSystem, GameEffectSystemRequestBus, GetIGameEffectSystem); -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: ~CGameEffect -// Desc: Destructor -//-------------------------------------------------------------------------------------------------- -inline CGameEffect::~CGameEffect() -{ -#if DEBUG_GAME_FX_SYSTEM - // Output message if effect hasn't been released before being deleted - const bool bEffectIsReleased = - (m_flags & GAME_EFFECT_RELEASED) || // -> Needs to be released before deleted - !(m_flags & GAME_EFFECT_INITIALISED) || // -> Except when not initialised - (gEnv->IsEditor()); // -> Or the editor (memory safely released by editor) - if (!bEffectIsReleased) - { - string dbgMessage = m_debugName + " being destroyed without being released first"; - FX_ASSERT_MESSAGE(bEffectIsReleased, dbgMessage.c_str()); - } -#endif - - if (m_gameEffectSystem) - { - // -> Effect should have been released and been unregistered, but to avoid - // crashes call unregister here too - m_gameEffectSystem->UnRegisterEffect(this); - } -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: Initialise -// Desc: Initializes game effect -//-------------------------------------------------------------------------------------------------- -inline void CGameEffect::Initialize(const SGameEffectParams* gameEffectParams) -{ -#if DEBUG_GAME_FX_SYSTEM - m_debugName = GetName(); // Store name so it can be accessed in destructor and debugging -#endif - - if (!IsFlagSet(GAME_EFFECT_INITIALISED)) - { - SGameEffectParams params; - if (gameEffectParams) - { - params = *gameEffectParams; - } - - SetFlag(GAME_EFFECT_AUTO_UPDATES_WHEN_ACTIVE, params.autoUpdatesWhenActive); - SetFlag(GAME_EFFECT_AUTO_UPDATES_WHEN_NOT_ACTIVE, params.autoUpdatesWhenNotActive); - SetFlag(GAME_EFFECT_AUTO_RELEASE, params.autoRelease); - SetFlag(GAME_EFFECT_AUTO_DELETE, params.autoDelete); - - m_gameEffectSystem->RegisterEffect(this); - - SetFlag(GAME_EFFECT_INITIALISED, true); - SetFlag(GAME_EFFECT_RELEASED, false); - } -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: Release -// Desc: Releases game effect -//-------------------------------------------------------------------------------------------------- -inline void CGameEffect::Release() -{ - SetFlag(GAME_EFFECT_RELEASING, true); - if (IsFlagSet(GAME_EFFECT_ACTIVE)) - { - SetActive(false); - } - m_gameEffectSystem->UnRegisterEffect(this); - SetFlag(GAME_EFFECT_INITIALISED, false); - SetFlag(GAME_EFFECT_RELEASING, false); - SetFlag(GAME_EFFECT_RELEASED, true); -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: Update -// Desc: Updates game effect -//-------------------------------------------------------------------------------------------------- -inline void CGameEffect::Update(float frameTime) -{ - FX_ASSERT_MESSAGE(IsFlagSet(GAME_EFFECT_INITIALISED), - "Effect being updated without being initialised first"); - FX_ASSERT_MESSAGE((IsFlagSet(GAME_EFFECT_RELEASED) == false), - "Effect being updated after being released"); -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: SetActive -// Desc: Sets active status -//-------------------------------------------------------------------------------------------------- -inline void CGameEffect::SetActive(bool isActive) -{ - FX_ASSERT_MESSAGE(IsFlagSet(GAME_EFFECT_INITIALISED), - "Effect changing active status without being initialised first"); - FX_ASSERT_MESSAGE((IsFlagSet(GAME_EFFECT_RELEASED) == false), - "Effect changing active status after being released"); - - SetFlag(GAME_EFFECT_ACTIVE, isActive); - m_gameEffectSystem->RegisterEffect(this); // Re-register effect with game effects system -} //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: LoadMaterial -// Desc: Loads and calls AddRef on material -//-------------------------------------------------------------------------------------------------- -inline _smart_ptr CGameEffect::LoadMaterial(const char* pMaterialName) -{ - _smart_ptr pMaterial = NULL; - I3DEngine* p3DEngine = gEnv->p3DEngine; - if (pMaterialName && p3DEngine) - { - IMaterialManager* pMaterialManager = p3DEngine->GetMaterialManager(); - if (pMaterialManager) - { - pMaterial = pMaterialManager->LoadMaterial(pMaterialName); - } - } - return pMaterial; -} //------------------------------------------------------------------------------------------------ - - -#endif//_GAMEEFFECTBASE_H_ diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/IGameEffect.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/IGameEffect.h deleted file mode 100644 index b2f9aed17f..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffects/IGameEffect.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _GAMEEFFECT_INTERFACE_H_ -#define _GAMEEFFECT_INTERFACE_H_ - -#include - -//================================================================================================== -// Name: EGameEffectFlags -// Desc: Game effect flags -// Author: James Chilvers -//================================================================================================== -enum EGameEffectFlags -{ - GAME_EFFECT_INITIALISED = (1 << 0), - GAME_EFFECT_RELEASED = (1 << 1), - GAME_EFFECT_AUTO_RELEASE = (1 << 2), // Release called when Game Effect System is destroyed - GAME_EFFECT_AUTO_DELETE = (1 << 3), // Delete is called when Game Effect System is destroyed - GAME_EFFECT_AUTO_UPDATES_WHEN_ACTIVE = (1 << 4), - GAME_EFFECT_AUTO_UPDATES_WHEN_NOT_ACTIVE = (1 << 5), - GAME_EFFECT_REGISTERED = (1 << 6), - GAME_EFFECT_ACTIVE = (1 << 7), - GAME_EFFECT_DEBUG_EFFECT = (1 << 8), // Set true for any debug effects to avoid confusion - GAME_EFFECT_UPDATE_WHEN_PAUSED = (1 << 9), - GAME_EFFECT_RELEASING = (1 << 10) -}; //----------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: SGameEffectParams -// Desc: Game effect parameters -// Author: James Chilvers -//================================================================================================== -struct SGameEffectParams -{ - friend class CGameEffect; - - // Make constructor private to stop SGameEffectParams ever being created, should always inherit - // this - // for each effect to avoid casting problems -protected: - SGameEffectParams() - { - autoUpdatesWhenActive = true; - autoUpdatesWhenNotActive = false; - autoRelease = false; - autoDelete = false; - } - -public: - bool autoUpdatesWhenActive; - bool autoUpdatesWhenNotActive; - bool autoRelease; // Release called when Game Effect System is destroyed - bool autoDelete; // Delete is called when Game Effect System is destroyed -}; //----------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: IGameEffect -// Desc: Interface for all game effects -// Author: James Chilvers -//================================================================================================== -struct IGameEffect -{ - DECLARE_TYPELIB(IGameEffect); // Allow soft coding on this interface - - friend class CGameEffectsSystem; - -public: - virtual ~IGameEffect() {} - - virtual void Initialize(const SGameEffectParams* gameEffectParams = NULL) = 0; - virtual void Release() = 0; - virtual void Update(float frameTime) = 0; - - virtual void SetActive(bool isActive) = 0; - - virtual void SetFlag(uint32 flag, bool state) = 0; - virtual bool IsFlagSet(uint32 flag) const = 0; - virtual uint32 GetFlags() const = 0; - virtual void SetFlags(uint32 flags) = 0; - - virtual void GetMemoryUsage(ICrySizer* pSizer) const = 0; - - virtual const char* GetName() const = 0; - - virtual void UnloadData() = 0; - -private: - virtual IGameEffect* Next() const = 0; - virtual IGameEffect* Prev() const = 0; - virtual void SetNext(IGameEffect* newNext) = 0; - virtual void SetPrev(IGameEffect* newPrev) = 0; -}; //----------------------------------------------------------------------------------------------- - -#endif//_GAMEEFFECT_INTERFACE_H_ diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffectsSystemDefines.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffectsSystemDefines.h deleted file mode 100644 index 296a9975e2..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/GameEffectsSystemDefines.h +++ /dev/null @@ -1,179 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _EFFECTS_GAMEEFFECTSSYSTEMDEFINES_H_ -#define _EFFECTS_GAMEEFFECTSSYSTEMDEFINES_H_ -#pragma once - -// Includes -#include "TypeLibrary.h" - -#include - -// Defines -#define GAME_FX_SYSTEM GetIGameEffectSystem() - -#ifndef _RELEASE -#define DEBUG_GAME_FX_SYSTEM 1 -#else -#define DEBUG_GAME_FX_SYSTEM 0 -#endif - -#if DEBUG_GAME_FX_SYSTEM -// Register effect's DebugOnInput and DebugDisplay callback functions -#define REGISTER_EFFECT_DEBUG_DATA(inputEventCallback, debugDisplayCallback, effectName) \ - static CGameEffectsSystem::SRegisterEffectDebugData effectName(inputEventCallback, \ - debugDisplayCallback, \ - #effectName) - -// Debug views -enum EGameEffectsSystemDebugView -{ - eGAME_FX_DEBUG_VIEW_None = 0, - eGAME_FX_DEBUG_VIEW_Profiling, - eGAME_FX_DEBUG_VIEW_EffectList, - eGAME_FX_DEBUG_VIEW_BoundingBox, - eGAME_FX_DEBUG_VIEW_BoundingSphere, - eGAME_FX_DEBUG_VIEW_Particles, - eMAX_GAME_FX_DEBUG_VIEWS - // ** If you add/remove a view then remember to update GAME_FX_DEBUG_VIEW_NAMES ** -}; - -#else -#define REGISTER_EFFECT_DEBUG_DATA(inputEventCallback, debugDisplayCallback, effectName) -#endif - -// FX Asserts -#if DEBUG_GAME_FX_SYSTEM -#define FX_ASSERT_MESSAGE(condition, message) \ - CRY_ASSERT_MESSAGE(condition, message); \ - if (!(condition)) \ - { \ - CryLogAlways("\n*************************************************************************" \ - "************"); \ - CryLogAlways("FX ASSERT"); \ - CryLogAlways("Condition: %s", #condition); \ - CryLogAlways("Message: %s", message); \ - CryLogAlways("File: %s", __FILE__); \ - CryLogAlways("Line: %d", __LINE__); \ - CryLogAlways("***************************************************************************" \ - "**********\n"); \ - } -#else -#define FX_ASSERT_MESSAGE(condition, message) -#endif - -// Profile tags -#define ENABLE_GAME_FX_PROFILE_TAGS 0 - -#if ENABLE_GAME_FX_PROFILE_TAGS -#define GAME_FX_PROFILE_BEGIN(_TAG_NAME_) \ - { \ - CryProfile::PushProfilingMarker(#_TAG_NAME_); \ - gEnv->pRenderer->PushProfileMarker(#_TAG_NAME_); \ - } -#define GAME_FX_PROFILE_END(_TAG_NAME_) \ - { \ - CryProfile::PopProfilingMarker(); \ - gEnv->pRenderer->PopProfileMarker(#_TAG_NAME_); \ - } -#define GAME_FX_PROFILE_MARKER(...) \ - { \ - PIXSetMarker(0, __VA_ARGS__); \ - } -#else -#define GAME_FX_PROFILE_BEGIN(_TAG_NAME_) \ - { \ - } -#define GAME_FX_PROFILE_END(_TAG_NAME_) \ - { \ - } -#define GAME_FX_PROFILE_MARKER(...) \ - { \ - } -#endif // ENABLE_GAME_FX_PROFILE_TAGS - -#define GAME_FX_LISTENER_NAME "GameEffectsSystem" -#define GAME_FX_LIBRARY_NAME "GameEffectsLibrary" -#define GAME_RENDER_NODE_LISTENER_NAME "GameRenderNodeListener" -#define GAME_RENDER_NODE_LIBRARY_NAME "GameRenderNodeLibrary" -#define GAME_RENDER_ELEMENT_LISTENER_NAME "GameRenderElementListener" -#define GAME_RENDER_ELEMENT_LIBRARY_NAME "GameRenderElementLibrary" - -// Macro to remove specific code when soft code is enabled -#ifdef SOFTCODE_ENABLED -#define REMOVE_IN_SOFT_CODE(_softCodeOnlyCode_) -#else -#define REMOVE_IN_SOFT_CODE(_softCodeOnlyCode_) _softCodeOnlyCode_ -#endif - -// Register effect's Game callbacks -#define REGISTER_GAME_CALLBACKS(enteredGameCallback, effectName) \ - static SRegisterGameCallbacks effectName(enteredGameCallback) - -// Create Game FX Soft Code instance -#ifdef SOFTCODE_ENABLED -#define CREATE_GAME_FX_SOFT_CODE_INSTANCE(T) \ - (static_cast(GAME_FX_SYSTEM.CreateSoftCodeInstance(#T))) -#else -#define CREATE_GAME_FX_SOFT_CODE_INSTANCE(T) (new T) -#endif - -// Safely release and delete effect through macro -#define SAFE_DELETE_GAME_EFFECT(pGameEffect) \ - if (pGameEffect) \ - { \ - pGameEffect->Release(); \ - SAFE_DELETE(pGameEffect); \ - } - -// Safely delete game render nodes -#define SAFE_DELETE_GAME_RENDER_NODE(pGameRenderNode) \ - if (pGameRenderNode) \ - { \ - pGameRenderNode->ReleaseGameRenderNode(); \ - gEnv->p3DEngine->FreeRenderNodeState(pGameRenderNode); \ - pGameRenderNode = NULL; \ - } - -// Safely delete game render elements -#define SAFE_DELETE_GAME_RENDER_ELEMENT(pGameRenderElement) \ - if (pGameRenderElement) \ - { \ - pGameRenderElement->ReleaseGameRenderElement(); \ - pGameRenderElement = NULL; \ - } - -// FX input -#define GAME_FX_INPUT_ReleaseDebugEffect AzFramework::InputDeviceKeyboard::Key::NavigationEnd.GetNameCrc32() -#define GAME_FX_INPUT_ResetParticleManager AzFramework::InputDeviceKeyboard::Key::NavigationDelete.GetNameCrc32() -#define GAME_FX_INPUT_PauseParticleManager AzFramework::InputDeviceKeyboard::Key::NavigationEnd.GetNameCrc32() -#define GAME_FX_INPUT_ReloadEffectData AzFramework::InputDeviceKeyboard::Key::NumPadDecimal.GetNameCrc32() -#define GAME_FX_INPUT_IncrementDebugEffectId AzFramework::InputDeviceKeyboard::Key::NumPadAdd.GetNameCrc32() -#define GAME_FX_INPUT_DecrementDebugEffectId AzFramework::InputDeviceKeyboard::Key::NumPadSubtract.GetNameCrc32() -#define GAME_FX_INPUT_IncrementDebugView AzFramework::InputDeviceKeyboard::Key::NavigationArrowRight.GetNameCrc32() -#define GAME_FX_INPUT_DecrementDebugView AzFramework::InputDeviceKeyboard::Key::NavigationArrowLeft.GetNameCrc32() - -// Forward declares -struct IGameEffect; -struct IGameRenderNode; -struct IGameRenderElement; -class CGameRenderNodeSoftCodeListener; -class CGameRenderElementSoftCodeListener; - -// Typedefs -typedef void (* EnteredGameCallback)(); -typedef void (* DebugOnInputEventCallback)(int); -typedef void (* DebugDisplayCallback)(const Vec2& textStartPos, float textSize, float textYStep); -typedef _smart_ptr IGameRenderNodePtr; -typedef _smart_ptr IGameRenderElementPtr; - -#endif//_EFFECTS_GAMEEFFECTSSYSTEMDEFINES_H_ diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameEffectSystem.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameEffectSystem.h deleted file mode 100644 index 22ca06b781..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameEffectSystem.h +++ /dev/null @@ -1,163 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _GAMEEFFECTSYSTEM_INTERFACE_H_ -#define _GAMEEFFECTSYSTEM_INTERFACE_H_ - -#include -#include -#include -#include - -class IGameEffectSystem; -struct ITypeLibrary; - -/** - * For requesting the GameEffectSystem. - */ -class GameEffectSystemRequests - : public AZ::EBusTraits -{ -public: - ////////////////////////////////////////////////////////////////////////// - // EBusTraits overrides - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - ////////////////////////////////////////////////////////////////////////// - - virtual IGameEffectSystem* GetIGameEffectSystem() = 0; -}; -using GameEffectSystemRequestBus = AZ::EBus; - -/** - * Dispatches notifications from the GameEffectSystem. - */ -class GameEffectSystemNotifications - : public AZ::EBusTraits -{ -public: - /// Called when it's appropriate to release all registered GameEffects - virtual void OnReleaseGameEffects() { } -}; -using GameEffectSystemNotificationBus = AZ::EBus; - -/// Returns global instance of IGameEffectSystem. -/// This function exists to support the legacy GAME_FX_SYSYTEM macro, -/// this is not the suggested way to fetch a singleton. -inline IGameEffectSystem& GetIGameEffectSystem() -{ - IGameEffectSystem* instance = nullptr; - EBUS_EVENT_RESULT(instance, GameEffectSystemRequestBus, GetIGameEffectSystem); - return *instance; -} - -class IGameEffectSystem -{ -public: - virtual SC_API void RegisterEffect(IGameEffect* effect) = 0; - virtual SC_API void UnRegisterEffect(IGameEffect* effect) = 0; - - virtual SC_API void GameRenderNodeInstanceReplaced(void* pOldInstance, void* pNewInstance) = 0; - virtual SC_API void GameRenderElementInstanceReplaced(void* pOldInstance, void* pNewInstance) = 0; - -#ifdef SOFTCODE_ENABLED - // Create soft code instance using libs - virtual SC_API void* CreateSoftCodeInstance(const char* pTypeName); - // Register soft code lib for creation of instances - virtual SC_API void RegisterSoftCodeLib(ITypeLibrary* pLib); -#endif - - SC_API static void RegisterEnteredGameCallback(EnteredGameCallback enteredGameCallback); - -#ifdef DEBUG_GAME_FX_SYSTEM - SC_API static void RegisterEffectDebugData(DebugOnInputEventCallback inputEventCallback, - DebugDisplayCallback displayCallback, - const char* effectName); -#endif//DEBUG_GAME_FX_SYSTEM -}; - -#if DEBUG_GAME_FX_SYSTEM -// Creating a static version of SRegisterEffectDebugData inside an effect cpp registers the -// effect's debug data with the game effects system -struct SRegisterEffectDebugData -{ - SRegisterEffectDebugData(DebugOnInputEventCallback inputEventCallback, - DebugDisplayCallback debugDisplayCallback, const char* effectName) - { - IGameEffectSystem::RegisterEffectDebugData(inputEventCallback, debugDisplayCallback, - effectName); - } -}; - -struct SEffectDebugData -{ - SEffectDebugData(DebugOnInputEventCallback paramInputCallback, - DebugDisplayCallback paramDisplayCallback, const char* paramEffectName) - { - inputCallback = paramInputCallback; - displayCallback = paramDisplayCallback; - effectName = paramEffectName; - } - DebugOnInputEventCallback inputCallback; - DebugDisplayCallback displayCallback; - const char* effectName; -}; -#endif//DEBUG_GAME_FX_SYSTEM - -// Creating a static version of SRegisterGameCallbacks inside an effect cpp registers the -// effect's game callback functions with the game effects system -struct SRegisterGameCallbacks -{ - SRegisterGameCallbacks(EnteredGameCallback enteredGameCallback) - { - IGameEffectSystem::RegisterEnteredGameCallback(enteredGameCallback); - } -}; - -//-------------------------------------------------------------------------------------------------- -// Desc: Game Effect System Static data - contains access to any data where static initialisation -// order is critical, this will enforce initialisation on first use -//-------------------------------------------------------------------------------------------------- -struct SGameEffectSystemStaticData -{ - static PodArray& GetEnteredGameCallbackList() - { - static PodArray enteredGameCallbackList; - return enteredGameCallbackList; - } - -#if DEBUG_GAME_FX_SYSTEM - static PodArray& GetEffectDebugList() - { - static PodArray effectDebugList; - return effectDebugList; - } -#endif//DEBUG_GAME_FX_SYSTEM -}; -// Easy access macros -#define s_enteredGameCallbackList SGameEffectSystemStaticData::GetEnteredGameCallbackList() -#if DEBUG_GAME_FX_SYSTEM -#define s_effectDebugList SGameEffectSystemStaticData::GetEffectDebugList() -#endif//DEBUG_GAME_FX_SYSTEM - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterEnteredGameCallback -// Desc: Registers entered game callback -//-------------------------------------------------------------------------------------------------- -inline void IGameEffectSystem::RegisterEnteredGameCallback(EnteredGameCallback enteredGameCallback) -{ - if (enteredGameCallback) - { - s_enteredGameCallbackList.push_back(enteredGameCallback); - } -} //------------------------------------------------------------------------------------------------- - -#endif//_GAMEEFFECTSYSTEM_INTERFACE_H_ diff --git a/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameRenderNode.h b/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameRenderNode.h deleted file mode 100644 index e236dbc8a6..0000000000 --- a/Gems/GameEffectSystem/Code/include/GameEffectSystem/IGameRenderNode.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _EFFECTS_RENDERNODES_IGAMERENDERNODE_H_ -#define _EFFECTS_RENDERNODES_IGAMERENDERNODE_H_ -#pragma once - -#include -#include - -// Forward declares -struct IGameRenderNodeParams; - -//================================================================================================== -// Name: IGameRenderNode -// Desc: Base interface for all game render nodes -// Author: James Chilvers -//================================================================================================== -struct IGameRenderNode - : public IRenderNode - , public _i_reference_target_t -{ - DECLARE_TYPELIB(IGameRenderNode); // Allow soft coding on this interface - - virtual ~IGameRenderNode() {} - - virtual bool InitialiseGameRenderNode() = 0; - virtual void ReleaseGameRenderNode() = 0; - - virtual void SetParams(const IGameRenderNodeParams* pParams = NULL) = 0; -}; //----------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: IGameRenderNodeParams -// Desc: Game render node params -// Author: James Chilvers -//================================================================================================== -struct IGameRenderNodeParams -{ - virtual ~IGameRenderNodeParams() {} -}; //------------------------------------------------------------------------------------------------ - -#endif//_EFFECTS_RENDERNODES_IGAMERENDERNODE_H_ diff --git a/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.cpp b/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.cpp deleted file mode 100644 index 589364a33a..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "GameEffectSystem_precompiled.h" -#include "GameEffectSystemGem.h" - -namespace -{ - /** - * Console command function for reloading the game effect system's data. - */ - void CmdReloadGameFx([[maybe_unused]] IConsoleCmdArgs* pArgs) - { - IGameEffectSystem* iGameEffectSystem = nullptr; - GameEffectSystemRequestBus::BroadcastResult(iGameEffectSystem, &GameEffectSystemRequestBus::Events::GetIGameEffectSystem); - if (iGameEffectSystem) - { - CGameEffectsSystem* cGameEffectsSystem = reinterpret_cast(iGameEffectSystem); - cGameEffectsSystem->ReloadData(); - } - } -} - -GameEffectSystemGem::GameEffectSystemGem() - : CryHooksModule() - , m_gameEffectSystem(nullptr) - , g_gameFXSystemDebug(0) -{ - GameEffectSystemRequestBus::Handler::BusConnect(); -} - -GameEffectSystemGem::~GameEffectSystemGem() -{ - GameEffectSystemRequestBus::Handler::BusDisconnect(); -} - -void GameEffectSystemGem::OnSystemEvent(ESystemEvent event, [[maybe_unused]] UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) -{ - switch (event) - { - case ESYSTEM_EVENT_GAME_POST_INIT: - // Put your init code here - // All other Gems will exist at this point - REGISTER_CVAR(g_gameFXSystemDebug, 0, 0, "Toggles game effects system debug state"); - REGISTER_COMMAND("g_reloadGameFx", &CmdReloadGameFx, 0, "Reload all game fx"); - - m_gameEffectSystem = new CGameEffectsSystem(); - m_gameEffectSystem->Initialize(); - m_gameEffectSystem->LoadData(); - break; - - case ESYSTEM_EVENT_FULL_SHUTDOWN: - case ESYSTEM_EVENT_FAST_SHUTDOWN: - if (m_gameEffectSystem) - { - m_gameEffectSystem->ReleaseData(); - m_gameEffectSystem->Destroy(); - - delete m_gameEffectSystem; - m_gameEffectSystem = nullptr; - } - break; - } -} - -IGameEffectSystem* GameEffectSystemGem::GetIGameEffectSystem() -{ - return m_gameEffectSystem; -} - -AZ_DECLARE_MODULE_CLASS(Gem_GameEffectSystem, GameEffectSystemGem) diff --git a/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.h b/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.h deleted file mode 100644 index 930bbca726..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectSystemGem.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _GEM_GAMEEFFECTSYSTEM_H_ -#define _GEM_GAMEEFFECTSYSTEM_H_ - -#include "GameEffectsSystem.h" - -class GameEffectSystemGem - : public CryHooksModule - , public GameEffectSystemRequestBus::Handler -{ -public: - AZ_RTTI(GameEffectSystemGem, "{44350C39-A90B-46EB-AC1C-DB505113F4A6}", CryHooksModule); - -public: - GameEffectSystemGem(); - ~GameEffectSystemGem() override; - - void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) override; - IGameEffectSystem* GetIGameEffectSystem() override; - -private: - CGameEffectsSystem* m_gameEffectSystem; - int g_gameFXSystemDebug; -}; - -#endif//_GEM_GAMEEFFECTSYSTEM_H_ diff --git a/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.cpp b/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.cpp deleted file mode 100644 index 9a1af37a08..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.cpp +++ /dev/null @@ -1,12 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "GameEffectSystem_precompiled.h" diff --git a/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.h b/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.h deleted file mode 100644 index a551219e7c..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectSystem_precompiled.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef AFX_GAMEEFFECTSYSTEM_PRECOMPILED_H__140A8406_81F3_42C3_B6BB_0B14734012DE__INCLUDED_ -#define AFX_GAMEEFFECTSYSTEM_PRECOMPILED_H__140A8406_81F3_42C3_B6BB_0B14734012DE__INCLUDED_ - -#include -#include -#include -#include -#include - -#endif//AFX_GAMEEFFECTSYSTEM_PRECOMPILED_H__140A8406_81F3_42C3_B6BB_0B14734012DE__INCLUDED_ diff --git a/Gems/GameEffectSystem/Code/source/GameEffects/GameEffectSoftCodeLibrary.cpp b/Gems/GameEffectSystem/Code/source/GameEffects/GameEffectSoftCodeLibrary.cpp deleted file mode 100644 index 14f55b2af6..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffects/GameEffectSoftCodeLibrary.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: GameEffectSoftCodeLibrary -// Desc: Game Effect Soft Code Library -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include "GameEffectSystem/GameEffectsSystemDefines.h" -#include "GameEffectSystem/GameEffects/IGameEffect.h" - -IMPLEMENT_TYPELIB(IGameEffect, GAME_FX_LIBRARY_NAME); // Implementation of Soft Coding library diff --git a/Gems/GameEffectSystem/Code/source/GameEffectsSystem.cpp b/Gems/GameEffectSystem/Code/source/GameEffectsSystem.cpp deleted file mode 100644 index b9a2d4dfa7..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectsSystem.cpp +++ /dev/null @@ -1,1012 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: CGameEffectsSystem -// Desc: System to handle game effects, render nodes and render elements -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include "GameEffectsSystem.h" -#include "BitFiddling.h" -#include "RenderElements/GameRenderElement.h" -#include -#include - -#include - -//-------------------------------------------------------------------------------------------------- -// Desc: Defines -//-------------------------------------------------------------------------------------------------- -#define GAME_FX_DATA_FILE "scripts/effects/gameeffects.xml" -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Desc: Debug data -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -int CGameEffectsSystem::s_currentDebugEffectId = 0; - -const char* GAME_FX_DEBUG_VIEW_NAMES[eMAX_GAME_FX_DEBUG_VIEWS] = { - "None", "Profiling", - "Effect List", "Bounding Box", - "Bounding Sphere", "Particles" -}; - -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Desc: Static data -//-------------------------------------------------------------------------------------------------- -int CGameEffectsSystem::s_postEffectCVarNameOffset = 0; -//-------------------------------------------------------------------------------------------------- -//-------------------------------------------------------------------------------------------------- - -//================================================================================================== -// Name: CGameRenderNodeSoftCodeListener -// Desc: Game Render Node Soft Code Listener -// Author: James Chilvers -//================================================================================================== -class CGameRenderNodeSoftCodeListener - : public ISoftCodeListener -{ -public: - CGameRenderNodeSoftCodeListener() - { - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->AddListener(GAME_RENDER_NODE_LIBRARY_NAME, this, - GAME_RENDER_NODE_LISTENER_NAME); - } - } - virtual ~CGameRenderNodeSoftCodeListener() - { - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->RemoveListener(GAME_RENDER_NODE_LIBRARY_NAME, this); - } - } - - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) - { - GAME_FX_SYSTEM.GameRenderNodeInstanceReplaced(pOldInstance, pNewInstance); - } -}; //------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: CGameRenderElementSoftCodeListener -// Desc: Game Render Element Soft Code Listener -// Author: James Chilvers -//================================================================================================== -class CGameRenderElementSoftCodeListener - : public ISoftCodeListener -{ -public: - CGameRenderElementSoftCodeListener() - { - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->AddListener(GAME_RENDER_ELEMENT_LIBRARY_NAME, this, - GAME_RENDER_ELEMENT_LISTENER_NAME); - } - } - virtual ~CGameRenderElementSoftCodeListener() - { - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->RemoveListener(GAME_RENDER_ELEMENT_LIBRARY_NAME, this); - } - } - - virtual void InstanceReplaced(void* pOldInstance, void* pNewInstance) - { - GAME_FX_SYSTEM.GameRenderElementInstanceReplaced(pOldInstance, pNewInstance); - } -}; //------------------------------------------------------------------------------------------------ - -//-------------------------------------------------------------------------------------------------- -// Name: CGameEffectsSystem -// Desc: Constructor -//-------------------------------------------------------------------------------------------------- -CGameEffectsSystem::CGameEffectsSystem() - : AzFramework::InputChannelEventListener(AzFramework::InputChannelEventListener::GetPriorityDebug()) -{ -#if DEBUG_GAME_FX_SYSTEM - AzFramework::InputChannelEventListener::Connect(); -#endif - -#ifdef SOFTCODE_ENABLED - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->AddListener(GAME_FX_LIBRARY_NAME, this, GAME_FX_LISTENER_NAME); - } - - m_gameRenderNodes.clear(); - m_gameRenderNodeSoftCodeListener = new CGameRenderNodeSoftCodeListener; - - m_gameRenderElements.clear(); - m_gameRenderElementSoftCodeListener = new CGameRenderElementSoftCodeListener; - - RegisterSoftCodeLib(IGameEffect::TLibrary::Instance()); - RegisterSoftCodeLib(IGameRenderNode::TLibrary::Instance()); - RegisterSoftCodeLib(IGameRenderElement::TLibrary::Instance()); -#endif - - Reset(); -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: ~CGameEffectsSystem -// Desc: Destructor -//-------------------------------------------------------------------------------------------------- -CGameEffectsSystem::~CGameEffectsSystem() -{ -#if DEBUG_GAME_FX_SYSTEM - AzFramework::InputChannelEventListener::Disconnect(); -#endif - -#ifdef SOFTCODE_ENABLED - if (gEnv->pSoftCodeMgr) - { - gEnv->pSoftCodeMgr->RemoveListener(GAME_FX_LIBRARY_NAME, this); - } - - SAFE_DELETE(m_gameRenderNodeSoftCodeListener); - SAFE_DELETE(m_gameRenderElementSoftCodeListener); - m_softCodeTypeLibs.clear(); - m_gameRenderNodes.clear(); - m_gameRenderElements.clear(); -#endif - - AZ::TickBus::Handler::BusDisconnect(); -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: Destroy -// Desc: Destroys effects system -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::Destroy() -{ - EBUS_EVENT(GameEffectSystemNotificationBus, OnReleaseGameEffects); - AutoReleaseAndDeleteFlaggedEffects(m_effectsToUpdate); - AutoReleaseAndDeleteFlaggedEffects(m_effectsNotToUpdate); - FX_ASSERT_MESSAGE(m_effectsToUpdate == nullptr && m_effectsNotToUpdate == nullptr, - "Game Effects System being destroyed even though game effects still exist!"); -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: Reset -// Desc: Resets effects systems data -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::Reset() -{ - m_isInitialised = false; - m_effectsToUpdate = NULL; - m_effectsNotToUpdate = NULL; - m_nextEffectToUpdate = NULL; - s_postEffectCVarNameOffset = 0; - -#if DEBUG_GAME_FX_SYSTEM - m_debugView = eGAME_FX_DEBUG_VIEW_None; -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: Initialize -// Desc: Initializes effects system -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::Initialize() -{ - if (m_isInitialised == false) - { - Reset(); - SetPostEffectCVarCallbacks(); - - AZ::TickBus::Handler::BusConnect(); - - m_isInitialised = true; - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GameRulesInitialise -// Desc: Game Rules initialise -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::GameRulesInitialise() -{ -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: LoadData -// Desc: Loads data for game effects system and effects -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::LoadData() -{ -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: ReleaseData -// Desc: Releases any loaded data for game effects system and any effects with registered callbacks -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::ReleaseData() -{ - if (s_hasLoadedData) - { -#if DEBUG_GAME_FX_SYSTEM - // Unload all debug effects which rely on effect data - for (size_t i = 0; i < s_effectDebugList.Size(); i++) - { - if (s_effectDebugList[i].inputCallback) - { - s_effectDebugList[i].inputCallback(GAME_FX_INPUT_ReleaseDebugEffect); - } - } -#endif - - for (IGameEffect* ge = m_effectsToUpdate; ge; ge = ge->Next()) - { - ge->UnloadData(); - } - for (IGameEffect* ge = m_effectsNotToUpdate; ge; ge = ge->Next()) - { - ge->UnloadData(); - } - s_hasLoadedData = false; - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: ReloadData -// Desc: Reloads any loaded data for game effects registered callbacks -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::ReloadData() -{ -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: EnteredGame -// Desc: Called when entering a game -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::EnteredGame() -{ - const int callbackCount = s_enteredGameCallbackList.size(); - EnteredGameCallback enteredGameCallbackFunc = NULL; - for (int i = 0; i < callbackCount; i++) - { - enteredGameCallbackFunc = s_enteredGameCallbackList[i]; - if (enteredGameCallbackFunc) - { - enteredGameCallbackFunc(); - } - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: AutoReleaseAndDeleteFlaggedEffects -// Desc: Calls release and delete on any effects with the these flags set -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::AutoReleaseAndDeleteFlaggedEffects(IGameEffect* effectList) -{ - if (effectList) - { - IGameEffect* effect = effectList; - while (effect) - { - m_nextEffectToUpdate = effect->Next(); - - bool autoRelease = effect->IsFlagSet(GAME_EFFECT_AUTO_RELEASE); - bool autoDelete = effect->IsFlagSet(GAME_EFFECT_AUTO_DELETE); - - if (autoRelease || autoDelete) - { - SOFTCODE_RETRY(effect, effect->Release()); - if (autoDelete) - { - SAFE_DELETE(effect); - } - } - - effect = m_nextEffectToUpdate; - } - m_nextEffectToUpdate = NULL; - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: InstanceReplaced -// Desc: Replaces instance for soft coding -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::InstanceReplaced([[maybe_unused]] void* pOldInstance, [[maybe_unused]] void* pNewInstance) -{ -#ifdef SOFTCODE_ENABLED - if (pNewInstance && pOldInstance) - { - IGameEffect* pNewGameEffectInstance = static_cast(pNewInstance); - IGameEffect* pOldGameEffectInstance = static_cast(pOldInstance); - - // Copy over flags and remove registered flag so new effect instance can be registered - // We haven't used the SOFT macro on the m_flags member because the oldInstance's flags - // would then be Nulled out, and they are needed for the effect to be deregistered - uint32 oldGameEffectFlags = pOldGameEffectInstance->GetFlags(); - SET_FLAG(oldGameEffectFlags, GAME_EFFECT_REGISTERED, false); - pNewGameEffectInstance->SetFlags(oldGameEffectFlags); - - // Register new effect instance, old instance will get unregistered by destructor - GAME_FX_SYSTEM.RegisterEffect(pNewGameEffectInstance); - - // Reload all data used by effects, then data can be added/removed for soft coding - ReloadData(); - - // Data used by effect will be copied to new effect, so mustn't release it but - // must set flag so destructor doesn't assert - pOldGameEffectInstance->SetFlag(GAME_EFFECT_RELEASED, true); - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GameRenderNodeInstanceReplaced -// Desc: Replaces Game Render Node instance for soft coding -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::GameRenderNodeInstanceReplaced([[maybe_unused]] void* pOldInstance, [[maybe_unused]] void* pNewInstance) -{ -#ifdef SOFTCODE_ENABLED - if (pOldInstance && pNewInstance) - { - IGameRenderNode* pOldGameRenderNodeInstance = (IGameRenderNode*)pOldInstance; - IGameRenderNode* pNewGameRenderNodeInstance = (IGameRenderNode*)pNewInstance; - - // Unregister old node from engine - gEnv->p3DEngine->FreeRenderNodeState(pOldGameRenderNodeInstance); - - // Register new node with engine - gEnv->p3DEngine->RegisterEntity(pNewGameRenderNodeInstance); - - for (TGameRenderNodeVec::iterator iter(m_gameRenderNodes.begin()); - iter != m_gameRenderNodes.end(); ++iter) - { - IGameRenderNodePtr* ppRenderNode = *iter; - if (ppRenderNode) - { - IGameRenderNodePtr& pRenderNode = *ppRenderNode; - - if (pRenderNode == pOldGameRenderNodeInstance) - { - pRenderNode = pNewGameRenderNodeInstance; - } - } - } - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GameRenderElementInstanceReplaced -// Desc: Replaces Game Render Element instance for soft coding -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::GameRenderElementInstanceReplaced([[maybe_unused]] void* pOldInstance, [[maybe_unused]] void* pNewInstance) -{ -#ifdef SOFTCODE_ENABLED - if (pOldInstance && pNewInstance) - { - IGameRenderElement* pOldGameRenderElementInstance = (IGameRenderElement*)pOldInstance; - IGameRenderElement* pNewGameRenderElementInstance = (IGameRenderElement*)pNewInstance; - - pNewGameRenderElementInstance->UpdatePrivateImplementation(); - - for (TGameRenderElementVec::iterator iter(m_gameRenderElements.begin()); - iter != m_gameRenderElements.end(); ++iter) - { - IGameRenderElementPtr* ppRenderElement = *iter; - if (ppRenderElement) - { - IGameRenderElementPtr& pRenderElement = *ppRenderElement; - - if (pRenderElement == pOldGameRenderElementInstance) - { - pRenderElement = pNewGameRenderElementInstance; - } - } - } - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: SetPostEffectCVarCallbacks -// Desc: Sets Post effect CVar callbacks for testing and tweaking post effect values -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::SetPostEffectCVarCallbacks() -{ -#if DEBUG_GAME_FX_SYSTEM - ICVar* postEffectCvar = NULL; - const char postEffectNames[][64] = - { - "g_postEffect.FilterGrain_Amount", "g_postEffect.FilterRadialBlurring_Amount", - "g_postEffect.FilterRadialBlurring_ScreenPosX", - "g_postEffect.FilterRadialBlurring_ScreenPosY", "g_postEffect.FilterRadialBlurring_Radius", - "g_postEffect.Global_User_ColorC", "g_postEffect.Global_User_ColorM", - "g_postEffect.Global_User_ColorY", "g_postEffect.Global_User_ColorK", - "g_postEffect.Global_User_Brightness", "g_postEffect.Global_User_Contrast", - "g_postEffect.Global_User_Saturation", "g_postEffect.Global_User_ColorHue" - }; - - int postEffectNameCount = sizeof(postEffectNames) / sizeof(*postEffectNames); - - if (postEffectNameCount > 0) - { - // Calc name offset - const char* postEffectName = postEffectNames[0]; - s_postEffectCVarNameOffset = 0; - while ((*postEffectName) != 0) - { - s_postEffectCVarNameOffset++; - if ((*postEffectName) == '.') - { - break; - } - postEffectName++; - } - - // Set callback functions - for (int i = 0; i < postEffectNameCount; i++) - { - postEffectCvar = gEnv->pConsole->GetCVar(postEffectNames[i]); - if (postEffectCvar) - { - postEffectCvar->SetOnChangeCallback(PostEffectCVarCallback); - } - } - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: PostEffectCVarCallback -// Desc: Callback function of post effect cvars to set their values -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::PostEffectCVarCallback(ICVar* cvar) -{ - const char* effectName = cvar->GetName() + s_postEffectCVarNameOffset; - gEnv->p3DEngine->SetPostEffectParam(effectName, cvar->GetFVal()); -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterEffect -// Desc: Registers effect with effect system -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::RegisterEffect(IGameEffect* effect) -{ - FX_ASSERT_MESSAGE(m_isInitialised, - "Game Effects System trying to register an effect without being initialised"); - FX_ASSERT_MESSAGE(effect, "Trying to Register a NULL effect"); - - if (effect) - { - // If effect is registered, then unregister first - if (effect->IsFlagSet(GAME_EFFECT_REGISTERED)) - { - UnRegisterEffect(effect); - } - - // Add effect to effect list - IGameEffect** effectList = NULL; - bool isActive = effect->IsFlagSet(GAME_EFFECT_ACTIVE); - bool autoUpdatesWhenActive = effect->IsFlagSet(GAME_EFFECT_AUTO_UPDATES_WHEN_ACTIVE); - bool autoUpdatesWhenNotActive = effect->IsFlagSet(GAME_EFFECT_AUTO_UPDATES_WHEN_NOT_ACTIVE); - if ((isActive && autoUpdatesWhenActive) || ((!isActive) && autoUpdatesWhenNotActive)) - { - effectList = &m_effectsToUpdate; - } - else - { - effectList = &m_effectsNotToUpdate; - } - - if (*effectList) - { - (*effectList)->SetPrev(effect); - effect->SetNext(*effectList); - } - (*effectList) = effect; - - effect->SetFlag(GAME_EFFECT_REGISTERED, true); - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UnRegisterEffect -// Desc: UnRegisters effect from effect system -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::UnRegisterEffect(IGameEffect* effect) -{ - FX_ASSERT_MESSAGE( - m_isInitialised, - "Game Effects System trying to unregister an effect without being initialised"); - FX_ASSERT_MESSAGE(effect, "Trying to UnRegister a NULL effect"); - - if (effect && effect->IsFlagSet(GAME_EFFECT_REGISTERED)) - { - // If the effect is the next one to be updated, then point m_nextEffectToUpdate to the next - // effect after it - if (effect == m_nextEffectToUpdate) - { - m_nextEffectToUpdate = m_nextEffectToUpdate->Next(); - } - - if (effect->Prev()) - { - effect->Prev()->SetNext(effect->Next()); - } - else - { - if (m_effectsToUpdate == effect) - { - m_effectsToUpdate = effect->Next(); - } - else - { - FX_ASSERT_MESSAGE((m_effectsNotToUpdate == effect), - "Effect isn't either updating list"); - m_effectsNotToUpdate = effect->Next(); - } - } - - if (effect->Next()) - { - effect->Next()->SetPrev(effect->Prev()); - } - - effect->SetNext(NULL); - effect->SetPrev(NULL); - - effect->SetFlag(GAME_EFFECT_REGISTERED, false); - } -} //------------------------------------------------------------------------------------------------- - -void CGameEffectsSystem::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) -{ - Update(deltaTime); -} - -//-------------------------------------------------------------------------------------------------- -// Name: Update -// Desc: Updates effects system and any effects registered in it's update list -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::Update(float frameTime) -{ - FX_ASSERT_MESSAGE(m_isInitialised, - "Game Effects System trying to update without being initialised"); - - // Update effects - if (m_effectsToUpdate) - { - IGameEffect* effect = m_effectsToUpdate; - while (effect) - { - m_nextEffectToUpdate = effect->Next(); - if (effect->IsFlagSet(GAME_EFFECT_UPDATE_WHEN_PAUSED)) - { - SOFTCODE_RETRY(effect, effect->Update(frameTime)); - } - effect = m_nextEffectToUpdate; - } - } - - m_nextEffectToUpdate = NULL; - -#if DEBUG_GAME_FX_SYSTEM - DrawDebugDisplay(); -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: CreateSoftCodeInstance -// Desc: Creates soft code instance -//-------------------------------------------------------------------------------------------------- -#ifdef SOFTCODE_ENABLED -void* CGameEffectsSystem::CreateSoftCodeInstance(const char* pTypeName) -{ - void* pNewInstance = NULL; - - if (pTypeName) - { - for (std::vector::iterator iter(m_softCodeTypeLibs.begin()); - iter != m_softCodeTypeLibs.end(); ++iter) - { - ITypeLibrary* pLib = *iter; - if (pLib) - { - if (pNewInstance = pLib->CreateInstanceVoid(pTypeName)) - { - break; - } - } - } - } - - return pNewInstance; -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterSoftCodeLib -// Desc: Register soft code lib for creation of instances -//-------------------------------------------------------------------------------------------------- -#ifdef SOFTCODE_ENABLED -void CGameEffectsSystem::RegisterSoftCodeLib(ITypeLibrary* pLib) -{ - m_softCodeTypeLibs.push_back(pLib); -}; -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterGameRenderNode -// Desc: Registers game render node -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::RegisterGameRenderNode([[maybe_unused]] IGameRenderNodePtr& pGameRenderNode) -{ -#ifdef SOFTCODE_ENABLED - for (TGameRenderNodeVec::iterator iter(m_gameRenderNodes.begin()); - iter != m_gameRenderNodes.end(); ++iter) - { - IGameRenderNodePtr* ppIterRenderNode = *iter; - if (ppIterRenderNode == NULL) - { - *iter = &pGameRenderNode; - return; - } - } - m_gameRenderNodes.push_back(&pGameRenderNode); -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UnregisterGameRenderNode -// Desc: Unregisters game render node -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::UnregisterGameRenderNode([[maybe_unused]] IGameRenderNodePtr& pGameRenderNode) -{ -#ifdef SOFTCODE_ENABLED - TGameRenderNodeVec::iterator iter( - std::find(m_gameRenderNodes.begin(), m_gameRenderNodes.end(), &pGameRenderNode)); - if (iter != m_gameRenderNodes.end()) - { - *iter = NULL; - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterGameRenderElement -// Desc: Registers game render element -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::RegisterGameRenderElement([[maybe_unused]] IGameRenderElementPtr& pGameRenderElement) -{ -#ifdef SOFTCODE_ENABLED - for (TGameRenderElementVec::iterator iter(m_gameRenderElements.begin()); - iter != m_gameRenderElements.end(); ++iter) - { - IGameRenderElementPtr* ppIterRenderElement = *iter; - if (ppIterRenderElement == NULL) - { - *iter = &pGameRenderElement; - return; - } - } - m_gameRenderElements.push_back(&pGameRenderElement); -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UnregisterGameRenderElement -// Desc: Unregisters game render element -//-------------------------------------------------------------------------------------------------- -void CGameEffectsSystem::UnregisterGameRenderElement([[maybe_unused]] IGameRenderElementPtr& pGameRenderElement) -{ -#ifdef SOFTCODE_ENABLED - TGameRenderElementVec::iterator iter( - std::find(m_gameRenderElements.begin(), m_gameRenderElements.end(), &pGameRenderElement)); - if (iter != m_gameRenderElements.end()) - { - *iter = NULL; - } -#endif -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: DrawDebugDisplay -// Desc: Draws debug display -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -void CGameEffectsSystem::DrawDebugDisplay() -{ - static ColorF textCol(1.0f, 1.0f, 1.0f, 1.0f); - static ColorF controlCol(0.6f, 0.6f, 0.6f, 1.0f); - - static Vec2 textPos(10.0f, 10.0f); - static float textSize = 1.4f; - static float textYSpacing = 18.0f; - - static float effectNameXOffset = 100.0f; - static ColorF effectNameCol(0.0f, 1.0f, 0.0f, 1.0f); - - Vec2 currentTextPos = textPos; - - int debugEffectCount = s_effectDebugList.Size(); - if (GetISystem()->GetIConsole()->GetCVar("g_gameFXSystemDebug")->GetIVal() && debugEffectCount > 0) - { - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &textCol.r, - false, "Debug view:"); - gEnv->pRenderer->Draw2dLabel(currentTextPos.x + effectNameXOffset, currentTextPos.y, - textSize, &effectNameCol.r, false, - GAME_FX_DEBUG_VIEW_NAMES[m_debugView]); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Change debug view: Left/Right arrows)"); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &textCol.r, - false, "Debug effect:"); - gEnv->pRenderer->Draw2dLabel(currentTextPos.x + effectNameXOffset, currentTextPos.y, - textSize, &effectNameCol.r, false, - s_effectDebugList[s_currentDebugEffectId].effectName); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Change effect: NumPad +/-)"); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Reload effect data: NumPad .)"); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Reset Particle System: Delete)"); - currentTextPos.y += textYSpacing; - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, &controlCol.r, - false, "(Pause Particle System: End)"); - currentTextPos.y += textYSpacing; - - if (s_effectDebugList[s_currentDebugEffectId].displayCallback) - { - s_effectDebugList[s_currentDebugEffectId].displayCallback(currentTextPos, textSize, - textYSpacing); - } - - if (m_debugView == eGAME_FX_DEBUG_VIEW_EffectList) - { - static Vec2 listPos(350.0f, 50.0f); - static float nameSize = 150.0f; - static float tabSize = 60.0f; - currentTextPos = listPos; - - const int EFFECT_LIST_COUNT = 2; - IGameEffect* pEffectListArray[EFFECT_LIST_COUNT] = { - m_effectsToUpdate, - m_effectsNotToUpdate - }; - - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, - &effectNameCol.r, false, "Name"); - currentTextPos.x += nameSize; - - const int FLAG_COUNT = 9; - - const char* flagName[FLAG_COUNT] = { - "Init", "Rel", "ARels", "ADels", "AUWA", - "AUWnA", "Reg", "Actv", "DBG" - }; - const int flag[FLAG_COUNT] = { - GAME_EFFECT_INITIALISED, GAME_EFFECT_RELEASED, - GAME_EFFECT_AUTO_RELEASE, GAME_EFFECT_AUTO_DELETE, - GAME_EFFECT_AUTO_UPDATES_WHEN_ACTIVE, - GAME_EFFECT_AUTO_UPDATES_WHEN_NOT_ACTIVE, - GAME_EFFECT_REGISTERED, GAME_EFFECT_ACTIVE, - GAME_EFFECT_DEBUG_EFFECT - }; - - for (int i = 0; i < FLAG_COUNT; i++) - { - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, - &effectNameCol.r, false, flagName[i]); - currentTextPos.x += tabSize; - } - - currentTextPos.y += textYSpacing; - - for (int l = 0; l < EFFECT_LIST_COUNT; l++) - { - IGameEffect* pCurrentEffect = pEffectListArray[l]; - while (pCurrentEffect) - { - currentTextPos.x = listPos.x; - - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, - &textCol.r, false, pCurrentEffect->GetName()); - currentTextPos.x += nameSize; - - for (int i = 0; i < FLAG_COUNT; i++) - { - gEnv->pRenderer->Draw2dLabel(currentTextPos.x, currentTextPos.y, textSize, - &textCol.r, false, - pCurrentEffect->IsFlagSet(flag[i]) ? "1" - : "0"); - currentTextPos.x += tabSize; - } - - currentTextPos.y += textYSpacing; - pCurrentEffect = pCurrentEffect->Next(); - } - } - } - } -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: OnInputChannelEventFiltered -// Desc: Handles any debug input for the game effects system to test effects -//-------------------------------------------------------------------------------------------------- -bool CGameEffectsSystem::OnInputChannelEventFiltered([[maybe_unused]] const AzFramework::InputChannel& inputChannel) -{ -#if DEBUG_GAME_FX_SYSTEM - - int debugEffectCount = s_effectDebugList.Size(); - - if ((GetISystem()->GetIConsole()->GetCVar("g_gameFXSystemDebug")->GetIVal()) && (debugEffectCount > 0)) - { - if (AzFramework::InputDeviceKeyboard::IsKeyboardDevice(inputChannel.GetInputDevice().GetInputDeviceId()) && - inputChannel.IsStateBegan()) - { - const AZ::Crc32& inputChannelNameCrc32 = inputChannel.GetInputChannelId().GetNameCrc32(); - if (inputChannelNameCrc32 == GAME_FX_INPUT_IncrementDebugEffectId) - { - if (s_currentDebugEffectId < (debugEffectCount - 1)) - { - s_currentDebugEffectId++; - } - } - else if (inputChannelNameCrc32 == GAME_FX_INPUT_DecrementDebugEffectId) - { - if (s_currentDebugEffectId > 0) - { - s_currentDebugEffectId--; - } - } - else if (inputChannelNameCrc32 == GAME_FX_INPUT_DecrementDebugView) - { - if (m_debugView > 0) - { - OnDeActivateDebugView(m_debugView); - m_debugView--; - OnActivateDebugView(m_debugView); - } - } - else if (inputChannelNameCrc32 == GAME_FX_INPUT_IncrementDebugView) - { - if (m_debugView < (eMAX_GAME_FX_DEBUG_VIEWS - 1)) - { - OnDeActivateDebugView(m_debugView); - m_debugView++; - OnActivateDebugView(m_debugView); - } - } - else if (inputChannelNameCrc32 == GAME_FX_INPUT_ReloadEffectData) - { - ReloadData(); - } - - // Send input to current debug effect - if (s_effectDebugList[s_currentDebugEffectId].inputCallback) - { - s_effectDebugList[s_currentDebugEffectId].inputCallback(inputChannelNameCrc32); - } - } - } -#endif - - return false; // Return false so that other listeners will get this event -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GetDebugEffect -// Desc: Gets debug instance of effect -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -IGameEffect* CGameEffectsSystem::GetDebugEffect(const char* pEffectName) const -{ - const int EFFECT_LIST_COUNT = 2; - IGameEffect* pEffectListArray[EFFECT_LIST_COUNT] = {m_effectsToUpdate, m_effectsNotToUpdate}; - - for (int l = 0; l < EFFECT_LIST_COUNT; l++) - { - IGameEffect* pCurrentEffect = pEffectListArray[l]; - while (pCurrentEffect) - { - if (pCurrentEffect->IsFlagSet(GAME_EFFECT_DEBUG_EFFECT) && - (strcmp(pCurrentEffect->GetName(), pEffectName) == 0)) - { - return pCurrentEffect; - } - pCurrentEffect = pCurrentEffect->Next(); - } - } - - return NULL; -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: OnActivateDebugView -// Desc: Called on debug view activation -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -void CGameEffectsSystem::OnActivateDebugView(int debugView) -{ - switch (debugView) - { - case eGAME_FX_DEBUG_VIEW_Profiling: - { - ICVar* r_displayInfoCVar = gEnv->pConsole->GetCVar("r_DisplayInfo"); - if (r_displayInfoCVar) - { - r_displayInfoCVar->Set(1); - } - break; - } - } -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: OnDeActivateDebugView -// Desc: Called on debug view de-activation -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -void CGameEffectsSystem::OnDeActivateDebugView(int debugView) -{ - switch (debugView) - { - case eGAME_FX_DEBUG_VIEW_Profiling: - { - ICVar* r_displayInfoCVar = gEnv->pConsole->GetCVar("r_DisplayInfo"); - if (r_displayInfoCVar) - { - r_displayInfoCVar->Set(0); - } - break; - } - } -} -#endif -//-------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: RegisterEffectDebugData -// Desc: Registers effect's debug data with the game effects system, which will then call the -// relevant debug callback functions for the for the effect when its selected -//using the -// s_currentDebugEffectId -//-------------------------------------------------------------------------------------------------- -#if DEBUG_GAME_FX_SYSTEM -void IGameEffectSystem::RegisterEffectDebugData(DebugOnInputEventCallback inputEventCallback, - DebugDisplayCallback displayCallback, - const char* effectName) -{ - s_effectDebugList.push_back(SEffectDebugData(inputEventCallback, displayCallback, effectName)); -} -#endif -//-------------------------------------------------------------------------------------------------- diff --git a/Gems/GameEffectSystem/Code/source/GameEffectsSystem.h b/Gems/GameEffectSystem/Code/source/GameEffectsSystem.h deleted file mode 100644 index 4dd6fe0435..0000000000 --- a/Gems/GameEffectSystem/Code/source/GameEffectsSystem.h +++ /dev/null @@ -1,137 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _EFFECTS_GAMEEFFECTSSYSTEM_H_ -#define _EFFECTS_GAMEEFFECTSSYSTEM_H_ -#pragma once - -// Includes -#include "GameEffectSystem/IGameEffectSystem.h" -#include "GameEffectSystem/GameEffectsSystemDefines.h" -#include -#include - -//================================================================================================== -// Name: CGameEffectsSystem -// Desc: System to handle game effects, game render nodes and game render elements -// Game effect: separates out effect logic from game logic -// Game render node: handles the render object in 3d space -// Game render element: handles the rendering of the object -// CVar activation system: system used to have data driven cvars activated in game -//effects -// Post effect activation system: system used to have data driven post effects -//activated in game effects -// Author: James Chilvers -//================================================================================================== -class CGameEffectsSystem - : public IGameEffectSystem - , public AzFramework::InputChannelEventListener - , public ISoftCodeListener - , public AZ::TickBus::Handler -{ - friend struct SGameEffectSystemStaticData; - -public: - void Destroy(); - void Initialize(); - void LoadData(); - void ReleaseData(); - - template - T* CreateEffect() // Use if dynamic memory allocation is required for the game effect - { // Using this function then allows easy changing of memory allocator for all dynamically - // created effects - T* newEffect = new T; - return newEffect; - } - - // Each effect automatically registers and unregisters itself - SC_API void RegisterEffect(IGameEffect* effect) override; - SC_API void UnRegisterEffect(IGameEffect* effect) override; - - void Update(float frameTime); - - SC_API void RegisterGameRenderNode(IGameRenderNodePtr& pGameRenderNode); - SC_API void UnregisterGameRenderNode(IGameRenderNodePtr& pGameRenderNode); - - SC_API void RegisterGameRenderElement(IGameRenderElementPtr& pGameRenderElement); - SC_API void UnregisterGameRenderElement(IGameRenderElementPtr& pGameRenderElement); - -#ifdef SOFTCODE_ENABLED - SC_API void* - CreateSoftCodeInstance(const char* pTypeName) override; // Create soft code instance using libs - SC_API void - RegisterSoftCodeLib(ITypeLibrary* pLib) override; // Register soft code lib for creation of instances -#endif - - bool OnInputChannelEventFiltered(const AzFramework::InputChannel& inputChannel) override; - - // ISoftCodeListener implementation - void InstanceReplaced(void* pOldInstance, void* pNewInstance) override; - void GameRenderNodeInstanceReplaced(void* pOldInstance, void* pNewInstance) override; - void GameRenderElementInstanceReplaced(void* pOldInstance, void* pNewInstance) override; - - // SGameRulesListener implementation - void GameRulesInitialise(); - // #TODO: Have this receive events from GameRules - void EnteredGame();// override; - - void ReloadData(); - - CGameEffectsSystem(); - virtual ~CGameEffectsSystem(); - - // AZ::TickBus::Handler implementation - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - -private: - void Reset(); - void AutoReleaseAndDeleteFlaggedEffects(IGameEffect* effectList); - void AutoDeleteEffects(IGameEffect* effectList); - void SetPostEffectCVarCallbacks(); - static void PostEffectCVarCallback(ICVar* cvar); - -#if DEBUG_GAME_FX_SYSTEM - void DrawDebugDisplay(); - void OnActivateDebugView(int debugView); - void OnDeActivateDebugView(int debugView); - - int GetDebugView() const { return m_debugView; } - SC_API IGameEffect* GetDebugEffect(const char* pEffectName) const; - - static int s_currentDebugEffectId; - - int m_debugView; -#endif - - static int s_postEffectCVarNameOffset; - -#ifdef SOFTCODE_ENABLED - std::vector m_softCodeTypeLibs; - - typedef std::vector TGameRenderNodeVec; - TGameRenderNodeVec m_gameRenderNodes; - CGameRenderNodeSoftCodeListener* m_gameRenderNodeSoftCodeListener; - - typedef std::vector TGameRenderElementVec; - TGameRenderElementVec m_gameRenderElements; - CGameRenderElementSoftCodeListener* m_gameRenderElementSoftCodeListener; -#endif - - IGameEffect* m_effectsToUpdate; - IGameEffect* m_effectsNotToUpdate; - // If in update loop, this is the next effect to be updated this will get changed if the effect is unregistered - IGameEffect* m_nextEffectToUpdate; - bool m_isInitialised; - bool s_hasLoadedData; -}; //------------------------------------------------------------------------------------------------ - -#endif//_EFFECTS_GAMEEFFECTSSYSTEM_H_ diff --git a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.cpp b/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.cpp deleted file mode 100644 index c68b8526b0..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: CGameRenderElement -// Desc: Base class for all game render elements -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include "GameRenderElement.h" - -//-------------------------------------------------------------------------------------------------- -// Name: CGameRenderElement -// Desc: Constructor -//-------------------------------------------------------------------------------------------------- -CGameRenderElement::CGameRenderElement() -{ - m_pREGameEffect = NULL; -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: InitialiseGameRenderElement -// Desc: Initialises game render element -//-------------------------------------------------------------------------------------------------- -bool CGameRenderElement::InitialiseGameRenderElement() -{ - m_pREGameEffect = (CREGameEffect*)gEnv->pRenderer->EF_CreateRE(eDATA_GameEffect); - if (m_pREGameEffect) - { - m_pREGameEffect->SetPrivateImplementation(this); - m_pREGameEffect->mfUpdateFlags(FCEF_TRANSFORM); - } - - return true; -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: ReleaseGameRenderElement -// Desc: Releases game render element -//-------------------------------------------------------------------------------------------------- -void CGameRenderElement::ReleaseGameRenderElement() -{ - if (m_pREGameEffect) - { - m_pREGameEffect->SetPrivateImplementation(NULL); - m_pREGameEffect->Release(false); - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: UpdatePrivateImplementation -// Desc: Updates private implementation -//-------------------------------------------------------------------------------------------------- -void CGameRenderElement::UpdatePrivateImplementation() -{ - if (m_pREGameEffect) - { - m_pREGameEffect->SetPrivateImplementation(this); - } -} //------------------------------------------------------------------------------------------------- - -//-------------------------------------------------------------------------------------------------- -// Name: GetCREGameEffect -// Desc: returns the game effect render element -//-------------------------------------------------------------------------------------------------- -CREGameEffect* CGameRenderElement::GetCREGameEffect() -{ - return m_pREGameEffect; -} //------------------------------------------------------------------------------------------------- diff --git a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.h b/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.h deleted file mode 100644 index 37d149cdde..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElement.h +++ /dev/null @@ -1,78 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef _EFFECTS_RENDERELEMENTS_GAMERENDERELEMENT_H_ -#define _EFFECTS_RENDERELEMENTS_GAMERENDERELEMENT_H_ -#pragma once - -// Includes -#include "GameEffectsSystem.h" -#include - -// Forward declares -struct IGameRenderElementParams; - -//================================================================================================== -// Name: IGameRenderElement -// Desc: Base interface for all game render elements -// Author: James Chilvers -//================================================================================================== -struct IGameRenderElement - : public IREGameEffect - , public _i_reference_target_t -{ - DECLARE_TYPELIB(IGameRenderElement); // Allow soft coding on this interface - - virtual ~IGameRenderElement() {} - - virtual bool InitialiseGameRenderElement() = 0; - virtual void ReleaseGameRenderElement() = 0; - virtual void UpdatePrivateImplementation() = 0; - - virtual CREGameEffect* GetCREGameEffect() = 0; - - virtual IGameRenderElementParams* GetParams() = 0; -}; //------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: CGameRenderElement -// Desc: Base class for all game render elements -// Author: James Chilvers -//================================================================================================== -class CGameRenderElement - : public IGameRenderElement -{ - DECLARE_TYPE(CGameRenderElement, IGameRenderElement); // Exposes this type for SoftCoding -public: - CGameRenderElement(); - virtual ~CGameRenderElement() {} - - virtual bool InitialiseGameRenderElement(); - virtual void ReleaseGameRenderElement(); - virtual void UpdatePrivateImplementation(); - - virtual CREGameEffect* GetCREGameEffect(); - -protected: - CREGameEffect* SOFT(m_pREGameEffect); -}; //------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: IGameRenderElementParams -// Desc: Game Render Element params -// Author: James Chilvers -//================================================================================================== -struct IGameRenderElementParams -{ - virtual ~IGameRenderElementParams() {} -}; //------------------------------------------------------------------------------------------------ - -#endif//_EFFECTS_RENDERELEMENTS_GAMERENDERELEMENT_H_ diff --git a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElementSoftCodeLibrary.cpp b/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElementSoftCodeLibrary.cpp deleted file mode 100644 index 76bb0eb325..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderElements/GameRenderElementSoftCodeLibrary.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: GameRenderElementSoftCodeLibrary -// Desc: Render Node Soft Code Library -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include -#include "RenderElements/GameRenderElement.h" - -IMPLEMENT_TYPELIB(IGameRenderElement, - GAME_RENDER_ELEMENT_LIBRARY_NAME); // Implementation of Soft Coding library diff --git a/Gems/GameEffectSystem/Code/source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp b/Gems/GameEffectSystem/Code/source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp deleted file mode 100644 index a46e964016..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderNodes/GameRenderNodeSoftCodeLibrary.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -//================================================================================================== -// Name: GameRenderNodeSoftCodeLibrary -// Desc: Render Node Soft Code Library -// Author: James Chilvers -//================================================================================================== - -// Includes -#include "GameEffectSystem_precompiled.h" -#include -#include -#include - -IMPLEMENT_TYPELIB(IGameRenderNode, GAME_RENDER_NODE_LIBRARY_NAME); // Implementation of Soft Coding library diff --git a/Gems/GameEffectSystem/Code/source/RenderNodes/IGameRenderNode.h b/Gems/GameEffectSystem/Code/source/RenderNodes/IGameRenderNode.h deleted file mode 100644 index 7a88db116d..0000000000 --- a/Gems/GameEffectSystem/Code/source/RenderNodes/IGameRenderNode.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_GAMEDLL_EFFECTS_RENDERNODES_IGAMERENDERNODE_H -#define CRYINCLUDE_GAMEDLL_EFFECTS_RENDERNODES_IGAMERENDERNODE_H -#pragma once - -#include "Effects/RenderElements/GameRenderElement.h" -#include "Effects/GameEffectsSystem.h" - -// Forward declares -struct IGameRenderNodeParams; - -//================================================================================================== -// Name: IGameRenderNode -// Desc: Base interface for all game render nodes -// Author: James Chilvers -//================================================================================================== -struct IGameRenderNode - : public IRenderNode - , public _i_reference_target_t -{ - DECLARE_TYPELIB(IGameRenderNode); // Allow soft coding on this interface - - virtual ~IGameRenderNode() {} - - virtual bool InitialiseGameRenderNode() = 0; - virtual void ReleaseGameRenderNode() = 0; - - virtual void SetParams(const IGameRenderNodeParams* pParams = NULL) = 0; -}; //------------------------------------------------------------------------------------------------ - -//================================================================================================== -// Name: IGameRenderNodeParams -// Desc: Game render node params -// Author: James Chilvers -//================================================================================================== -struct IGameRenderNodeParams -{ - virtual ~IGameRenderNodeParams() {} -}; //------------------------------------------------------------------------------------------------ - -#endif // CRYINCLUDE_GAMEDLL_EFFECTS_RENDERNODES_IGAMERENDERNODE_H diff --git a/Gems/GameEffectSystem/gem.json b/Gems/GameEffectSystem/gem.json deleted file mode 100644 index ad97bc61ea..0000000000 --- a/Gems/GameEffectSystem/gem.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "gem_name": "GameEffectSystem", - "GemFormatVersion": 3, - "LinkType": "DynamicStatic", - "Name": "GameEffectSystem", - "DisplayName": "Game Effect System", - "Summary": "Provides fundamentals for creating and managing visual effects.", - "Tags": ["Effects System"], - "Uuid": "d378b5a7b47747d0a7aa741945df58f3", - "Version": "1.0.0", - "IconPath": "preview.png" -} diff --git a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLevelRunning.inl b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLevelRunning.inl index 174a5b43c4..335291d57e 100644 --- a/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLevelRunning.inl +++ b/Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLevelRunning.inl @@ -27,7 +27,6 @@ #include #include -#include #include #include @@ -59,10 +58,6 @@ namespace GameStateSamples { // Unload the currently loaded level levelSystem->UnloadLevel(); - if (iSystem->GetI3DEngine()) - { - iSystem->GetI3DEngine()->LoadEmptyLevel(); - } } } diff --git a/Gems/Gestures/Code/Source/Gestures_precompiled.h b/Gems/Gestures/Code/Source/Gestures_precompiled.h index c51e121abc..926c68d091 100644 --- a/Gems/Gestures/Code/Source/Gestures_precompiled.h +++ b/Gems/Gestures/Code/Source/Gestures_precompiled.h @@ -13,5 +13,4 @@ #pragma once #include -#include #include diff --git a/Gems/GradientSignal/Code/CMakeLists.txt b/Gems/GradientSignal/Code/CMakeLists.txt index 362ef61185..7b8c9813e6 100644 --- a/Gems/GradientSignal/Code/CMakeLists.txt +++ b/Gems/GradientSignal/Code/CMakeLists.txt @@ -24,7 +24,6 @@ ly_add_target( Legacy::CryCommon Gem::LmbrCentral Gem::SurfaceData - Gem::ImageProcessing.Headers Gem::ImageProcessingAtom.Headers ) @@ -42,7 +41,6 @@ ly_add_target( PRIVATE Gem::GradientSignal.Static PUBLIC - Gem::ImageProcessing.Headers # ImageProcessing/PixelFormats.h is part of a header in Includes Gem::ImageProcessingAtom.Headers # Atom/ImageProcessing/PixelFormats.h is part of a header in Includes RUNTIME_DEPENDENCIES Gem::LmbrCentral diff --git a/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h b/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h index 20db212da1..3114b4e811 100644 --- a/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h +++ b/Gems/GradientSignal/Code/Include/GradientSignal/ImageAsset.h @@ -15,7 +15,7 @@ #include #include #include -#include +#include namespace AZ { @@ -42,7 +42,7 @@ namespace GradientSignal AZ::u32 m_imageWidth = 0; AZ::u32 m_imageHeight = 0; AZ::u8 m_bytesPerPixel = 0; - ImageProcessing::EPixelFormat m_imageFormat = ImageProcessing::EPixelFormat::ePixelFormat_Unknown; + ImageProcessingAtom::EPixelFormat m_imageFormat = ImageProcessingAtom::EPixelFormat::ePixelFormat_Unknown; AZStd::vector m_imageData; }; diff --git a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp index cc207b59a3..ceaf2268e1 100644 --- a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp @@ -28,8 +28,6 @@ #include #include #include -#include -#include #include #include @@ -257,14 +255,6 @@ namespace GradientSignal return AZ::Uuid::CreateString("{7520DF20-16CA-4CF6-A6DB-D96759A09EE4}"); } - static ImageProcessing::EPixelFormat AtomPixelFormatToLegacyPixelFormat(ImageProcessingAtom::EPixelFormat atomPixFormat) - { - // This could be dangerous to do if these enums have differences in the middle. - // So far the enumerations correspond 1-to-1. Worst case this could be changed into a massive switch block. - int pixelFormatInt = static_cast(atomPixFormat); - return static_cast(pixelFormatInt); - } - static AZStd::unique_ptr AtomLoadImageFromPath(const AZStd::string& fullPath) { ImageProcessingAtom::IImageObjectPtr imageObject; @@ -286,7 +276,7 @@ namespace GradientSignal imageAsset->m_imageWidth = imageObject->GetWidth(0); imageAsset->m_imageHeight = imageObject->GetHeight(0); - imageAsset->m_imageFormat = AtomPixelFormatToLegacyPixelFormat(imageObject->GetPixelFormat()); + imageAsset->m_imageFormat = imageObject->GetPixelFormat(); AZ::u8* mem = nullptr; AZ::u32 pitch = 0; diff --git a/Gems/GradientSignal/Code/Source/GradientImageConversion.cpp b/Gems/GradientSignal/Code/Source/GradientImageConversion.cpp index cfbb71936b..4ed9107c47 100644 --- a/Gems/GradientSignal/Code/Source/GradientImageConversion.cpp +++ b/Gems/GradientSignal/Code/Source/GradientImageConversion.cpp @@ -13,7 +13,7 @@ #include "GradientSignal_precompiled.h" #include -#include +#include namespace { @@ -25,10 +25,10 @@ namespace constexpr auto A = 3; } - ImageProcessing::EPixelFormat ExportFormatToPixelFormat(GradientSignal::ExportFormat format) + ImageProcessingAtom::EPixelFormat ExportFormatToPixelFormat(GradientSignal::ExportFormat format) { using namespace GradientSignal; - using namespace ImageProcessing; + using namespace ImageProcessingAtom; switch (format) { @@ -49,29 +49,29 @@ namespace } } - template + template struct Underlying {}; template <> - struct Underlying + struct Underlying { using type = AZ::u8; }; template <> - struct Underlying + struct Underlying { using type = AZ::u16; }; template <> - struct Underlying + struct Underlying { using type = AZ::u32; }; template <> - struct Underlying + struct Underlying { using type = float; }; @@ -167,10 +167,10 @@ namespace buffer = AZStd::move(newBuffer); } - template - void ConvertBufferType(AZStd::vector& buffer, ImageProcessing::EPixelFormat newFormat, bool autoScale, AZStd::pair userRange) + template + void ConvertBufferType(AZStd::vector& buffer, ImageProcessingAtom::EPixelFormat newFormat, bool autoScale, AZStd::pair userRange) { - using namespace ImageProcessing; + using namespace ImageProcessingAtom; switch (newFormat) { @@ -195,9 +195,9 @@ namespace } } - ImageProcessing::EPixelFormat ConvertBufferType(AZStd::vector& buffer, ImageProcessing::EPixelFormat old, ImageProcessing::EPixelFormat newFormat, bool autoScale, AZStd::pair userRange) + ImageProcessingAtom::EPixelFormat ConvertBufferType(AZStd::vector& buffer, ImageProcessingAtom::EPixelFormat old, ImageProcessingAtom::EPixelFormat newFormat, bool autoScale, AZStd::pair userRange) { - using namespace ImageProcessing; + using namespace ImageProcessingAtom; switch (old) { @@ -356,9 +356,9 @@ namespace mem.resize(mem.size() / channels); } - AZStd::size_t GetChannels(ImageProcessing::EPixelFormat format) + AZStd::size_t GetChannels(ImageProcessingAtom::EPixelFormat format) { - using namespace ImageProcessing; + using namespace ImageProcessingAtom; switch (format) { @@ -379,10 +379,10 @@ namespace } template