From b38ab6c2bccec0f9c73db205fcff2eb0f4dafd07 Mon Sep 17 00:00:00 2001 From: Walters Date: Tue, 20 Apr 2021 22:17:11 -0700 Subject: [PATCH 001/185] Change reservation strategy in MotionInstancePool to reduce fragmentation --- Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp index cbe13308d9..d715fabd1c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/MotionInstancePool.cpp @@ -220,7 +220,7 @@ namespace EMotionFX //mPool->mFreeList.Reserve( numInstances * 2 ); if (mPool->mFreeList.GetMaxLength() < mPool->mNumInstances) { - mPool->mFreeList.Reserve(mPool->mNumInstances); + mPool->mFreeList.Reserve(mPool->mNumInstances + mPool->mFreeList.GetMaxLength() / 2); } mPool->mFreeList.ResizeFast(startIndex + numInstances); From 6b3abe3c56d5e267fc61c8341b9dcbf05051d876 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Sat, 24 Apr 2021 10:10:02 -0700 Subject: [PATCH 002/185] 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 | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 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(); - - shaderVariantReference->m_shaderOptionGroup = ShaderOptionGroup{ - shaderVariantReference->m_shaderAsset->GetShaderOptionGroupLayout(), - shaderVariantReference->m_shaderVariantId - }; + if (shaderVariantReference->m_shaderAsset.QueueLoad()) + { + shaderVariantReference->m_shaderAsset.BlockUntilLoadComplete(); + } + + 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 003/185] 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 15afcc341d26e9e302cda9af966841a5940afd0f Mon Sep 17 00:00:00 2001 From: hultonha Date: Mon, 26 Apr 2021 19:46:57 +0100 Subject: [PATCH 004/185] fixes and updates to CameraInput --- .../AzFramework/Viewport/CameraInput.cpp | 44 +++++++++---------- .../AzFramework/Viewport/CameraInput.h | 6 +-- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index ee49a95b23..1d0b440a9b 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -51,21 +51,21 @@ namespace AzFramework return nextCamera; } - void Cameras::AddCamera(AZStd::shared_ptr camera_input) + void Cameras::AddCamera(AZStd::shared_ptr cameraInput) { - m_idleCameraInputs.push_back(AZStd::move(camera_input)); + m_idleCameraInputs.push_back(AZStd::move(cameraInput)); } void Cameras::HandleEvents(const InputEvent& event) { - for (auto& camera_input : m_activeCameraInputs) + for (auto& cameraInput : m_activeCameraInputs) { - camera_input->HandleEvents(event); + cameraInput->HandleEvents(event); } - for (auto& camera_input : m_idleCameraInputs) + for (auto& cameraInput : m_idleCameraInputs) { - camera_input->HandleEvents(event); + cameraInput->HandleEvents(event); } } @@ -73,14 +73,14 @@ namespace AzFramework { for (int i = 0; i < m_idleCameraInputs.size();) { - auto& camera_input = m_idleCameraInputs[i]; - const bool can_begin = camera_input->Beginning() && + auto& cameraInput = m_idleCameraInputs[i]; + const bool canBegin = cameraInput->Beginning() && std::all_of(m_activeCameraInputs.cbegin(), m_activeCameraInputs.cend(), [](const auto& input) { return !input->Exclusive(); }) && - (!camera_input->Exclusive() || (camera_input->Exclusive() && m_activeCameraInputs.empty())); - if (can_begin) + (!cameraInput->Exclusive() || (cameraInput->Exclusive() && m_activeCameraInputs.empty())); + if (canBegin) { - m_activeCameraInputs.push_back(camera_input); + m_activeCameraInputs.push_back(cameraInput); using AZStd::swap; swap(m_idleCameraInputs[i], m_idleCameraInputs[m_idleCameraInputs.size() - 1]); m_idleCameraInputs.pop_back(); @@ -93,25 +93,25 @@ namespace AzFramework // accumulate Camera nextCamera = targetCamera; - for (auto& camera_input : m_activeCameraInputs) + for (auto& cameraInput : m_activeCameraInputs) { - nextCamera = camera_input->StepCamera(nextCamera, cursorDelta, scrollDelta, deltaTime); + nextCamera = cameraInput->StepCamera(nextCamera, cursorDelta, scrollDelta, deltaTime); } for (int i = 0; i < m_activeCameraInputs.size();) { - auto& camera_input = m_activeCameraInputs[i]; - if (camera_input->Ending()) + auto& cameraInput = m_activeCameraInputs[i]; + if (cameraInput->Ending()) { - camera_input->ClearActivation(); - m_idleCameraInputs.push_back(camera_input); + cameraInput->ClearActivation(); + m_idleCameraInputs.push_back(cameraInput); using AZStd::swap; swap(m_activeCameraInputs[i], m_activeCameraInputs[m_activeCameraInputs.size() - 1]); m_activeCameraInputs.pop_back(); } else { - camera_input->ContinueActivation(); + cameraInput->ContinueActivation(); i++; } } @@ -154,14 +154,14 @@ namespace AzFramework { Camera nextCamera = targetCamera; - nextCamera.m_pitch += float(cursorDelta.m_y) * m_props.m_rotateSpeed; - nextCamera.m_yaw += float(cursorDelta.m_x) * m_props.m_rotateSpeed; + nextCamera.m_pitch -= float(cursorDelta.m_y) * m_props.m_rotateSpeed; + nextCamera.m_yaw -= float(cursorDelta.m_x) * m_props.m_rotateSpeed; - auto clamp_rotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoOverPi, AZ::Constants::TwoOverPi); }; + auto clamp_rotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; nextCamera.m_yaw = clamp_rotation(nextCamera.m_yaw); // clamp pitch to be +-90 degrees - nextCamera.m_pitch = AZ::GetClamp(nextCamera.m_pitch, -AZ::Constants::Pi * 0.5f, AZ::Constants::Pi * 0.5f); + nextCamera.m_pitch = AZ::GetClamp(nextCamera.m_pitch, -AZ::Constants::HalfPi, AZ::Constants::HalfPi); return nextCamera; } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 736e2404d9..2fee6dc706 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -51,8 +51,8 @@ namespace AzFramework inline AZ::Transform Camera::Transform() const { - return AZ::Transform::CreateTranslation(m_lookAt) * AZ::Transform::CreateRotationX(m_pitch) * - AZ::Transform::CreateRotationZ(m_yaw) * AZ::Transform::CreateTranslation(AZ::Vector3::CreateAxisZ(m_lookDist)); + return AZ::Transform::CreateTranslation(m_lookAt) * AZ::Transform::CreateRotationZ(m_yaw) * + AZ::Transform::CreateRotationX(m_pitch) * AZ::Transform::CreateTranslation(AZ::Vector3::CreateAxisZ(m_lookDist)); } inline AZ::Matrix3x3 Camera::Rotation() const @@ -308,7 +308,7 @@ namespace AzFramework enum class TranslationType { // clang-format off - Nil = 0, + Nil = 0, Forward = 1 << 0, Backward = 1 << 1, Left = 1 << 2, From c8983183776f89ffb7d1cbab6fcce9b4d9d3283d Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 27 Apr 2021 10:30:07 +0100 Subject: [PATCH 005/185] updated camera changes --- .../AzFramework/Viewport/CameraInput.cpp | 37 ++++++++++--------- 1 file changed, 19 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 1d0b440a9b..33e11e84da 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -33,7 +33,7 @@ namespace AzFramework m_cameras.HandleEvents(event); } - Camera CameraSystem::StepCamera(const Camera& targetCamera, float deltaTime) + Camera CameraSystem::StepCamera(const Camera& targetCamera, const float deltaTime) { const auto cursorDelta = m_currentCursorPosition.has_value() && m_lastCursorPosition.has_value() ? m_currentCursorPosition.value() - m_lastCursorPosition.value() @@ -157,9 +157,9 @@ namespace AzFramework nextCamera.m_pitch -= float(cursorDelta.m_y) * m_props.m_rotateSpeed; nextCamera.m_yaw -= float(cursorDelta.m_x) * m_props.m_rotateSpeed; - auto clamp_rotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; + const auto clampRotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; - nextCamera.m_yaw = clamp_rotation(nextCamera.m_yaw); + nextCamera.m_yaw = clampRotation(nextCamera.m_yaw); // clamp pitch to be +-90 degrees nextCamera.m_pitch = AZ::GetClamp(nextCamera.m_pitch, -AZ::Constants::HalfPi, AZ::Constants::HalfPi); @@ -285,10 +285,10 @@ namespace AzFramework { Camera nextCamera = targetCamera; - const auto translation_basis = m_translationAxesFn(nextCamera); - const auto axisX = translation_basis.GetBasisX(); - const auto axisY = translation_basis.GetBasisY(); - const auto axisZ = translation_basis.GetBasisZ(); + const auto translationBasis = m_translationAxesFn(nextCamera); + const auto axisX = translationBasis.GetBasisX(); + const auto axisY = translationBasis.GetBasisY(); + const auto axisZ = translationBasis.GetBasisZ(); const float speed = [boost = m_boost, props = m_props]() { return props.m_translateSpeed * (boost ? props.m_boostMultiplier : 1.0f); @@ -366,7 +366,7 @@ namespace AzFramework } Camera OrbitCameraInput::StepCamera( - const Camera& targetCamera, const ScreenVector& cursorDelta, const float scrollDelta, float deltaTime) + const Camera& targetCamera, const ScreenVector& cursorDelta, const float scrollDelta, const float deltaTime) { Camera nextCamera = targetCamera; @@ -413,7 +413,7 @@ namespace AzFramework Camera OrbitDollyScrollCameraInput::StepCamera( const Camera& targetCamera, [[maybe_unused]] const ScreenVector& cursorDelta, const float scrollDelta, - [[maybe_unused]] float deltaTime) + [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + scrollDelta * m_props.m_dollySpeed, 0.0f); @@ -457,7 +457,7 @@ namespace AzFramework } Camera ScrollTranslationCameraInput::StepCamera( - const Camera& targetCamera, [[maybe_unused]] const ScreenVector& cursorDelta, float scrollDelta, + const Camera& targetCamera, [[maybe_unused]] const ScreenVector& cursorDelta, const float scrollDelta, [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; @@ -477,25 +477,26 @@ namespace AzFramework const auto clamp_rotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; // keep yaw in 0 - 360 range - float target_yaw = clamp_rotation(targetCamera.m_yaw); - const float current_yaw = clamp_rotation(currentCamera.m_yaw); + float targetYaw = clamp_rotation(targetCamera.m_yaw); + const float currentYaw = clamp_rotation(currentCamera.m_yaw); - auto sign = [](const float value) { return static_cast((0.0f < value) - (value < 0.0f)); }; + // return the sign of the float input (-1, 0, 1) + const auto sign = [](const float value) { return aznumeric_cast((0.0f < value) - (value < 0.0f)); }; // ensure smooth transition when moving across 0 - 360 boundary - const float yaw_delta = target_yaw - current_yaw; - if (std::abs(yaw_delta) >= AZ::Constants::Pi) + const float yawDelta = targetYaw - currentYaw; + if (std::abs(yawDelta) >= AZ::Constants::Pi) { - target_yaw -= AZ::Constants::TwoPi * sign(yaw_delta); + targetYaw -= AZ::Constants::TwoPi * sign(yawDelta); } Camera camera; - // note: the math for the lerp smoothing implementation for camera rotation and translation was inspired by this excellent + // note: the math for the lerp smoothing implementation for camera rotation and translation was inspired by this excellent // article by Scott Lembcke: https://www.gamasutra.com/blogs/ScottLembcke/20180404/316046/Improved_Lerp_Smoothing.php const float lookRate = std::exp2(props.m_lookSmoothness); const float lookT = std::exp2(-lookRate * deltaTime); camera.m_pitch = AZ::Lerp(targetCamera.m_pitch, currentCamera.m_pitch, lookT); - camera.m_yaw = AZ::Lerp(target_yaw, current_yaw, lookT); + camera.m_yaw = AZ::Lerp(targetYaw, currentYaw, lookT); const float moveRate = std::exp2(props.m_moveSmoothness); const float moveT = std::exp2(-moveRate * deltaTime); camera.m_lookDist = AZ::Lerp(targetCamera.m_lookDist, currentCamera.m_lookDist, moveT); From 1b946818a2c31e3de4019f8dce49dca5a33a133a Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 27 Apr 2021 13:58:17 +0100 Subject: [PATCH 006/185] more tidy-up to CameraInput.cpp --- .../AzFramework/Viewport/CameraInput.cpp | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 33e11e84da..6bde8dac85 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -190,18 +190,18 @@ namespace AzFramework { Camera nextCamera = targetCamera; - const auto pan_axes = m_panAxesFn(nextCamera); + const auto panAxes = m_panAxesFn(nextCamera); - const auto delta_pan_x = float(cursorDelta.m_x) * pan_axes.m_horizontalAxis * m_props.m_panSpeed; - const auto delta_pan_y = float(cursorDelta.m_y) * pan_axes.m_verticalAxis * m_props.m_panSpeed; + const auto deltaPanX = float(cursorDelta.m_x) * panAxes.m_horizontalAxis * m_props.m_panSpeed; + const auto deltaPanY = float(cursorDelta.m_y) * panAxes.m_verticalAxis * m_props.m_panSpeed; const auto inv = [](const bool invert) { constexpr float Dir[] = {1.0f, -1.0f}; return Dir[static_cast(invert)]; }; - nextCamera.m_lookAt += delta_pan_x * inv(m_props.m_panInvertX); - nextCamera.m_lookAt += delta_pan_y * -inv(m_props.m_panInvertY); + nextCamera.m_lookAt += deltaPanX * inv(m_props.m_panInvertX); + nextCamera.m_lookAt += deltaPanY * -inv(m_props.m_panInvertY); return nextCamera; } @@ -344,10 +344,6 @@ namespace AzFramework { if (input->m_channelId == InputDeviceKeyboard::Key::ModifierAltL) { - if (input->m_state == InputChannel::State::Updated) - { - goto end; - } if (input->m_state == InputChannel::State::Began) { BeginActivation(); @@ -358,7 +354,7 @@ namespace AzFramework } } } - end: + if (Active()) { m_orbitCameras.HandleEvents(event); @@ -388,7 +384,6 @@ namespace AzFramework if (Active()) { - // todo: need to return nested cameras to idle state when ending nextCamera = m_orbitCameras.StepCamera(nextCamera, cursorDelta, scrollDelta, deltaTime); } From 64e06c30107acc5f87e92cf24f3003620e4aedf1 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 27 Apr 2021 19:40:45 +0100 Subject: [PATCH 007/185] more updates to camera code --- .../AzFramework/Viewport/CameraInput.cpp | 17 ++++-- .../AzFramework/Viewport/CameraInput.h | 10 ++-- Code/Sandbox/Editor/EditorViewportWidget.cpp | 9 ++- .../Editor/ModernViewportCameraController.cpp | 55 +++++++++++++++---- .../Editor/ModernViewportCameraController.h | 15 +++-- 5 files changed, 76 insertions(+), 30 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 6bde8dac85..984526e373 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -19,7 +19,7 @@ namespace AzFramework { - void CameraSystem::HandleEvents(const InputEvent& event) + bool CameraSystem::HandleEvents(const InputEvent& event) { if (const auto& cursor_motion = AZStd::get_if(&event)) { @@ -30,7 +30,7 @@ namespace AzFramework m_scrollDelta = scroll->m_delta; } - m_cameras.HandleEvents(event); + return m_cameras.HandleEvents(event); } Camera CameraSystem::StepCamera(const Camera& targetCamera, const float deltaTime) @@ -56,17 +56,21 @@ namespace AzFramework m_idleCameraInputs.push_back(AZStd::move(cameraInput)); } - void Cameras::HandleEvents(const InputEvent& event) + bool Cameras::HandleEvents(const InputEvent& event) { + bool handling = false; for (auto& cameraInput : m_activeCameraInputs) { cameraInput->HandleEvents(event); + handling = !cameraInput->Idle() || handling; } for (auto& cameraInput : m_idleCameraInputs) { cameraInput->HandleEvents(event); } + + return handling; } Camera Cameras::StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, const float deltaTime) @@ -504,6 +508,11 @@ namespace AzFramework const auto& inputChannelId = inputChannel.GetInputChannelId(); const auto& inputDeviceId = inputChannel.GetInputDevice().GetInputDeviceId(); + const bool wasMouseButton = + AZStd::any_of(InputDeviceMouse::Button::All.begin(), InputDeviceMouse::Button::All.end(), [inputChannelId](const auto& button) { + return button == inputChannelId; + }); + if (inputChannelId == InputDeviceMouse::SystemCursorPosition) { AZ::Vector2 systemCursorPositionNormalized = AZ::Vector2::CreateZero(); @@ -517,7 +526,7 @@ namespace AzFramework { return ScrollEvent{inputChannel.GetValue()}; } - else if (InputDeviceMouse::IsMouseDevice(inputDeviceId) || InputDeviceKeyboard::IsKeyboardDevice(inputDeviceId)) + else if ((InputDeviceMouse::IsMouseDevice(inputDeviceId) && wasMouseButton) || InputDeviceKeyboard::IsKeyboardDevice(inputDeviceId)) { return DiscreteInputEvent{inputChannelId, inputChannel.GetState()}; } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 2fee6dc706..cbfe603c83 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -52,7 +52,7 @@ namespace AzFramework inline AZ::Transform Camera::Transform() const { return AZ::Transform::CreateTranslation(m_lookAt) * AZ::Transform::CreateRotationZ(m_yaw) * - AZ::Transform::CreateRotationX(m_pitch) * AZ::Transform::CreateTranslation(AZ::Vector3::CreateAxisZ(m_lookDist)); + AZ::Transform::CreateRotationX(m_pitch) * AZ::Transform::CreateTranslation(AZ::Vector3::CreateAxisY(m_lookDist)); } inline AZ::Matrix3x3 Camera::Rotation() const @@ -171,7 +171,7 @@ namespace AzFramework { public: void AddCamera(AZStd::shared_ptr cameraInput); - void HandleEvents(const InputEvent& event); + bool HandleEvents(const InputEvent& event); Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime); void Reset(); @@ -183,7 +183,7 @@ namespace AzFramework class CameraSystem { public: - void HandleEvents(const InputEvent& event); + bool HandleEvents(const InputEvent& event); Camera StepCamera(const Camera& targetCamera, float deltaTime); Cameras m_cameras; @@ -369,7 +369,7 @@ namespace AzFramework struct Props { - float m_dollySpeed = 0.2f; + float m_dollySpeed = 0.02f; } m_props; }; @@ -393,7 +393,7 @@ namespace AzFramework struct Props { - float m_translateSpeed = 0.2f; + float m_translateSpeed = 0.02f; } m_props; }; diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 25588e85a7..6a32a6abb1 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -1633,8 +1633,8 @@ void EditorViewportWidget::keyPressEvent(QKeyEvent* event) QCoreApplication::sendEvent(GetIEditor()->GetEditorMainWindow(), event); } - // NOTE: we keep track of keypresses and releases explicitly because the OS/Qt will insert a slight delay between sending - // keyevents when the key is held down. This is standard, but makes responding to key events for game style input silly + // NOTE: we keep track of key presses and releases explicitly because the OS/Qt will insert a slight delay between sending + // key events when the key is held down. This is standard, but makes responding to key events for game style input silly // because we want the movement to be butter smooth. if (!event->isAutoRepeat()) { @@ -2428,7 +2428,10 @@ void EditorViewportWidget::SetDefaultCamera() return; } ResetToViewSourceType(ViewSourceType::None); - gEnv->p3DEngine->GetPostEffectBaseGroup()->SetParam("Dof_Active", 0.0f); + 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/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 80bd9416f7..09fd5be2e9 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -14,9 +14,14 @@ #include #include +#include #include +#include #include #include +#include + +AZ_CVAR(bool, ed_newCameraSystemDebug, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Enable debug drawing for the new camera system"); namespace SandboxEditor { @@ -37,8 +42,17 @@ namespace SandboxEditor return viewportContext; } + struct ModernViewportCameraControllerInstance::Impl + { + AzFramework::Camera m_camera; + AzFramework::Camera m_targetCamera; + AzFramework::SmoothProps m_smoothProps; + AzFramework::CameraSystem m_cameraSystem; + }; + ModernViewportCameraControllerInstance::ModernViewportCameraControllerInstance(const AzFramework::ViewportId viewportId) : MultiViewportControllerInstanceInterface(viewportId) + , m_impl(AZStd::make_unique()) { // LYN-2315 TODO - move setup out of constructor, pass cameras in auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::InputDeviceMouse::Button::Right); @@ -58,21 +72,28 @@ namespace SandboxEditor orbitCamera->m_orbitCameras.AddCamera(orbitDollyMoveCamera); orbitCamera->m_orbitCameras.AddCamera(orbitPanCamera); - m_cameraSystem.m_cameras.AddCamera(firstPersonRotateCamera); - m_cameraSystem.m_cameras.AddCamera(firstPersonPanCamera); - m_cameraSystem.m_cameras.AddCamera(firstPersonTranslateCamera); - m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); - m_cameraSystem.m_cameras.AddCamera(orbitCamera); + m_impl->m_cameraSystem.m_cameras.AddCamera(firstPersonRotateCamera); + m_impl->m_cameraSystem.m_cameras.AddCamera(firstPersonPanCamera); + m_impl->m_cameraSystem.m_cameras.AddCamera(firstPersonTranslateCamera); + m_impl->m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); + m_impl->m_cameraSystem.m_cameras.AddCamera(orbitCamera); if (const auto viewportContext = RetrieveViewportContext(viewportId)) { // set position but not orientation - m_targetCamera.m_lookAt = viewportContext->GetCameraTransform().GetTranslation(); + m_impl->m_targetCamera.m_lookAt = viewportContext->GetCameraTransform().GetTranslation(); // LYN-2315 TODO https://www.geometrictools.com/Documentation/EulerAngles.pdf - m_camera = m_targetCamera; + m_impl->m_camera = m_impl->m_targetCamera; } + + AzFramework::ViewportDebugDisplayEventBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); + } + + ModernViewportCameraControllerInstance::~ModernViewportCameraControllerInstance() + { + AzFramework::ViewportDebugDisplayEventBus::Handler::BusDisconnect(); } bool ModernViewportCameraControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) @@ -80,18 +101,28 @@ namespace SandboxEditor AzFramework::WindowSize windowSize; AzFramework::WindowRequestBus::EventResult( windowSize, event.m_windowHandle, &AzFramework::WindowRequestBus::Events::GetClientAreaSize); - m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel, windowSize)); - return true; // consume event + return m_impl->m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel, windowSize)); } void ModernViewportCameraControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) { if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { - m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); - m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); + m_impl->m_targetCamera = m_impl->m_cameraSystem.StepCamera(m_impl->m_targetCamera, event.m_deltaTime.count()); + m_impl->m_camera = + AzFramework::SmoothCamera(m_impl->m_camera, m_impl->m_targetCamera, m_impl->m_smoothProps, event.m_deltaTime.count()); + + viewportContext->SetCameraTransform(m_impl->m_camera.Transform()); + } + } - viewportContext->SetCameraTransform(m_camera.Transform()); + void ModernViewportCameraControllerInstance::DisplayViewport( + [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) + { + if (ed_newCameraSystemDebug) + { + debugDisplay.SetColor(AZ::Colors::White); + debugDisplay.DrawWireSphere(m_impl->m_targetCamera.m_lookAt, 0.5f); } } } // namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index c65dbc8b8a..57fdd1cb55 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -12,25 +12,28 @@ #pragma once -#include +#include #include namespace SandboxEditor { - class ModernViewportCameraControllerInstance final : public AzFramework::MultiViewportControllerInstanceInterface + class ModernViewportCameraControllerInstance final : public AzFramework::MultiViewportControllerInstanceInterface, + private AzFramework::ViewportDebugDisplayEventBus::Handler { public: explicit ModernViewportCameraControllerInstance(AzFramework::ViewportId viewportId); + ~ModernViewportCameraControllerInstance(); // MultiViewportControllerInstanceInterface overrides ... bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override; void UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) override; + // AzFramework::ViewportDebugDisplayEventBus ... + void DisplayViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; + private: - AzFramework::Camera m_camera; - AzFramework::Camera m_targetCamera; - AzFramework::SmoothProps m_smoothProps; - AzFramework::CameraSystem m_cameraSystem; + struct Impl; + AZStd::unique_ptr m_impl; }; using ModernViewportCameraController = AzFramework::MultiViewportController; From f2ce91fb44d53c25a5191c8fc587cc5f6a0bba1a Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Tue, 27 Apr 2021 14:57:51 -0500 Subject: [PATCH 008/185] AtomDebugDisplayViewportInterface - Fix Crash if FontQueryInterface in null --- .../AtomDebugDisplayViewportInterface.cpp | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 77f15284f1..690963e26b 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -1234,8 +1234,15 @@ namespace AZ::AtomBridge int srcOffsetX [[maybe_unused]], int srcOffsetY [[maybe_unused]]) { + // abort draw if draw is invalid or font query interface is missing. + if (!text || size == 0.0f || !AZ::Interface::Get()) + { + return; + } + AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); - if (!fontDrawInterface || !text || size == 0.0f) + // abort draw if font draw interface is missing + if (!fontDrawInterface) { return; } @@ -1263,8 +1270,15 @@ namespace AZ::AtomBridge const char* text, bool center) { + // abort draw if draw is invalid or font query interface is missing. + if (!text || size == 0.0f || !AZ::Interface::Get()) + { + return; + } + AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); - if (!fontDrawInterface || !text || size == 0.0f) + // abort draw if font draw interface is missing + if (!fontDrawInterface) { return; } From d35adce246cc8a817d36271dbce2a7e27bbf84e9 Mon Sep 17 00:00:00 2001 From: greerdv Date: Thu, 29 Apr 2021 11:46:08 +0100 Subject: [PATCH 009/185] 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 010/185] 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 011/185] 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 7d96fcdf1fe0bd8dbf19b1be00580019b786ddd4 Mon Sep 17 00:00:00 2001 From: hultonha Date: Thu, 29 Apr 2021 18:39:03 +0100 Subject: [PATCH 012/185] updates to fix camera behaviour --- .../AzFramework/Viewport/CameraInput.cpp | 11 ++++- .../AzFramework/Viewport/CameraInput.h | 19 +++++++- Code/Sandbox/Editor/CryEditDoc.cpp | 13 +++++- .../Editor/ModernViewportCameraController.cpp | 43 +++++++++---------- .../Editor/ModernViewportCameraController.h | 15 +++++-- 5 files changed, 69 insertions(+), 32 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 984526e373..6d8c019fec 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -12,11 +12,16 @@ #include "CameraInput.h" +#include #include #include #include #include +AZ_CVAR( + float, ed_newCameraSystemDefaultPlaneHeight, 34.0f, nullptr, AZ::ConsoleFunctorFlags::Null, + "What is the default height of the ground plane to do intersection tests against when orbiting"); + namespace AzFramework { bool CameraSystem::HandleEvents(const InputEvent& event) @@ -373,9 +378,11 @@ namespace AzFramework if (Beginning()) { float hit_distance = 0.0f; - if (AZ::Plane::CreateFromNormalAndPoint(AZ::Vector3::CreateAxisZ(), AZ::Vector3::CreateZero()) - .CastRay(targetCamera.Translation(), targetCamera.Rotation().GetBasisY() * m_props.m_maxOrbitDistance, hit_distance)) + if (AZ::Plane::CreateFromNormalAndPoint( + AZ::Vector3::CreateAxisZ(), AZ::Vector3::CreateAxisZ(ed_newCameraSystemDefaultPlaneHeight)) + .CastRay(targetCamera.Translation(), targetCamera.Rotation().GetBasisY(), hit_distance)) { + hit_distance = AZStd::min(hit_distance, m_props.m_maxOrbitDistance); nextCamera.m_lookDist = -hit_distance; nextCamera.m_lookAt = targetCamera.Translation() + targetCamera.Rotation().GetBasisY() * hit_distance; } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index cbfe603c83..3491453ff1 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -12,6 +12,7 @@ #pragma once +#include #include #include #include @@ -25,6 +26,22 @@ namespace AzFramework { struct WindowSize; + // to be moved + class ModernViewportCameraControllerRequests : public AZ::EBusTraits + { + public: + using BusIdType = AzFramework::ViewportId; ///< ViewportId - used to address requests to this EBus. + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + + virtual void SetTargetCameraTransform(const AZ::Transform& transform) = 0; + + protected: + ~ModernViewportCameraControllerRequests() = default; + }; + + using ModernViewportCameraControllerRequestBus = AZ::EBus; + struct Camera { AZ::Vector3 m_lookAt = AZ::Vector3::CreateZero(); //!< Position of camera when m_lookDist is zero, @@ -411,7 +428,7 @@ namespace AzFramework struct Props { - float m_defaultOrbitDistance = 15.0f; + float m_defaultOrbitDistance = 60.0f; float m_maxOrbitDistance = 100.0f; } m_props; }; diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 8819c8b382..00e5a3b85b 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -28,6 +28,7 @@ #include #include #include +#include // AzToolsFramework #include @@ -669,13 +670,21 @@ void CCryEditDoc::SerializeViewSettings(CXmlArchive& xmlAr) CViewport* pVP = GetIEditor()->GetViewManager()->GetView(i); + Matrix34 tm = Matrix34::CreateRotationXYZ(va); + tm.SetTranslation(vp); + if (pVP) { - Matrix34 tm = Matrix34::CreateRotationXYZ(va); - tm.SetTranslation(vp); pVP->SetViewTM(tm); } + if (auto viewportContext = AZ::Interface::Get()->GetDefaultViewportContext()) + { + AzFramework::ModernViewportCameraControllerRequestBus::Event( + viewportContext->GetId(), &AzFramework::ModernViewportCameraControllerRequestBus::Events::SetTargetCameraTransform, + LYTransformToAZTransform(tm)); + } + // Load grid. auto gridName = QString("Grid%1").arg(useOldViewFormat ? "" : QString::number(i)); XmlNodeRef gridNode = xmlAr.root->newChild(gridName.toUtf8().constData()); diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 09fd5be2e9..f94f067a21 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -16,7 +16,6 @@ #include #include #include -#include #include #include #include @@ -42,17 +41,8 @@ namespace SandboxEditor return viewportContext; } - struct ModernViewportCameraControllerInstance::Impl - { - AzFramework::Camera m_camera; - AzFramework::Camera m_targetCamera; - AzFramework::SmoothProps m_smoothProps; - AzFramework::CameraSystem m_cameraSystem; - }; - ModernViewportCameraControllerInstance::ModernViewportCameraControllerInstance(const AzFramework::ViewportId viewportId) : MultiViewportControllerInstanceInterface(viewportId) - , m_impl(AZStd::make_unique()) { // LYN-2315 TODO - move setup out of constructor, pass cameras in auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::InputDeviceMouse::Button::Right); @@ -72,27 +62,29 @@ namespace SandboxEditor orbitCamera->m_orbitCameras.AddCamera(orbitDollyMoveCamera); orbitCamera->m_orbitCameras.AddCamera(orbitPanCamera); - m_impl->m_cameraSystem.m_cameras.AddCamera(firstPersonRotateCamera); - m_impl->m_cameraSystem.m_cameras.AddCamera(firstPersonPanCamera); - m_impl->m_cameraSystem.m_cameras.AddCamera(firstPersonTranslateCamera); - m_impl->m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); - m_impl->m_cameraSystem.m_cameras.AddCamera(orbitCamera); + m_cameraSystem.m_cameras.AddCamera(firstPersonRotateCamera); + m_cameraSystem.m_cameras.AddCamera(firstPersonPanCamera); + m_cameraSystem.m_cameras.AddCamera(firstPersonTranslateCamera); + m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); + m_cameraSystem.m_cameras.AddCamera(orbitCamera); if (const auto viewportContext = RetrieveViewportContext(viewportId)) { // set position but not orientation - m_impl->m_targetCamera.m_lookAt = viewportContext->GetCameraTransform().GetTranslation(); + m_targetCamera.m_lookAt = viewportContext->GetCameraTransform().GetTranslation(); // LYN-2315 TODO https://www.geometrictools.com/Documentation/EulerAngles.pdf - m_impl->m_camera = m_impl->m_targetCamera; + m_camera = m_targetCamera; } AzFramework::ViewportDebugDisplayEventBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); + AzFramework::ModernViewportCameraControllerRequestBus::Handler::BusConnect(viewportId); } ModernViewportCameraControllerInstance::~ModernViewportCameraControllerInstance() { + AzFramework::ModernViewportCameraControllerRequestBus::Handler::BusDisconnect(); AzFramework::ViewportDebugDisplayEventBus::Handler::BusDisconnect(); } @@ -101,18 +93,18 @@ namespace SandboxEditor AzFramework::WindowSize windowSize; AzFramework::WindowRequestBus::EventResult( windowSize, event.m_windowHandle, &AzFramework::WindowRequestBus::Events::GetClientAreaSize); - return m_impl->m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel, windowSize)); + return m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel, windowSize)); } void ModernViewportCameraControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) { if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { - m_impl->m_targetCamera = m_impl->m_cameraSystem.StepCamera(m_impl->m_targetCamera, event.m_deltaTime.count()); - m_impl->m_camera = - AzFramework::SmoothCamera(m_impl->m_camera, m_impl->m_targetCamera, m_impl->m_smoothProps, event.m_deltaTime.count()); + m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); + m_camera = + AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); - viewportContext->SetCameraTransform(m_impl->m_camera.Transform()); + viewportContext->SetCameraTransform(m_camera.Transform()); } } @@ -122,7 +114,12 @@ namespace SandboxEditor if (ed_newCameraSystemDebug) { debugDisplay.SetColor(AZ::Colors::White); - debugDisplay.DrawWireSphere(m_impl->m_targetCamera.m_lookAt, 0.5f); + debugDisplay.DrawWireSphere(m_targetCamera.m_lookAt, 0.5f); } } + + void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) + { + m_targetCamera.m_lookAt = transform.GetTranslation(); + } } // namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index 57fdd1cb55..a3d4f8cea6 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -13,12 +13,14 @@ #pragma once #include +#include #include namespace SandboxEditor { class ModernViewportCameraControllerInstance final : public AzFramework::MultiViewportControllerInstanceInterface, - private AzFramework::ViewportDebugDisplayEventBus::Handler + private AzFramework::ViewportDebugDisplayEventBus::Handler, + private AzFramework::ModernViewportCameraControllerRequestBus::Handler { public: explicit ModernViewportCameraControllerInstance(AzFramework::ViewportId viewportId); @@ -28,12 +30,17 @@ namespace SandboxEditor bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override; void UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) override; - // AzFramework::ViewportDebugDisplayEventBus ... + // AzFramework::ViewportDebugDisplayEventBus overrides ... void DisplayViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; + // ModernViewportCameraControllerRequestBus overrides ... + void SetTargetCameraTransform(const AZ::Transform& transform) override; + private: - struct Impl; - AZStd::unique_ptr m_impl; + AzFramework::Camera m_camera; + AzFramework::Camera m_targetCamera; + AzFramework::SmoothProps m_smoothProps; + AzFramework::CameraSystem m_cameraSystem; }; using ModernViewportCameraController = AzFramework::MultiViewportController; From d433cd623becb2606ff764bb67a4f11b86ea280c Mon Sep 17 00:00:00 2001 From: srikappa Date: Thu, 29 Apr 2021 17:02:44 -0700 Subject: [PATCH 013/185] Fix undo for nested prefab creation by providing link patches to the undo node --- .../Prefab/PrefabPublicHandler.cpp | 52 +++++++++++++++++-- .../Prefab/PrefabPublicHandler.h | 11 ++++ .../Prefab/PrefabSystemComponent.cpp | 5 +- .../AzToolsFramework/Prefab/PrefabUndo.cpp | 10 ++-- .../AzToolsFramework/Prefab/PrefabUndo.h | 4 +- .../Prefab/PrefabUndoHelpers.cpp | 8 ++- .../Prefab/PrefabUndoHelpers.h | 4 +- 7 files changed, 75 insertions(+), 19 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 1e9cc35230..1b4bf9f50c 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -96,9 +96,12 @@ namespace AzToolsFramework // target templates of the other instances. for (auto& nestedInstance : instances) { - PrefabUndoHelpers::RemoveLink( - nestedInstance->GetTemplateId(), commonRootEntityOwningInstance->get().GetTemplateId(), - nestedInstance->GetInstanceAlias(), nestedInstance->GetLinkId(), undoBatch.GetUndoBatch()); + PrefabOperationResult removeLinkResult = RemoveLink( + nestedInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); + if (!removeLinkResult.IsSuccess()) + { + return removeLinkResult; + } } PrefabUndoHelpers::UpdatePrefabInstance( @@ -287,6 +290,49 @@ namespace AzToolsFramework m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter)); } + PrefabOperationResult PrefabPublicHandler::RemoveLink( + AZStd::unique_ptr& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch) + { + LinkReference nestedInstanceLink = m_prefabSystemComponentInterface->FindLink(sourceInstance->GetLinkId()); + if (!nestedInstanceLink.has_value()) + { + AZ_Assert(false, "A valid link was not found for one of the instances provided as input for the CreatePrefab operation."); + return AZ::Failure( + AZStd::string("A valid link was not found for one of the instances provided as input for the CreatePrefab operation.")); + } + + PrefabDomReference nestedInstanceLinkDom = nestedInstanceLink->get().GetLinkDom(); + if (!nestedInstanceLinkDom.has_value()) + { + AZ_Assert( + false, + "A valid DOM was not found for the link corresponding to one of the instances provided as input for the " + "CreatePrefab operation."); + return AZ::Failure(AZStd::string("A valid DOM was not found for the link corresponding to one of the instances " + "provided as input for the CreatePrefab operation.")); + } + + PrefabDomValueReference nestedInstanceLinkPatches = + PrefabDomUtils::FindPrefabDomValue(nestedInstanceLinkDom->get(), PrefabDomUtils::PatchesName); + if (!nestedInstanceLinkPatches.has_value()) + { + AZ_Assert( + false, + "A valid DOM for patches was not found for the link corresponding to one of the instances provided as input for the " + "CreatePrefab operation."); + return AZ::Failure(AZStd::string("A valid DOM for patcheswas not found for the link corresponding to one of the instances " + "provided as input for the CreatePrefab operation.")); + } + + PrefabDom patchesCopyForUndoSupport; + patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator()); + PrefabUndoHelpers::RemoveLink( + sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(), + patchesCopyForUndoSupport, undoBatch); + + return AZ::Success(); + } + PrefabOperationResult PrefabPublicHandler::SavePrefab(AZ::IO::Path filePath) { auto templateId = m_prefabSystemComponentInterface->GetTemplateIdFromFilePath(filePath.c_str()); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index e83513dbff..8d27603e8d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -82,6 +82,17 @@ namespace AzToolsFramework const EntityList& topLevelEntities, Instance& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch, AZ::EntityId commonRootEntityId); + /** + * Removes the link between template of the sourceInstance and the template corresponding to targetTemplateId. + * + * \param sourceInstance The instance corresponding to the source template of the link to be removed. + * \param targetTemplateId The id of the target template of the link to be removed. + * \param undoBatch The undo batch to set as parent for this remove link action. + * \return PrefabOperationResult Indicates whether the removal of link was successful. + */ + PrefabOperationResult RemoveLink( + AZStd::unique_ptr& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch); + /** * Given a list of entityIds, finds the prefab instance that owns the common root entity of the entityIds. * diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index 3f660bb73b..c6a95b01fe 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -663,8 +663,9 @@ namespace AzToolsFramework newLink.SetSourceTemplateId(linkSourceId); newLink.SetInstanceName(instanceAlias.c_str()); newLink.GetLinkDom().SetObject(); - newLink.GetLinkDom().AddMember(rapidjson::StringRef(PrefabDomUtils::SourceName), - rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), newLink.GetLinkDom().GetAllocator()); + newLink.GetLinkDom().AddMember( + rapidjson::StringRef(PrefabDomUtils::SourceName), rapidjson::StringRef(sourceTemplate.GetFilePath().c_str()), + newLink.GetLinkDom().GetAllocator()); if (linkPatch && linkPatch->get().IsArray() && !(linkPatch->get().Empty())) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp index ea3fa5d84d..ad0cdc166a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.cpp @@ -113,7 +113,7 @@ namespace AzToolsFramework , m_sourceId(InvalidTemplateId) , m_instanceAlias("") , m_linkId(InvalidLinkId) - , m_linkDom(PrefabDom()) + , m_linkPatches(PrefabDom()) , m_linkStatus(LinkStatus::LINKSTATUS) { m_prefabSystemComponentInterface = AZ::Interface::Get(); @@ -124,7 +124,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkDom, + PrefabDomReference linkPatches, const LinkId linkId) { m_targetId = targetId; @@ -132,9 +132,9 @@ namespace AzToolsFramework m_instanceAlias = instanceAlias; m_linkId = linkId; - if (linkDom.has_value()) + if (linkPatches.has_value()) { - m_linkDom = AZStd::move(linkDom->get()); + m_linkPatches = AZStd::move(linkPatches->get()); } //if linkId is invalid, set as ADD @@ -193,7 +193,7 @@ namespace AzToolsFramework void PrefabUndoInstanceLink::AddLink() { - m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkDom, m_linkId); + m_linkId = m_prefabSystemComponentInterface->CreateLink(m_targetId, m_sourceId, m_instanceAlias, m_linkPatches, m_linkId); } void PrefabUndoInstanceLink::RemoveLink() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h index 0d15d707d2..49bae4eda0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndo.h @@ -101,7 +101,7 @@ namespace AzToolsFramework const TemplateId& targetId, const TemplateId& sourceId, const InstanceAlias& instanceAlias, - PrefabDomReference linkDom = PrefabDomReference(), + PrefabDomReference linkPatches = PrefabDomReference(), const LinkId linkId = InvalidLinkId); void Undo() override; @@ -120,7 +120,7 @@ namespace AzToolsFramework InstanceAlias m_instanceAlias; LinkId m_linkId; - PrefabDom m_linkDom; //data for delete/update + PrefabDom m_linkPatches; //data for delete/update LinkStatus m_linkStatus; PrefabSystemComponentInterface* m_prefabSystemComponentInterface = nullptr; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp index 2062e8b12c..24eb71e055 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.cpp @@ -46,13 +46,11 @@ namespace AzToolsFramework } void RemoveLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, - LinkId linkId, UndoSystem::URSequencePoint* undoBatch) + TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, + PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch) { auto linkRemoveUndo = aznew PrefabUndoInstanceLink("Remove Link"); - PrefabDom emptyLinkDom; - linkRemoveUndo->Capture( - targetTemplateId, sourceTemplateId, instanceAlias, emptyLinkDom, linkId); + linkRemoveUndo->Capture(targetTemplateId, sourceTemplateId, instanceAlias, linkPatches, linkId); linkRemoveUndo->SetParent(undoBatch); linkRemoveUndo->Redo(); } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h index 74532b87a2..6429df3b04 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabUndoHelpers.h @@ -25,8 +25,8 @@ namespace AzToolsFramework TemplateId sourceTemplateId, TemplateId targetTemplateId, PrefabDomReference patch, const InstanceAlias& instanceAlias, UndoSystem::URSequencePoint* undoBatch); void RemoveLink( - TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, - LinkId linkId, UndoSystem::URSequencePoint* undoBatch); + TemplateId sourceTemplateId, TemplateId targetTemplateId, const InstanceAlias& instanceAlias, LinkId linkId, + PrefabDomReference linkPatches, UndoSystem::URSequencePoint* undoBatch); } } // namespace Prefab } // namespace AzToolsFramework From d1801bbe47dc4fc827b9d5e0eaf55e271b7cd897 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Fri, 30 Apr 2021 00:39:48 -0700 Subject: [PATCH 014/185] ATOM-14495 POM Height Bias Added parallax "Height Offset" properties to StandardPBR and EnhancedPBR. - Refactored depth pass and shadow pass shaders to use the GetParallaxInput utility. - Updated EnhancedPBR.materialtype to match the parallax controls and functors of StandardPBR.materialtype. - Updated EnhancedPBR's shadow pass shader to apply a ShadowMapDepthBias because I noticed StandardPBR is doing this, so I made them match. - Updated StandardPBR and EnhancedPBR to both use the depth offset property, as well as heightmap clipping debug view. - Note that depth offset is not supported in StandardMultilayerPBR yet, it's hard-coded to 0 for now. - Note that I plan to rename a lot of the "depth" terms to "heightmap" or "displacement" in an upcoming commit. --- .../Materials/Types/EnhancedPBR.materialtype | 100 ++++++-------- .../Types/EnhancedPBR_DepthPass_WithPS.azsl | 26 +--- .../Types/EnhancedPBR_ForwardPass.azsl | 11 +- .../Types/EnhancedPBR_Shadowmap_WithPS.azsl | 28 +--- .../Types/MaterialInputs/ParallaxInput.azsli | 38 ++++-- ...tandardMultilayerPBR_DepthPass_WithPS.azsl | 3 +- .../StandardMultilayerPBR_ForwardPass.azsl | 5 +- ...tandardMultilayerPBR_Shadowmap_WithPS.azsl | 5 +- .../Materials/Types/StandardPBR.materialtype | 28 +++- .../Types/StandardPBR_DepthPass_WithPS.azsl | 30 +---- .../Types/StandardPBR_ForwardPass.azsl | 12 +- .../Types/StandardPBR_ParallaxState.lua | 4 +- .../Types/StandardPBR_Shadowmap_WithPS.azsl | 27 +--- .../Atom/Features/ParallaxMapping.azsli | 123 ++++++++++++++---- .../Types/AutoBrick_ForwardPass.azsl | 19 +-- 15 files changed, 256 insertions(+), 203 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype index cb66a987ae..954e01c592 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR.materialtype @@ -946,19 +946,6 @@ "type": "Bool", "defaultValue": false }, - { - "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", - "type": "Float", - "defaultValue": 0.0, - "min": 0.0, - "softMax": 0.1, - "connection": { - "type": "ShaderInput", - "id": "m_depthFactor" - } - }, { "id": "textureMap", "displayName": "Texture Map", @@ -981,6 +968,32 @@ "id": "m_parallaxUvIndex" } }, + { + "id": "factor", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", + "type": "Float", + "defaultValue": 0.0, + "min": 0.0, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_depthFactor" + } + }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", @@ -1026,6 +1039,17 @@ "type": "ShaderOption", "id": "o_parallax_enablePixelDepthOffset" } + }, + { + "id": "showClipping", + "displayName": "Show Clipping", + "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "type": "Bool", + "defaultValue": false, + "connection": { + "type": "ShaderOption", + "id": "o_parallax_highlightClipping" + } } ], "subsurfaceScattering": [ @@ -1714,22 +1738,6 @@ "shaderOption": "o_emissive_useTexture" } }, - { - // See the comment above for details. - "type": "UseTexture", - "args": { - "textureProperty": "parallax.textureMap", - "dependentProperties": ["parallax.textureMapUv"], - "useTextureProperty": "parallax.enable", - "shaderTags": [ - "ForwardPass", - "ForwardPass_EDS", - "Shadowmap_WithPS", - "DepthPass_WithPS" - ], - "shaderOption": "o_parallax_feature_enabled" - } - }, { // See the comment above for details. "type": "UseTexture", @@ -1813,34 +1821,6 @@ ] } }, - { - // Controls visibility for properties in the editor. - // @param actions - a list of actions that are executed in order. visibility will be set when triggerProperty hits the triggerValue. - // @param affectedProperties - the properties that are affected by actions. - "type": "UpdatePropertyVisibility", - "args": { - "actions": [ - { - "triggerProperty": "parallax.enable", - "triggerValue": true, - "visibility": "Enabled" - }, - { - "triggerProperty": "parallax.enable", - "triggerValue": false, - "visibility": "Hidden" - } - ], - "affectedProperties": [ - "parallax.factor", - "parallax.textureMap", - "parallax.invert", - "parallax.algorithm", - "parallax.quality", - "parallax.pdo" - ] - } - }, { "type": "UpdatePropertyVisibility", "args": { @@ -2076,6 +2056,12 @@ ] } }, + { + "type": "Lua", + "args": { + "file": "StandardPBR_ParallaxState.lua" + } + }, { "type": "Lua", "args": { diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl index 81601860ed..5d6c0fafd8 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl @@ -90,30 +90,12 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, float3(0, 0, 0) }; PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents, 1); - float3 tangent = tangents[MaterialSrg::m_parallaxUvIndex]; - float3 bitangent = bitangents[MaterialSrg::m_parallaxUvIndex]; - float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - - float3 tangentOffset = GetParallaxOffset( MaterialSrg::m_depthFactor, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], - ViewSrg::m_worldPosition.xyz - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrix); - - PixelDepthOffset pdo = CalcPixelDepthOffset(MaterialSrg::m_depthFactor, - tangentOffset, - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrixInverse, - ObjectSrg::GetWorldMatrix(), - ViewSrg::m_viewProjectionMatrix); - OUT.m_depth = pdo.m_depth; + + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index 27d7d7f65c..7d50cbf69b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -115,6 +115,8 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Depth & Parallax ------- depth = IN.m_position.z; + + bool displacementIsClipped = false; // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap) @@ -126,9 +128,9 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); // Apply second part of the offset to the detail UV (see comment above) IN.m_detailUv[MaterialSrg::m_parallaxUvIndex] -= IN.m_uv[MaterialSrg::m_parallaxUvIndex]; @@ -186,6 +188,11 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 baseColor = GetDetailedBaseColorInput( MaterialSrg::m_baseColorMap, MaterialSrg::m_sampler, baseColorUv, o_baseColor_useTexture, MaterialSrg::m_baseColor, MaterialSrg::m_baseColorFactor, o_baseColorTextureBlendMode, MaterialSrg::m_detail_baseColor_texture, MaterialSrg::m_sampler, detailUv, o_detail_baseColor_useTexture, detailLayerBaseColorFactor); + + if(o_parallax_highlightClipping && displacementIsClipped) + { + baseColor = lerp(baseColor, float3(1.0,0.0,1.0), 0.5); + } // ------- Metallic ------- diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl index f1021e354b..e344886c4b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl @@ -98,35 +98,21 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) { + static const float ShadowMapDepthBias = 0.000001; + // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, float3(0, 0, 0) }; PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents, 1); - float3 tangent = tangents[MaterialSrg::m_parallaxUvIndex]; - float3 bitangent = bitangents[MaterialSrg::m_parallaxUvIndex]; - float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float3 tangentOffset = GetParallaxOffset( MaterialSrg::m_depthFactor, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], - dirToCamera, - tangent, - bitangent, - IN.m_normal, - uvMatrix); - - PixelDepthOffset pdo = CalcPixelDepthOffset(MaterialSrg::m_depthFactor, - tangentOffset, - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrixInverse, - ObjectSrg::GetWorldMatrix(), - ViewSrg::m_viewProjectionMatrix); - OUT.m_depth = pdo.m_depth; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); + + OUT.m_depth += ShadowMapDepthBias; } return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli index edee4c3c07..ab601429e8 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/MaterialInputs/ParallaxInput.azsli @@ -24,16 +24,15 @@ #define COMMON_SRG_INPUTS_PARALLAX(prefix) \ Texture2D prefix##m_depthMap; \ float prefix##m_depthFactor; \ +float prefix##m_depthOffset; \ bool prefix##m_depthInverted; #define COMMON_OPTIONS_PARALLAX(prefix) \ option bool prefix##o_useDepthMap; -option bool o_parallax_feature_enabled; - -void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, +void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, - inout float2 uv, inout float3 worldPosition, inout float depth) + inout float2 uv, inout float3 worldPosition, inout float depth, out bool isClipped) { if(o_parallax_feature_enabled) { @@ -49,20 +48,22 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep dirToCamera = ViewSrg::m_worldPosition.xyz - worldPosition; } - float3 tangentOffset = GetParallaxOffset( depthFactor, - uv, - dirToCamera, - tangent, - bitangent, - normal, - uvMatrix); + ParallaxOffset tangentOffset = GetParallaxOffset( depthFactor, + depthOffset, + uv, + dirToCamera, + tangent, + bitangent, + normal, + uvMatrix); - uv += tangentOffset.xy; + uv += tangentOffset.m_offsetTS.xy; + isClipped = tangentOffset.m_isClipped; if(o_parallax_enablePixelDepthOffset) { PixelDepthOffset pdo = CalcPixelDepthOffset(depthFactor, - tangentOffset, + tangentOffset.m_offsetTS, worldPosition, tangent, bitangent, @@ -70,9 +71,20 @@ void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float dep uvMatrixInverse, objectWorldMatrix, ViewSrg::m_viewProjectionMatrix); + depth = pdo.m_depth; + worldPosition = pdo.m_worldPosition; } + } } +void GetParallaxInput(float3 normal, float3 tangent, float3 bitangent, float depthFactor, float depthOffset, + float4x4 objectWorldMatrix, float3x3 uvMatrix, float3x3 uvMatrixInverse, + inout float2 uv, inout float3 worldPosition, inout float depth) +{ + bool isClipped; + GetParallaxInput(normal, tangent, bitangent, depthFactor, depthOffset, objectWorldMatrix, uvMatrix, uvMatrixInverse, uv, worldPosition, depth, isClipped); +} + diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl index 074b9dce26..8e25292e9c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl @@ -126,7 +126,8 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, + float parallaxMainDepthOffset = 0.0; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl index a7338188a2..05a40d0f9d 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -163,8 +163,9 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, + + float parallaxMainDepthOffset = 0.0; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl index 1274e07f7d..0c9c186a11 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl @@ -124,8 +124,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, + + float parallaxMainDepthOffset = 0.0; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype index e071a793a5..a74ceb1783 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR.materialtype @@ -910,8 +910,8 @@ }, { "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -921,6 +921,19 @@ "id": "m_depthFactor" } }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", @@ -966,6 +979,17 @@ "type": "ShaderOption", "id": "o_parallax_enablePixelDepthOffset" } + }, + { + "id": "showClipping", + "displayName": "Show Clipping", + "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "type": "Bool", + "defaultValue": false, + "connection": { + "type": "ShaderOption", + "id": "o_parallax_highlightClipping" + } } ], "subsurfaceScattering": [ diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl index 2e64f5102a..3c04e9b391 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl @@ -91,31 +91,15 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, float3(0, 0, 0) }; PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents, 1); - - float3 tangent = tangents[MaterialSrg::m_parallaxUvIndex]; - float3 bitangent = bitangents[MaterialSrg::m_parallaxUvIndex]; - + float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - - float3 tangentOffset = GetParallaxOffset( MaterialSrg::m_depthFactor, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], - ViewSrg::m_worldPosition.xyz - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrix); - - PixelDepthOffset pdo = CalcPixelDepthOffset(MaterialSrg::m_depthFactor, - tangentOffset, - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrixInverse, - ObjectSrg::GetWorldMatrix(), - ViewSrg::m_viewProjectionMatrix); - OUT.m_depth = pdo.m_depth; + + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } + + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index 4c3da2b7d0..d55b865a27 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -106,15 +106,18 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Depth & Parallax ------- depth = IN.m_position.z; + + bool displacementIsClipped = false; // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap) { + float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); // Adjust directional light shadow coorinates for parallax correction if(o_parallax_enablePixelDepthOffset) @@ -150,6 +153,11 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 sampledColor = GetBaseColorInput(MaterialSrg::m_baseColorMap, MaterialSrg::m_sampler, baseColorUv, MaterialSrg::m_baseColor.rgb, o_baseColor_useTexture); float3 baseColor = BlendBaseColor(sampledColor, MaterialSrg::m_baseColor.rgb, MaterialSrg::m_baseColorFactor, o_baseColorTextureBlendMode, o_baseColor_useTexture); + if(o_parallax_highlightClipping && displacementIsClipped) + { + baseColor = lerp(baseColor, float3(1.0,0.0,1.0), 0.5); + } + // ------- Metallic ------- float metallic = 0; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua index bf1b59616a..0287e1105e 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ParallaxState.lua @@ -41,8 +41,10 @@ function ProcessEditor(context) if(not enable or textureMap == nil) then visibility = MaterialPropertyVisibility_Hidden end - + context:SetMaterialPropertyVisibility("parallax.factor", visibility) + context:SetMaterialPropertyVisibility("parallax.offset", visibility) + context:SetMaterialPropertyVisibility("parallax.showClipping", visibility) context:SetMaterialPropertyVisibility("parallax.invert", visibility) context:SetMaterialPropertyVisibility("parallax.algorithm", visibility) context:SetMaterialPropertyVisibility("parallax.quality", visibility) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl index 4decbcd0df..8f33b4cec6 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl @@ -107,31 +107,14 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float3 bitangents[UvSetCount] = { IN.m_bitangent.xyz, float3(0, 0, 0) }; PrepareGeneratedTangent(IN.m_normal, IN.m_worldPosition, isFrontFace, IN.m_uv, UvSetCount, tangents, bitangents, 1); - float3 tangent = tangents[MaterialSrg::m_parallaxUvIndex]; - float3 bitangent = bitangents[MaterialSrg::m_parallaxUvIndex]; - float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float3 tangentOffset = GetParallaxOffset( MaterialSrg::m_depthFactor, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], - dirToCamera, - tangent, - bitangent, - IN.m_normal, - uvMatrix); - - PixelDepthOffset pdo = CalcPixelDepthOffset(MaterialSrg::m_depthFactor, - tangentOffset, - IN.m_worldPosition, - tangent, - bitangent, - IN.m_normal, - uvMatrixInverse, - ObjectSrg::GetWorldMatrix(), - ViewSrg::m_viewProjectionMatrix); - - OUT.m_depth = pdo.m_depth + ShadowMapDepthBias; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_depthFactor, MaterialSrg::m_depthOffset, + ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); + + OUT.m_depth += ShadowMapDepthBias; } return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli index 8a6b5c479a..8027443f9a 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli @@ -18,6 +18,9 @@ option bool o_parallax_enablePixelDepthOffset; option enum class ParallaxAlgorithm {Basic, Steep, POM, Relief, Contact} o_parallax_algorithm; option enum class ParallaxQuality {Low, Medium, High, Ultra} o_parallax_quality; + +option bool o_parallax_feature_enabled; +option bool o_parallax_highlightClipping; option bool o_parallax_shadow; //! The client shader must define this function. @@ -34,23 +37,49 @@ float SampleDepthOrHeightMap(bool isHeightmap, Texture2D map, sampler mapSampler return abs((isHeightmap * 1.0) - map.SampleGrad(mapSampler, uv, uv_ddx, uv_ddy).r); } +float GetClampedDepth(float minSampledDepth, float2 uv, float2 uv_ddx, float2 uv_ddy) +{ + float sampledDepthValue = GetDepth(uv, uv_ddx, uv_ddy); + sampledDepthValue = max(sampledDepthValue, minSampledDepth); + return sampledDepthValue; +} + +struct ParallaxOffset +{ + float3 m_offsetTS; //!< represents the intersection point relative to the geometry surface, in tangent space. + bool m_isClipped; //!< Indicates whether the result is being clipped by the geometry surface, mainly for debug rendering. Only set when o_parallax_highlightClipping is true. +}; + // dirToCameraTS should be in tangent space and normalized // From Reat-Time Rendering 3rd edition, p.192 -float3 BasicParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraTS) +ParallaxOffset BasicParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraTS) { // the amount to shift float2 delta = dirToCameraTS.xy * GetDepth(uv, ddx_fine(uv), ddy_fine(uv)) * depthFactor; - float3 offset = float3(0,0,0); - offset.xy -= delta; - return offset; + ParallaxOffset result; + + result.m_offsetTS = float3(0,0,0); + result.m_offsetTS.xy -= delta; + result.m_isClipped = false; + return result; } -// dirToCameraTS and dirToLightTS should be in tangent space and normalized -// Adapt from CryEngine shader shadelib.cfi and POM function in https://github.com/a-riccardi/shader-toy +// Performs ray intersection against a surface with a heightmap. +// Adapted from CryEngine shader shadelib.cfi and POM function in https://github.com/a-riccardi/shader-toy // check https://github.com/UPBGE/blender/issues/1009 for more details. -float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraTS, float3 dirToLightTS, int numSteps, inout float parallaxShadowAttenuation) +// @param depthFactor - scales the heightmap in tangent space units (which normally ends up being world units). +// @param depthOffset - offsets the heighmap up or down in tangent space units (which normally ends up being world units). +// @param uv - the UV coordinates on the surface, where the search will begin, used to sample the heightmap. +// @param dirToCameraTS - normalized direction to the camera, in tangent space. +// @param dirToLightTS - normalized direction to a light source, in tangent space, for self-shadowing (if enabled via o_parallax_shadow). +// @param numSteps - the number of steps to take when marching along the ray searching for intersection. +// @param parallaxShadowAttenuation - returns a factor for attenuating a light source, for self-shadowing (if enabled via o_parallax_shadow). +ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, float2 uv, float3 dirToCameraTS, float3 dirToLightTS, int numSteps, inout float parallaxShadowAttenuation) { + ParallaxOffset result; + result.m_isClipped = false; + float dirToCameraZInverse = 1.0 / dirToCameraTS.z; float step = 1.0 / numSteps; float currentStep = 0.0; @@ -60,22 +89,41 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT float2 ddx_uv = ddx_fine(uv); float2 ddy_uv = ddy_fine(uv); - - float currentSample = GetDepth(uv, ddx_uv, ddy_uv); + + // This is the relative position at which we begin searching for intersection. + // It is adjusted according to the depthOffset, raising or lowering the whole surface by depthOffset units. + float3 parallaxOffset = dirToCameraTS.xyz * dirToCameraZInverse * depthOffset; + + // Note that depthOffset can raise the heightmap toward (and potentially above) the surface of the mesh. + // We will clamp the heightmap samples to prevent displacements that lie above the surface, which would cause various + // problems especially when PDO is enabled, like parallax surfaces clipping through foreground geometry, and parallax + // surfaces disappearing at low angles. + float minSampledDepth = depthOffset / depthFactor; + minSampledDepth = clamp(minSampledDepth, 0, 1); + + // Get an initial heightmap sample to start the intersection search, starting at our initial parallaxOffset position. + float currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); float prevSample; - float3 parallaxOffset = float3(0,0,0); + + // Note that when depthOffset > 0, we could actually narrow the search so that instead of going through the entire [0,1] range + // of the heightmap, we could go through the range [minSampledDepth,1]. This would give more accurate results and fewer artifacts + // in case where depthOffset is significant. But for the sake of simplicity we currently search the whole range in all cases. - // find the intersect step + // Do a basic search for the intersect step while(currentSample > currentStep) { currentStep += step; parallaxOffset += delta; + prevSample = currentSample; - currentSample = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } + // Depending on the algorithm, we refine the result of the above search switch(o_parallax_algorithm) { + case ParallaxAlgorithm::Steep: + break; // This algorithm just relies on the course intersection test loop above case ParallaxAlgorithm::POM: { if(currentStep > 0.0) @@ -108,7 +156,7 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT parallaxOffset += reliefDelta * depthSign; currentStep += reliefStep * depthSign; - currentSample = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } } break; @@ -136,7 +184,7 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT parallaxOffset += adjustedDelta; prevSample = currentSample; - currentSample = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } } break; @@ -144,6 +192,23 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT default: break; } + + // Even though we do a bunch of clamping above when calling GetClampedDepth(), there are still cases where the parallax offset + // can be noticeably above the surface and still needs to be clamped here. The main case is when depthFactor==0 and depthOffset>1. + if(parallaxOffset.z > 0.0) + { + result.m_isClipped = o_parallax_highlightClipping; + parallaxOffset = float3(0,0,0); + } + // Extra check to report whether the heightmap is clipped. Inaccuracies in the intersection search make it difficult to rely on + // parallaxOffset.z to determine whether clipping has occurred. The most accurate way to report clipping is to sample the + // heightmap one last time at the final adjusted UV. Since that's expensive, we only do it when the o_parallax_highlightClipping + // option is set. + else if (o_parallax_highlightClipping) + { + float sampledDepthValue = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + result.m_isClipped = sampledDepthValue < minSampledDepth; + } if(o_parallax_shadow && any(dirToLightTS)) { @@ -168,7 +233,7 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT } shadowUV += shadowDelta; - currentSample = GetDepth(shadowUV, ddx_uv, ddy_uv); + currentSample = GetClampedDepth(minSampledDepth, shadowUV, ddx_uv, ddy_uv); currentStep -= step; } @@ -181,12 +246,13 @@ float3 AdvancedParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraT parallaxShadowAttenuation = 1; } } - - return parallaxOffset; + + result.m_offsetTS = parallaxOffset; + return result; } // return offset in tangent space -float3 CalculateParallaxOffset(float depthFactor, float2 uv, float3 dirToCameraTS, float3 dirToLightTS, inout float parallaxShadowAttenuation) +ParallaxOffset CalculateParallaxOffset(float depthFactor, float depthOffset, float2 uv, float3 dirToCameraTS, float3 dirToLightTS, inout float parallaxShadowAttenuation) { if(o_parallax_algorithm == ParallaxAlgorithm::Basic) { @@ -194,27 +260,34 @@ float3 CalculateParallaxOffset(float depthFactor, float2 uv, float3 dirToCameraT } else { - float3 parallaxOffset; + ParallaxOffset parallaxOffset; switch(o_parallax_quality) { case ParallaxQuality::Low: - parallaxOffset = AdvancedParallaxMapping(depthFactor, uv, dirToCameraTS, dirToLightTS, 16, parallaxShadowAttenuation); + parallaxOffset = AdvancedParallaxMapping(depthFactor, depthOffset, uv, dirToCameraTS, dirToLightTS, 16, parallaxShadowAttenuation); break; case ParallaxQuality::Medium: - parallaxOffset = AdvancedParallaxMapping(depthFactor, uv, dirToCameraTS, dirToLightTS, 32, parallaxShadowAttenuation); + parallaxOffset = AdvancedParallaxMapping(depthFactor, depthOffset, uv, dirToCameraTS, dirToLightTS, 32, parallaxShadowAttenuation); break; case ParallaxQuality::High: - parallaxOffset = AdvancedParallaxMapping(depthFactor, uv, dirToCameraTS, dirToLightTS, 64, parallaxShadowAttenuation); + parallaxOffset = AdvancedParallaxMapping(depthFactor, depthOffset, uv, dirToCameraTS, dirToLightTS, 64, parallaxShadowAttenuation); break; case ParallaxQuality::Ultra: - parallaxOffset = AdvancedParallaxMapping(depthFactor, uv, dirToCameraTS, dirToLightTS, 128, parallaxShadowAttenuation); + parallaxOffset = AdvancedParallaxMapping(depthFactor, depthOffset, uv, dirToCameraTS, dirToLightTS, 128, parallaxShadowAttenuation); break; } return parallaxOffset; } } -float3 GetParallaxOffset( float depthFactor, +// Performs ray intersection against a surface with a heightmap, to determine an offset amount required for a parallax effect. +// @param depthFactor - scales the heightmap in tangent space units (which normally ends up being world units). +// @param depthOffset - offsets the heighmap up or down in tangent space units (which normally ends up being world units). +// @param uv - the UV coordinates on the surface, where the search will begin, used to sample the heightmap. +// @param dirToCameraTS - normalized direction to the camera, in tangent space. +// @param dirToLightTS - normalized direction to a light source, in tangent space, for self-shadowing (if enabled via o_parallax_shadow). +ParallaxOffset GetParallaxOffset( float depthFactor, + float depthOffset, float2 uv, float3 dirToCameraWS, float3 tangentWS, @@ -236,7 +309,7 @@ float3 GetParallaxOffset( float depthFactor, float4 dirToCameraTransformed = mul(uv3DTransform, float4(dirToCameraTS, 0.0)); float dummy = 1; - return CalculateParallaxOffset(depthFactor, uv, normalize(dirToCameraTransformed.xyz), float3(0,0,0), dummy); + return CalculateParallaxOffset(depthFactor, depthOffset, uv, normalize(dirToCameraTransformed.xyz), float3(0,0,0), dummy); } struct PixelDepthOffset diff --git a/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl b/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl index 770da549d0..fd11d0d8cd 100644 --- a/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl +++ b/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl @@ -136,15 +136,18 @@ ForwardPassOutput AutoBrick_ForwardPassPS(VSOutput IN) 0,1,0, 0,0,1 }; - float3 tangentOffset = GetParallaxOffset( AutoBrickSrg::m_lineDepth, - IN.m_uv, - ViewSrg::m_worldPosition.xyz - IN.m_worldPosition, - IN.m_tangent, - IN.m_bitangent, - IN.m_normal, - identityUvMatrix); + float depthOffset = 0.0; + + ParallaxOffset tangentOffset = GetParallaxOffset( AutoBrickSrg::m_lineDepth, + depthOffset, + IN.m_uv, + ViewSrg::m_worldPosition.xyz - IN.m_worldPosition, + IN.m_tangent, + IN.m_bitangent, + IN.m_normal, + identityUvMatrix); - IN.m_uv += tangentOffset.xy; + IN.m_uv += tangentOffset.m_offsetTS.xy; float3 baseColor = float3(1,1,1); const float noise = AutoBrickSrg::m_noise.Sample(AutoBrickSrg::m_sampler, IN.m_uv).r; From f01e64a023d709def3e9f584e8b2a74c54f615d3 Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 09:21:21 +0100 Subject: [PATCH 015/185] add missing includes --- Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h | 1 + Code/Sandbox/Editor/CryEditDoc.cpp | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 3491453ff1..4c076b887d 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -21,6 +21,7 @@ #include #include #include +#include namespace AzFramework { diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 00e5a3b85b..ceea0d1c1e 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -30,6 +30,10 @@ #include #include +// Atom +#include +#include + // AzToolsFramework #include #include From 0a4d62eeed4453f50f6caf7e4e998b5f77321879 Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 10:56:40 +0100 Subject: [PATCH 016/185] update cvar description --- Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 6d8c019fec..62b8fb338b 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -20,7 +20,7 @@ AZ_CVAR( float, ed_newCameraSystemDefaultPlaneHeight, 34.0f, nullptr, AZ::ConsoleFunctorFlags::Null, - "What is the default height of the ground plane to do intersection tests against when orbiting"); + "The default height of the ground plane to do intersection tests against when orbiting"); namespace AzFramework { From cee4ca8067f6c69ceb993e4eeec1e5405e203285 Mon Sep 17 00:00:00 2001 From: greerdv Date: Fri, 30 Apr 2021 12:37:12 +0100 Subject: [PATCH 017/185] WIP adding button to transform component to add non-uniform scale component --- .../ToolsComponents/TransformComponent.cpp | 73 +++++++++++++++++++ .../ToolsComponents/TransformComponent.h | 13 ++++ 2 files changed, 86 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index dcced5b705..7d8b802622 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -25,11 +25,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -37,10 +39,29 @@ #include +#pragma optimize("", off) + namespace AzToolsFramework { namespace Components { + void AddNonUniformScaleButton::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class()-> + Version(1); + + if (AZ::EditContext* ptrEdit = serializeContext->GetEditContext()) + { + ptrEdit->Class("AddNonUniformScaleButton", "")-> + UIElement(AZ::Edit::UIHandlers::Button, "", "Add non-uniform scale component")-> + Attribute(AZ::Edit::Attributes::ButtonText, "Add non-uniform scale") + ; + } + } + } + namespace Internal { const AZ::u32 ParentEntityCRC = AZ_CRC("Parent Entity", 0x5b1b276c); @@ -1196,8 +1217,55 @@ namespace AzToolsFramework destinationComponent->SetWorldTM(const_cast(sourceComponent)->GetWorldTM()); } + AZ::Crc32 TransformComponent::OnAddNonUniformScaleButtonPressed() + { + // if there is already a non-uniform scale component, do nothing + if (GetEntity()->FindComponent()) + { + return AZ::Edit::PropertyRefreshLevels::None; + } + + const AZStd::vector entityList = { GetEntityId() }; + const AZ::ComponentTypeList componentsToAdd = { EditorNonUniformScaleComponent::TYPEINFO_Uuid() }; + + AzToolsFramework::EntityCompositionRequests::AddComponentsOutcome outcome; + AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(outcome, + &AzToolsFramework::EntityCompositionRequests::AddComponentsToEntities, entityList, componentsToAdd); + + auto nonUniformScaleComponent = GetEntity()->FindComponent(); + + if (!outcome.IsSuccess() || nonUniformScaleComponent == nullptr) + { + AZ_Warning("Transform component", false, "Failed to add non-uniform scale component."); + return AZ::Edit::PropertyRefreshLevels::None; + } + + AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( + &AzToolsFramework::ToolsApplicationEvents::Bus::Events::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); + + ComponentOrderArray componentOrderArray; + EditorInspectorComponentRequestBus::EventResult(componentOrderArray, GetEntityId(), + &EditorInspectorComponentRequests::GetComponentOrderArray); + + // find the id for the non-uniform scale component and move it immediately after the transform component in the sort order + auto nonUniformScaleComponentIter = AZStd::find(componentOrderArray.begin(), componentOrderArray.end(), nonUniformScaleComponent->GetId()); + auto transformComponentIter = AZStd::find(componentOrderArray.begin(), componentOrderArray.end(), GetId()); + if (nonUniformScaleComponentIter != componentOrderArray.end() && transformComponentIter != componentOrderArray.end()) + { + componentOrderArray.erase(nonUniformScaleComponentIter); + transformComponentIter = AZStd::find(componentOrderArray.begin(), componentOrderArray.end(), GetId()); + componentOrderArray.insert(++transformComponentIter, nonUniformScaleComponent->GetId()); + EditorInspectorComponentRequestBus::Event(GetEntityId(), + &EditorInspectorComponentRequests::SetComponentOrderArray, componentOrderArray); + } + + return AZ::Edit::PropertyRefreshLevels::EntireTree; + } + void TransformComponent::Reflect(AZ::ReflectContext* context) { + AddNonUniformScaleButton::Reflect(context); + // reflect data for script, serialization, editing.. if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) { @@ -1211,6 +1279,7 @@ namespace AzToolsFramework serializeContext->Class()-> Field("Parent Entity", &TransformComponent::m_parentEntityId)-> Field("Transform Data", &TransformComponent::m_editorTransform)-> + Field("AddNonUniformScaleButton", &TransformComponent::m_addNonUniformScaleButton)-> Field("Cached World Transform", &TransformComponent::m_cachedWorldTransform)-> Field("Cached World Transform Parent", &TransformComponent::m_cachedWorldTransformParent)-> Field("Parent Activation Transform Mode", &TransformComponent::m_parentActivationTransformMode)-> @@ -1234,6 +1303,10 @@ namespace AzToolsFramework DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_editorTransform, "Values", "")-> Attribute(AZ::Edit::Attributes::ChangeNotify, &TransformComponent::TransformChanged)-> Attribute(AZ::Edit::Attributes::AutoExpand, true)-> + DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_addNonUniformScaleButton, "", "")-> + Attribute(AZ::Edit::Attributes::AutoExpand, true)-> + Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)-> + Attribute(AZ::Edit::Attributes::ChangeNotify, &TransformComponent::OnAddNonUniformScaleButtonPressed)-> DataElement(AZ::Edit::UIHandlers::ComboBox, &TransformComponent::m_parentActivationTransformMode, "Parent activation", "Configures relative transform behavior when parent activates.")-> EnumAttribute(AZ::TransformConfig::ParentActivationTransformMode::MaintainOriginalRelativeTransform, "Original relative transform")-> diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h index 8327c5f128..dd8c7b8693 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h @@ -23,6 +23,7 @@ #include #include #include +#include #include "EditorComponentBase.h" #include "TransformComponentBus.h" @@ -31,6 +32,15 @@ namespace AzToolsFramework { namespace Components { + class AddNonUniformScaleButton + { + public: + AZ_TYPE_INFO(AddNonUniformScaleButton, "{92ECB8B6-DD25-4FC0-A5EE-4CEBAF51A780}") + static void Reflect(AZ::ReflectContext* context); + private: + void OnAddNonUniformScaleButtonPressed() {}; + }; + /// Manages transform data as separate vector fields for editing purposes. /// The TransformComponent is referenced by other components in the same entity, it is not an asset. class TransformComponent @@ -228,6 +238,8 @@ namespace AzToolsFramework void CheckApplyCachedWorldTransform(const AZ::Transform& parentWorld); + AZ::Crc32 OnAddNonUniformScaleButtonPressed(); + // Drives transform behavior when parent activates. See AZ::TransformConfig::ParentActivationTransformMode for details. AZ::TransformConfig::ParentActivationTransformMode m_parentActivationTransformMode; @@ -259,6 +271,7 @@ namespace AzToolsFramework bool m_localTransformDirty = true; bool m_worldTransformDirty = true; bool m_isStatic = false; + AddNonUniformScaleButton m_addNonUniformScaleButton; // Deprecated AZ::InterpolationMode m_interpolatePosition; From 63526655a270762f8291b600be0fff741629ff55 Mon Sep 17 00:00:00 2001 From: jjjoness <82226755+jjjoness@users.noreply.github.com> Date: Fri, 30 Apr 2021 14:27:55 +0100 Subject: [PATCH 018/185] Fixed asset source tree layout in AssetProcessor --- .../assetprocessor_gui_files.cmake | 4 ++- .../native/ui/JobTreeViewItemDelegate.cpp | 25 +++++++++++++++ .../native/ui/JobTreeViewItemDelegate.h | 32 +++++++++++++++++++ .../AssetProcessor/native/ui/MainWindow.cpp | 2 ++ 4 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.cpp create mode 100644 Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h diff --git a/Code/Tools/AssetProcessor/assetprocessor_gui_files.cmake b/Code/Tools/AssetProcessor/assetprocessor_gui_files.cmake index 79771a9d37..ab7a1e4a9f 100644 --- a/Code/Tools/AssetProcessor/assetprocessor_gui_files.cmake +++ b/Code/Tools/AssetProcessor/assetprocessor_gui_files.cmake @@ -31,7 +31,9 @@ set(FILES native/ui/GoToButton.h native/ui/GoToButton.cpp native/ui/GoToButton.ui - native/ui/MainWindow.h + native/ui/JobTreeViewItemDelegate.h + native/ui/JobTreeViewItemDelegate.cpp + native/ui/MainWindow.ui native/ui/MainWindow.cpp native/ui/MainWindow.ui native/ui/ProductAssetDetailsPanel.h diff --git a/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.cpp b/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.cpp new file mode 100644 index 0000000000..e0da06ad79 --- /dev/null +++ b/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.cpp @@ -0,0 +1,25 @@ +/* +* 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 "JobTreeViewItemDelegate.h" + +namespace AssetProcessor +{ + void JobTreeViewItemDelegate::initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const + { + AzQtComponents::TableViewItemDelegate::initStyleOption(option, index); + + option->features &= ~(QStyleOptionViewItem::WrapText); + } +} + +#include diff --git a/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h b/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h new file mode 100644 index 0000000000..f0e74145ee --- /dev/null +++ b/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h @@ -0,0 +1,32 @@ +#pragma once + +/* +* 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. +* +*/ + +#if !defined(Q_MOC_RUN) +#include +#endif + +namespace AssetProcessor +{ + class JobTreeViewItemDelegate + : public AzQtComponents::TableViewItemDelegate + { + Q_OBJECT + + public: + using AzQtComponents::TableViewItemDelegate::TableViewItemDelegate; + + protected: + void initStyleOption(QStyleOptionViewItem* option, const QModelIndex& index) const override; + }; +} // namespace AssetProcessor diff --git a/Code/Tools/AssetProcessor/native/ui/MainWindow.cpp b/Code/Tools/AssetProcessor/native/ui/MainWindow.cpp index 3a874a464c..79019ab8fc 100644 --- a/Code/Tools/AssetProcessor/native/ui/MainWindow.cpp +++ b/Code/Tools/AssetProcessor/native/ui/MainWindow.cpp @@ -32,6 +32,7 @@ #include #include "native/ui/ui_MainWindow.h" +#include "native/ui/JobTreeViewItemDelegate.h" #include "../utilities/GUIApplicationManager.h" @@ -221,6 +222,7 @@ void MainWindow::Activate() ui->jobTreeView->setModel(m_jobSortFilterProxy); ui->jobTreeView->setSortingEnabled(true); ui->jobTreeView->header()->setDefaultAlignment(Qt::AlignVCenter | Qt::AlignHCenter); + ui->jobTreeView->setItemDelegate(new AssetProcessor::JobTreeViewItemDelegate(ui->jobTreeView)); ui->jobTreeView->setToolTip(tr("Click to view Job Log")); From fb46d11f6ca1aeb5a7f8ed115ef8c18dbff0c02c Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 14:52:14 +0100 Subject: [PATCH 019/185] add missing const --- .../Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 62b8fb338b..851522c701 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -78,7 +78,7 @@ namespace AzFramework return handling; } - Camera Cameras::StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, const float deltaTime) + Camera Cameras::StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, const float scrollDelta, const float deltaTime) { for (int i = 0; i < m_idleCameraInputs.size();) { @@ -87,6 +87,7 @@ namespace AzFramework std::all_of(m_activeCameraInputs.cbegin(), m_activeCameraInputs.cend(), [](const auto& input) { return !input->Exclusive(); }) && (!cameraInput->Exclusive() || (cameraInput->Exclusive() && m_activeCameraInputs.empty())); + if (canBegin) { m_activeCameraInputs.push_back(cameraInput); From a45c348f4fe71044f97982d84da68a18ba8189d8 Mon Sep 17 00:00:00 2001 From: Brian Herrera <19914798+brianherrera@users.noreply.github.com> Date: Fri, 30 Apr 2021 09:53:21 -0700 Subject: [PATCH 020/185] Fix root folder path for canary files This is related to the previous change to move these scripts. Validator will fail to find the canary files when running the script. --- scripts/scrubbing/validator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/scrubbing/validator.py b/scripts/scrubbing/validator.py index e442e443c8..ac7c45554f 100755 --- a/scripts/scrubbing/validator.py +++ b/scripts/scrubbing/validator.py @@ -312,7 +312,7 @@ class Validator(object): # Once we split the repos we will have to worry about multiple root points etc. but that is a problem for future us. # All the packaging safelist stuff goes away once repo is split for platforms this_path = Path(__file__).resolve() - root_folder = this_path.parents[5] + root_folder = this_path.parents[2] relative_folder = os.path.relpath(this_path.parent, root_folder) canary_file = os.path.join(root_folder, 'restricted', platform, relative_folder, platform.lower() + '_canary.txt') try: From db9df91977d589480a7030412dfd8af0138d0537 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Fri, 30 Apr 2021 10:43:27 -0700 Subject: [PATCH 021/185] Give MultiViewportControllerInstances a pointer to their parent controller, to allow state management --- .../Viewport/MultiViewportController.h | 9 +++++++- .../Viewport/MultiViewportController.inl | 6 ++--- .../Editor/LegacyViewportCameraController.cpp | 4 ++-- .../Editor/LegacyViewportCameraController.h | 8 ++++--- .../Editor/ModernViewportCameraController.cpp | 23 ++++++++++++------- .../Editor/ModernViewportCameraController.h | 13 +++++++---- .../Editor/ViewportManipulatorController.cpp | 4 ++-- .../Editor/ViewportManipulatorController.h | 9 ++++---- 8 files changed, 49 insertions(+), 27 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/MultiViewportController.h b/Code/Framework/AzFramework/AzFramework/Viewport/MultiViewportController.h index 2649655f50..ba67208365 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/MultiViewportController.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/MultiViewportController.h @@ -48,21 +48,28 @@ namespace AzFramework }; //! The interface used by MultiViewportController to manage individual instances. + template class MultiViewportControllerInstanceInterface { public: - explicit MultiViewportControllerInstanceInterface(ViewportId viewport) + using ControllerType = TController; + + explicit MultiViewportControllerInstanceInterface(ViewportId viewport, TController* controller) : m_viewportId(viewport) + , m_controller(controller) { } ViewportId GetViewportId() const { return m_viewportId; } + TController* GetController() { return m_controller; } + const TController* GetController() const { return m_controller; } virtual bool HandleInputChannelEvent([[maybe_unused]]const ViewportControllerInputEvent& event) { return false; } virtual void ResetInputChannels() {} virtual void UpdateViewport([[maybe_unused]]const ViewportControllerUpdateEvent& event) {} private: + TController* m_controller; ViewportId m_viewportId; }; } //namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/MultiViewportController.inl b/Code/Framework/AzFramework/AzFramework/Viewport/MultiViewportController.inl index cc59418dac..aa67df4139 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/MultiViewportController.inl +++ b/Code/Framework/AzFramework/AzFramework/Viewport/MultiViewportController.inl @@ -17,8 +17,8 @@ namespace AzFramework MultiViewportController::~MultiViewportController() { static_assert( - AZStd::is_constructible::value, - "TViewportControllerInstance must implement a TViewportControllerInstance(ViewportId) constructor" + AZStd::is_same::value, + "TViewportControllerInstance must implement a TViewportControllerInstance(ViewportId, ViewportController) constructor" ); } @@ -50,7 +50,7 @@ namespace AzFramework template void MultiViewportController::RegisterViewportContext(ViewportId viewport) { - m_instances[viewport] = AZStd::make_unique(viewport); + m_instances[viewport] = AZStd::make_unique(viewport, static_cast(this)); } template diff --git a/Code/Sandbox/Editor/LegacyViewportCameraController.cpp b/Code/Sandbox/Editor/LegacyViewportCameraController.cpp index 518b17f898..56bf986cfc 100644 --- a/Code/Sandbox/Editor/LegacyViewportCameraController.cpp +++ b/Code/Sandbox/Editor/LegacyViewportCameraController.cpp @@ -28,8 +28,8 @@ namespace SandboxEditor { -LegacyViewportCameraControllerInstance::LegacyViewportCameraControllerInstance(AzFramework::ViewportId viewportId) - : AzFramework::MultiViewportControllerInstanceInterface(viewportId) +LegacyViewportCameraControllerInstance::LegacyViewportCameraControllerInstance(AzFramework::ViewportId viewportId, LegacyViewportCameraController* controller) + : AzFramework::MultiViewportControllerInstanceInterface(viewportId, controller) { } diff --git a/Code/Sandbox/Editor/LegacyViewportCameraController.h b/Code/Sandbox/Editor/LegacyViewportCameraController.h index 129a2409da..84a8fe2301 100644 --- a/Code/Sandbox/Editor/LegacyViewportCameraController.h +++ b/Code/Sandbox/Editor/LegacyViewportCameraController.h @@ -28,11 +28,14 @@ namespace AzFramework namespace SandboxEditor { + class LegacyViewportCameraControllerInstance; + using LegacyViewportCameraController = AzFramework::MultiViewportController; + class LegacyViewportCameraControllerInstance final - : public AzFramework::MultiViewportControllerInstanceInterface + : public AzFramework::MultiViewportControllerInstanceInterface { public: - explicit LegacyViewportCameraControllerInstance(AzFramework::ViewportId viewport); + LegacyViewportCameraControllerInstance(AzFramework::ViewportId viewport, LegacyViewportCameraController* controller); bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override; void ResetInputChannels() override; @@ -69,5 +72,4 @@ namespace SandboxEditor bool m_capturingCursor = false; }; - using LegacyViewportCameraController = AzFramework::MultiViewportController; } //namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 80bd9416f7..6fda0381e8 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -37,10 +37,9 @@ namespace SandboxEditor return viewportContext; } - ModernViewportCameraControllerInstance::ModernViewportCameraControllerInstance(const AzFramework::ViewportId viewportId) - : MultiViewportControllerInstanceInterface(viewportId) + AzFramework::Cameras ModernViewportCameraController::GetCameras() const { - // LYN-2315 TODO - move setup out of constructor, pass cameras in + AzFramework::Cameras cameras; auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::InputDeviceMouse::Button::Right); auto firstPersonPanCamera = AZStd::make_shared(AzFramework::LookPan); auto firstPersonTranslateCamera = AZStd::make_shared(AzFramework::LookTranslation); @@ -58,11 +57,19 @@ namespace SandboxEditor orbitCamera->m_orbitCameras.AddCamera(orbitDollyMoveCamera); orbitCamera->m_orbitCameras.AddCamera(orbitPanCamera); - m_cameraSystem.m_cameras.AddCamera(firstPersonRotateCamera); - m_cameraSystem.m_cameras.AddCamera(firstPersonPanCamera); - m_cameraSystem.m_cameras.AddCamera(firstPersonTranslateCamera); - m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); - m_cameraSystem.m_cameras.AddCamera(orbitCamera); + cameras.AddCamera(firstPersonRotateCamera); + cameras.AddCamera(firstPersonPanCamera); + cameras.AddCamera(firstPersonTranslateCamera); + cameras.AddCamera(firstPersonWheelCamera); + cameras.AddCamera(orbitCamera); + return AZStd::move(cameras); + } + + ModernViewportCameraControllerInstance::ModernViewportCameraControllerInstance(const AzFramework::ViewportId viewportId, ModernViewportCameraController* controller) + : MultiViewportControllerInstanceInterface(viewportId, controller) + { + // LYN-2315 TODO - move setup out of constructor, pass cameras in + m_cameraSystem.m_cameras = controller->GetCameras(); if (const auto viewportContext = RetrieveViewportContext(viewportId)) { diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index c65dbc8b8a..9cb2fe45f7 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -17,10 +17,17 @@ namespace SandboxEditor { - class ModernViewportCameraControllerInstance final : public AzFramework::MultiViewportControllerInstanceInterface + class ModernViewportCameraControllerInstance; + class ModernViewportCameraController : public AzFramework::MultiViewportController { public: - explicit ModernViewportCameraControllerInstance(AzFramework::ViewportId viewportId); + AzFramework::Cameras GetCameras() const; + }; + + class ModernViewportCameraControllerInstance final : public AzFramework::MultiViewportControllerInstanceInterface + { + public: + explicit ModernViewportCameraControllerInstance(AzFramework::ViewportId viewportId, ModernViewportCameraController* controller); // MultiViewportControllerInstanceInterface overrides ... bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override; @@ -32,6 +39,4 @@ namespace SandboxEditor AzFramework::SmoothProps m_smoothProps; AzFramework::CameraSystem m_cameraSystem; }; - - using ModernViewportCameraController = AzFramework::MultiViewportController; } // namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.cpp b/Code/Sandbox/Editor/ViewportManipulatorController.cpp index fc376b27d0..0083d295c1 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.cpp +++ b/Code/Sandbox/Editor/ViewportManipulatorController.cpp @@ -27,8 +27,8 @@ static const auto InteractionPriority = AzFramework::ViewportControllerPriority: namespace SandboxEditor { -ViewportManipulatorControllerInstance::ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport) - : AzFramework::MultiViewportControllerInstanceInterface(viewport) +ViewportManipulatorControllerInstance::ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport, ViewportManipulatorController* controller) + : AzFramework::MultiViewportControllerInstanceInterface(viewport, controller) { } diff --git a/Code/Sandbox/Editor/ViewportManipulatorController.h b/Code/Sandbox/Editor/ViewportManipulatorController.h index 03a823fa64..d5540229c4 100644 --- a/Code/Sandbox/Editor/ViewportManipulatorController.h +++ b/Code/Sandbox/Editor/ViewportManipulatorController.h @@ -19,11 +19,14 @@ namespace SandboxEditor { + class ViewportManipulatorControllerInstance; + using ViewportManipulatorController = AzFramework::MultiViewportController; + class ViewportManipulatorControllerInstance final - : public AzFramework::MultiViewportControllerInstanceInterface + : public AzFramework::MultiViewportControllerInstanceInterface { public: - explicit ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport); + explicit ViewportManipulatorControllerInstance(AzFramework::ViewportId viewport, ViewportManipulatorController* controller); bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override; void ResetInputChannels() override; @@ -40,6 +43,4 @@ namespace SandboxEditor AZStd::unordered_map m_pendingDoubleClicks; AZ::ScriptTimePoint m_curTime; }; - - using ViewportManipulatorController = AzFramework::MultiViewportController; } //namespace SandboxEditor From 7e678e15e86c1a1dda6dd9559ec23bfa6b4e2b29 Mon Sep 17 00:00:00 2001 From: Pip Potter Date: Fri, 30 Apr 2021 15:10:57 -0700 Subject: [PATCH 022/185] lyn2919: Update all references to O3DE - Also fix issue where invalid SIDs could be generated - Make default project name consistent across Gems --- Gems/AWSClientAuth/cdk/README.md | 6 +++--- Gems/AWSClientAuth/cdk/app.py | 6 +++--- Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py | 2 +- Gems/AWSClientAuth/cdk/utils/name_utils.py | 6 ++++-- Gems/AWSCore/cdk/README.md | 6 +++--- Gems/AWSCore/cdk/app.py | 6 +++--- Gems/AWSCore/cdk/core/core_stack.py | 2 +- Gems/AWSMetrics/cdk/README.md | 6 +++--- Gems/AWSMetrics/cdk/app.py | 6 +++--- Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py | 4 ++-- 10 files changed, 26 insertions(+), 24 deletions(-) diff --git a/Gems/AWSClientAuth/cdk/README.md b/Gems/AWSClientAuth/cdk/README.md index d604057a65..4fe668cb9d 100644 --- a/Gems/AWSClientAuth/cdk/README.md +++ b/Gems/AWSClientAuth/cdk/README.md @@ -26,9 +26,9 @@ Once the python and pip are set up, you can install the required dependencies. Set variables ``` -set O3D_AWS_DEPLOY_REGION="us-west-2" -set O3D_AWS_DEPLOY_ACCOUNT="" -set O3D_AWS_PROJECT_NAME="AWSIProject" +set O3DE_AWS_DEPLOY_REGION="us-west-2" +set O3DE_AWS_DEPLOY_ACCOUNT="" +set O3DE_AWS_PROJECT_NAME="AWSIProject" If you want to add 3rd party providers fill values in utils/constant.py ``` diff --git a/Gems/AWSClientAuth/cdk/app.py b/Gems/AWSClientAuth/cdk/app.py index d6bba06f39..3b57eea07f 100755 --- a/Gems/AWSClientAuth/cdk/app.py +++ b/Gems/AWSClientAuth/cdk/app.py @@ -16,11 +16,11 @@ from aws_client_auth.client_auth_stack import AWSClientAuthStack import os """Configuration""" -REGION = os.environ.get('O3D_AWS_DEPLOY_REGION', os.environ['CDK_DEFAULT_REGION']) -ACCOUNT = os.environ.get('O3D_AWS_DEPLOY_ACCOUNT', os.environ['CDK_DEFAULT_ACCOUNT']) +REGION = os.environ.get('O3DE_AWS_DEPLOY_REGION', os.environ['CDK_DEFAULT_REGION']) +ACCOUNT = os.environ.get('O3DE_AWS_DEPLOY_ACCOUNT', os.environ['CDK_DEFAULT_ACCOUNT']) # Set the common prefix to group stacks in a project together. -PROJECT_NAME = os.environ.get('O3D_AWS_PROJECT_NAME', f'O3D-AWS-PROJECT').upper() +PROJECT_NAME = os.environ.get('O3DE_AWS_PROJECT_NAME', f'O3DE-AWS-PROJECT').upper() env = core.Environment(account=ACCOUNT, region=REGION) app = core.App() diff --git a/Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py b/Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py index b09269bf3e..d030f8573c 100755 --- a/Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py +++ b/Gems/AWSClientAuth/cdk/cognito/cognito_identity_pool.py @@ -58,7 +58,7 @@ class CognitoIdentityPool: self._identity_pool.add_depends_on(cognito_user_pool.get_user_pool()) self._identity_pool.add_depends_on(cognito_user_pool.get_user_pool_client()) - # Create roles to associate with Cognito Idenity pool + # Create roles to associate with Cognito Identity pool self._auth_role = CognitoIdentityPoolRole(scope, feature_name, project_name, env, self._identity_pool, authenticated=True) self._unauth_role = CognitoIdentityPoolRole(scope, feature_name, project_name, env, diff --git a/Gems/AWSClientAuth/cdk/utils/name_utils.py b/Gems/AWSClientAuth/cdk/utils/name_utils.py index 8c8f6a7e82..bab4cd0389 100755 --- a/Gems/AWSClientAuth/cdk/utils/name_utils.py +++ b/Gems/AWSClientAuth/cdk/utils/name_utils.py @@ -8,7 +8,7 @@ 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. """ - +import re from aws_cdk import core @@ -21,7 +21,9 @@ def format_aws_resource_id(feature_name: str, project_name: str, env: core.Envir def format_aws_resource_sid(feature_name: str, project_name: str, resource_type: str): - return f'{project_name}{feature_name}{resource_type}SId' + sid = f'{project_name}{feature_name}{resource_type}SId' + # Strip out all chars not valid in a sid + return re.sub(r'[^a-zA-Z0-9]', '', sid) def format_aws_resource_authenticated_id(feature_name: str, project_name: str, env: core.Environment, diff --git a/Gems/AWSCore/cdk/README.md b/Gems/AWSCore/cdk/README.md index c49155a422..e4c0335c9c 100644 --- a/Gems/AWSCore/cdk/README.md +++ b/Gems/AWSCore/cdk/README.md @@ -44,9 +44,9 @@ $ pip install -r requirements.txt ## Set environment variables or accept defaults -* O3D_AWS_DEPLOY_REGION*: The region to deploy the stacks into, will default to CDK_DEFAULT_REGION -* O3D_AWS_DEPLOY_ACCOUNT*: The account to deploy stacks into, will default to CDK_DEFAULT_ACCOUNT -* O3D_AWS_PROJECT_NAME*: The name of the O3DE project stacks should be deployed for will default to AWS-PROJECT +* O3DE_AWS_DEPLOY_REGION*: The region to deploy the stacks into, will default to CDK_DEFAULT_REGION +* O3DE_AWS_DEPLOY_ACCOUNT*: The account to deploy stacks into, will default to CDK_DEFAULT_ACCOUNT +* O3DE_AWS_PROJECT_NAME*: The name of the O3DE project stacks should be deployed for will default to AWS-PROJECT See https://docs.aws.amazon.com/cdk/latest/guide/environments.html for more information including how to pass parameters to use for environment variables. diff --git a/Gems/AWSCore/cdk/app.py b/Gems/AWSCore/cdk/app.py index 2e5b196e02..2d8bfa4181 100755 --- a/Gems/AWSCore/cdk/app.py +++ b/Gems/AWSCore/cdk/app.py @@ -22,11 +22,11 @@ from core.aws_core import AWSCore from example.example_resources_stack import ExampleResources """Configuration""" -REGION = os.environ.get('O3D_AWS_DEPLOY_REGION', os.environ.get('CDK_DEFAULT_REGION')) -ACCOUNT = os.environ.get('O3D_AWS_DEPLOY_ACCOUNT', os.environ.get('CDK_DEFAULT_ACCOUNT')) +REGION = os.environ.get('O3DE_AWS_DEPLOY_REGION', os.environ.get('CDK_DEFAULT_REGION')) +ACCOUNT = os.environ.get('O3DE_AWS_DEPLOY_ACCOUNT', os.environ.get('CDK_DEFAULT_ACCOUNT')) # Set the common prefix to group stacks in a project together. -PROJECT_NAME = os.environ.get('O3D_AWS_PROJECT_NAME', f'AWS-PROJECT').upper() +PROJECT_NAME = os.environ.get('O3DE_AWS_PROJECT_NAME', f'O3DE-AWS-PROJECT').upper() # The name of this feature FEATURE_NAME = 'Core' diff --git a/Gems/AWSCore/cdk/core/core_stack.py b/Gems/AWSCore/cdk/core/core_stack.py index 7bf8676987..997d15ef6b 100755 --- a/Gems/AWSCore/cdk/core/core_stack.py +++ b/Gems/AWSCore/cdk/core/core_stack.py @@ -27,7 +27,7 @@ class CoreStack(core.Stack): """ # Resource groups cannot start with 'AWS' or 'aws' so add this prefix - RESOURCE_GROUP_PREFIX = 'O3D' + RESOURCE_GROUP_PREFIX = 'O3DE' def __init__(self, scope: core.Construct, id_: str, project_name: str, feature_name: str, **kwargs) -> None: super().__init__(scope, id_, **kwargs) diff --git a/Gems/AWSMetrics/cdk/README.md b/Gems/AWSMetrics/cdk/README.md index 3f0544a9ce..6f2c774bc3 100644 --- a/Gems/AWSMetrics/cdk/README.md +++ b/Gems/AWSMetrics/cdk/README.md @@ -42,9 +42,9 @@ $ pip install -r requirements.txt ## Set environment variables or accept defaults -* O3D_AWS_DEPLOY_REGION*: The region to deploy the stacks into, will default to CDK_DEFAULT_REGION -* O3D_AWS_DEPLOY_ACCOUNT*: The account to deploy stacks into, will default to CDK_DEFAULT_ACCOUNT -* O3D_AWS_PROJECT_NAME*: The name of the O3DE project stacks should be deployed for will default to AWS-PROJECT +* O3DE_AWS_DEPLOY_REGION*: The region to deploy the stacks into, will default to CDK_DEFAULT_REGION +* O3DE_AWS_DEPLOY_ACCOUNT*: The account to deploy stacks into, will default to CDK_DEFAULT_ACCOUNT +* O3DE_AWS_PROJECT_NAME*: The name of the O3DE project stacks should be deployed for will default to AWS-PROJECT See https://docs.aws.amazon.com/cdk/latest/guide/environments.html for more information including how to pass parameters to use for environment variables. diff --git a/Gems/AWSMetrics/cdk/app.py b/Gems/AWSMetrics/cdk/app.py index 21f8c8f802..469925e533 100755 --- a/Gems/AWSMetrics/cdk/app.py +++ b/Gems/AWSMetrics/cdk/app.py @@ -17,11 +17,11 @@ from aws_metrics.aws_metrics_construct import AWSMetrics import os """Configuration""" -REGION = os.environ.get('O3D_AWS_DEPLOY_REGION', os.environ['CDK_DEFAULT_REGION']) -ACCOUNT = os.environ.get('O3D_AWS_DEPLOY_ACCOUNT', os.environ['CDK_DEFAULT_ACCOUNT']) +REGION = os.environ.get('O3DE_AWS_DEPLOY_REGION', os.environ['CDK_DEFAULT_REGION']) +ACCOUNT = os.environ.get('O3DE_AWS_DEPLOY_ACCOUNT', os.environ['CDK_DEFAULT_ACCOUNT']) # Set the common prefix to group stacks in a project together. Defaults to LY-AWS. -PROJECT_NAME = os.environ.get('O3D_AWS_PROJECT_NAME', f'AWS-PROJECT').upper() +PROJECT_NAME = os.environ.get('O3DE_AWS_PROJECT_NAME', f'O3DE-AWS-PROJECT').upper() # The name of this feature FEATURE_NAME = 'AWSMetrics' diff --git a/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py b/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py index f1a356addf..fe85615d8d 100755 --- a/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py +++ b/Gems/AWSMetrics/cdk/aws_metrics/batch_processing.py @@ -259,7 +259,7 @@ class BatchProcessing: ) policy_statements.append(input_stream_policy_statement) - log_policy_statetement = iam.PolicyStatement( + log_policy_statement = iam.PolicyStatement( actions=[ 'logs:PutLogEvents', ], @@ -268,7 +268,7 @@ class BatchProcessing: self._firehose_delivery_stream_log_group.log_group_arn ] ) - policy_statements.append(log_policy_statetement) + policy_statements.append(log_policy_statement) data_catalog_policy_statement = iam.PolicyStatement( actions=[ From 896738ccff9cd94526fb66bf6ee8968b1accd951 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Fri, 30 Apr 2021 16:08:43 -0700 Subject: [PATCH 023/185] Update Qt 3rdParty packages to fix a minor CMake issue --- cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake | 2 +- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 7ccd118413..620995a85b 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -43,6 +43,6 @@ ly_associate_package(PACKAGE_NAME mikkelsen-1.0.0.4-linux TARGETS mikk ly_associate_package(PACKAGE_NAME googletest-1.8.1-rev4-linux TARGETS googletest PACKAGE_HASH 7b7ad330f369450c316a4c4592d17fbb4c14c731c95bd8f37757203e8c2bbc1b) ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-linux TARGETS GoogleBenchmark PACKAGE_HASH 4038878f337fc7e0274f0230f71851b385b2e0327c495fc3dd3d1c18a807928d) ly_associate_package(PACKAGE_NAME unwind-1.2.1-linux TARGETS unwind PACKAGE_HASH 3453265fb056e25432f611a61546a25f60388e315515ad39007b5925dd054a77) -ly_associate_package(PACKAGE_NAME qt-5.15.2-linux TARGETS Qt PACKAGE_HASH 3857fbb2fc5581cdb71d80a7f9298c83ef06073d4e1ccd86a32b4f88782b6f14) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-linux TARGETS Qt PACKAGE_HASH b7d9932647f4b138b3f0b124d70debd250d2a8a6dca52b04dcbe82c6369d48ca) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-linux TARGETS libsamplerate PACKAGE_HASH 41643c31bc6b7d037f895f89d8d8d6369e906b92eff42b0fe05ee6a100f06261) ly_associate_package(PACKAGE_NAME OpenSSL-1.1.1b-rev2-linux TARGETS OpenSSL PACKAGE_HASH b779426d1e9c5ddf71160d5ae2e639c3b956e0fb5e9fcaf9ce97c4526024e3bc) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index fb6b17fb72..290508b348 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-mac TARGETS Qt PACKAGE_HASH ac248833d65838e4bcef50f30c9ff02ba9464ff64b9ada52de2ad6045d38baec) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev3-mac TARGETS Qt PACKAGE_HASH 29966f22ec253dc9904e88ad48fe6b6a669302b2dc7049f2e2bbd4949e79e595) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-mac TARGETS libsamplerate PACKAGE_HASH b912af40c0ac197af9c43d85004395ba92a6a859a24b7eacd920fed5854a97fe) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index e8c1361b3f..bdc93d9a0e 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -51,7 +51,7 @@ ly_associate_package(PACKAGE_NAME googlebenchmark-1.5.0-rev2-windows TARGETS Goo ly_associate_package(PACKAGE_NAME d3dx12-headers-rev1-windows TARGETS d3dx12 PACKAGE_HASH 088c637159fba4a3e4c0cf08fb4921906fd4cca498939bd239db7c54b5b2f804) ly_associate_package(PACKAGE_NAME pyside2-qt-5.15.1-rev2-windows TARGETS pyside2 PACKAGE_HASH c90f3efcc7c10e79b22a33467855ad861f9dbd2e909df27a5cba9db9fa3edd0f) ly_associate_package(PACKAGE_NAME openimageio-2.1.16.0-rev2-windows TARGETS OpenImageIO PACKAGE_HASH 85a2a6cf35cbc4c967c56ca8074babf0955c5b490c90c6e6fd23c78db99fc282) -ly_associate_package(PACKAGE_NAME qt-5.15.2-windows TARGETS Qt PACKAGE_HASH edaf954c647c99727bfd313dab2959803d2df0873914bb96368c3d8286eed6d9) +ly_associate_package(PACKAGE_NAME qt-5.15.2-rev2-windows TARGETS Qt PACKAGE_HASH 29966f22ec253dc9904e88ad48fe6b6a669302b2dc7049f2e2bbd4949e79e595) ly_associate_package(PACKAGE_NAME libsamplerate-0.2.1-rev2-windows TARGETS libsamplerate PACKAGE_HASH dcf3c11a96f212a52e2c9241abde5c364ee90b0f32fe6eeb6dcdca01d491829f) ly_associate_package(PACKAGE_NAME OpenMesh-8.1-rev1-windows TARGETS OpenMesh PACKAGE_HASH 1c1df639358526c368e790dfce40c45cbdfcfb1c9a041b9d7054a8949d88ee77) ly_associate_package(PACKAGE_NAME civetweb-1.8-rev1-windows TARGETS civetweb PACKAGE_HASH 36d0e58a59bcdb4dd70493fb1b177aa0354c945b06c30416348fd326cf323dd4) From 5eeeaf4346904cbb0308ceb206a12c311528e965 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Sat, 1 May 2021 13:26:54 -0700 Subject: [PATCH 024/185] Fixed several release build compile errors. --- Code/Framework/AzFramework/AzFramework/Scene/Scene.inl | 2 +- .../AzToolsFramework/Prefab/PrefabSystemComponent.cpp | 2 +- .../ImguiAtom/Code/Source/ImguiAtomSystemComponent.cpp | 2 +- Gems/LyShine/Code/Source/LyShineDebug.cpp | 2 ++ 4 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Scene/Scene.inl b/Code/Framework/AzFramework/AzFramework/Scene/Scene.inl index b0c1a18b08..360ab93436 100644 --- a/Code/Framework/AzFramework/AzFramework/Scene/Scene.inl +++ b/Code/Framework/AzFramework/AzFramework/Scene/Scene.inl @@ -51,7 +51,7 @@ namespace AzFramework } template - bool Scene::UnsetSubsystem(const T& system) + bool Scene::UnsetSubsystem([[maybe_unused]] const T& system) { const AZ::TypeId& targetType = azrtti_typeid(); const size_t systemKeysCount = m_systemKeys.size(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp index 3f660bb73b..2570367049 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabSystemComponent.cpp @@ -770,8 +770,8 @@ namespace AzToolsFramework return false; } - Template& sourceTemplate = sourceTemplateReference->get(); #if defined(AZ_ENABLE_TRACING) + Template& sourceTemplate = sourceTemplateReference->get(); Template& targetTemplate = targetTemplateReference->get(); #endif diff --git a/Gems/AtomLyIntegration/ImguiAtom/Code/Source/ImguiAtomSystemComponent.cpp b/Gems/AtomLyIntegration/ImguiAtom/Code/Source/ImguiAtomSystemComponent.cpp index 34e7af688c..8493b78171 100644 --- a/Gems/AtomLyIntegration/ImguiAtom/Code/Source/ImguiAtomSystemComponent.cpp +++ b/Gems/AtomLyIntegration/ImguiAtom/Code/Source/ImguiAtomSystemComponent.cpp @@ -99,7 +99,7 @@ namespace AZ #endif } - void ImguiAtomSystemComponent::OnViewportSizeChanged(AzFramework::WindowSize size) + void ImguiAtomSystemComponent::OnViewportSizeChanged([[maybe_unused]] AzFramework::WindowSize size) { #if defined(IMGUI_ENABLED) ImGui::ImGuiManagerBus::Broadcast([this, size](ImGui::ImGuiManagerBus::Events* imgui) diff --git a/Gems/LyShine/Code/Source/LyShineDebug.cpp b/Gems/LyShine/Code/Source/LyShineDebug.cpp index 5ea01c5c1e..76b4030106 100644 --- a/Gems/LyShine/Code/Source/LyShineDebug.cpp +++ b/Gems/LyShine/Code/Source/LyShineDebug.cpp @@ -115,11 +115,13 @@ static int Create2DTexture(int width, int height, byte* data, ETEX_Format format #endif #endif +#if !defined(_RELEASE) static AZ::Vector2 GetTextureSize(AZ::Data::Instance image) { AZ::RHI::Size size = image->GetDescriptor().m_size; return AZ::Vector2(size.m_width, size.m_height); } +#endif //////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(_RELEASE) From 009ecbc152c9a4c52ada55d821e0576c6824a34e Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Sat, 1 May 2021 15:53:24 -0700 Subject: [PATCH 025/185] 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 026/185] 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 fae33e92354a93b303976dfc300735e22cb10bcb Mon Sep 17 00:00:00 2001 From: guthadam Date: Sun, 2 May 2021 17:08:21 -0500 Subject: [PATCH 027/185] ATOM-15439 Implement basic local socket and server for IPC in material editor and other tools This replaces grid hub usage in the material editor. It allows material editor and other tools to intercommunicate on the local host. This will allow enforcing that there is only one instance of the material editor running. Opening a second instance will forward command line options to the first instance running a local server. https://jira.agscollab.com/browse/ATOM-15439 https://jira.agscollab.com/browse/ATOM-13742 --- .../AtomToolsFramework/Code/CMakeLists.txt | 1 + .../Communication/LocalServer.h | 56 +++++++++ .../Communication/LocalSocket.h | 45 ++++++++ .../Code/Source/Communication/LocalServer.cpp | 108 ++++++++++++++++++ .../Code/Source/Communication/LocalSocket.cpp | 86 ++++++++++++++ .../Code/atomtoolsframework_files.cmake | 4 + .../Tools/MaterialEditor/Code/CMakeLists.txt | 1 + .../Document/MaterialDocumentModule.cpp | 2 - .../MaterialDocumentSystemComponent.cpp | 16 --- .../MaterialDocumentSystemComponent.h | 7 -- .../Code/Source/MaterialEditorApplication.cpp | 81 ++++++++++--- .../Code/Source/MaterialEditorApplication.h | 19 +-- .../Tools/MaterialEditor/Code/Source/main.cpp | 46 ++++---- .../ShaderManagementConsoleDocumentModule.cpp | 2 - ...nagementConsoleDocumentSystemComponent.cpp | 16 --- ...ManagementConsoleDocumentSystemComponent.h | 7 -- .../EditorMaterialSystemComponent.cpp | 35 +----- .../Material/EditorMaterialSystemComponent.h | 9 -- 18 files changed, 406 insertions(+), 135 deletions(-) create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Communication/LocalServer.h create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Communication/LocalSocket.h create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Source/Communication/LocalServer.cpp create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Source/Communication/LocalSocket.cpp diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt b/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt index fb4750ce93..4cd6ad8182 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/CMakeLists.txt @@ -33,6 +33,7 @@ ly_add_target( AZ::AzQtComponents 3rdParty::Qt::Core 3rdParty::Qt::Gui + 3rdParty::Qt::Network 3rdParty::Qt::Widgets 3rdParty::Python Gem::Atom_RPI.Edit diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Communication/LocalServer.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Communication/LocalServer.h new file mode 100644 index 0000000000..4482566113 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Communication/LocalServer.h @@ -0,0 +1,56 @@ +/* + * 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 AtomToolsFramework +{ + //! A named local server that will manage connections and forward recieved data + class LocalServer : public QObject + { + Q_OBJECT + public: + LocalServer(); + ~LocalServer(); + + //! Start a named local server + bool Connect(const QString& serverName); + + //! Stop the server + void Disconnect(); + + //! Get server status + bool IsConnected() const; + + using ReadHandler = AZStd::function; + + //! Set a handler that recieved data will be forwarded to + void SetReadHandler(ReadHandler handler); + + private: + void AddConnection(QLocalSocket* connection); + void ReadFromConnection(QLocalSocket* connection); + void DeleteConnection(QLocalSocket* connection); + + QString m_serverName; + QLocalServer m_server; + ReadHandler m_readHandler; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Communication/LocalSocket.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Communication/LocalSocket.h new file mode 100644 index 0000000000..4eb4d533ed --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Communication/LocalSocket.h @@ -0,0 +1,45 @@ +/* + * 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 +#endif + +namespace AtomToolsFramework +{ + //! LocalSocket enables interprocess communication by establ;ishing a connection and sending data to a LocalServer + class LocalSocket : public QObject + { + Q_OBJECT + public: + LocalSocket(); + ~LocalSocket(); + + //! Attempt to connect to a named local server + bool Connect(const QString& serverName); + + //! Sever connection from server + void Disconnect(); + + //! Get the sockets connection status + bool IsConnected() const; + + //! Send a stream of data to the connected local server + bool Send(const QByteArray& buffer); + + private: + QString m_serverName; + QLocalSocket m_socket; + }; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Communication/LocalServer.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Communication/LocalServer.cpp new file mode 100644 index 0000000000..6f26b00c4f --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Communication/LocalServer.cpp @@ -0,0 +1,108 @@ +/* + * 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 +#include +#include + +namespace AtomToolsFramework +{ + LocalServer::LocalServer() + { + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Creating local server\n"); + m_server.setSocketOptions(QLocalServer::WorldAccessOption); + + QObject::connect(&m_server, &QLocalServer::newConnection, this, [this]() { AddConnection(m_server.nextPendingConnection()); }); + } + + LocalServer::~LocalServer() + { + Disconnect(); + } + + bool LocalServer::Connect(const QString& serverName) + { + Disconnect(); + + m_serverName = serverName; + + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Starting: %s\n", m_serverName.toUtf8().constData()); + if (m_server.listen(m_serverName)) + { + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Started: %s\n", m_serverName.toUtf8().constData()); + return true; + } + + if (m_server.serverError() == QAbstractSocket::AddressInUseError) + { + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Restarting: %s\n", m_serverName.toUtf8().constData()); + Disconnect(); + + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Starting: %s\n", m_serverName.toUtf8().constData()); + if (m_server.listen(m_serverName)) + { + return true; + } + } + + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Starting failed: %s\n", m_serverName.toUtf8().constData()); + Disconnect(); + return false; + } + + void LocalServer::Disconnect() + { + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Disconnecting: %s\n", m_serverName.toUtf8().constData()); + QLocalServer::removeServer(m_serverName); + } + + bool LocalServer::IsConnected() const + { + return m_server.isListening(); + } + + void LocalServer::SetReadHandler(LocalServer::ReadHandler handler) + { + m_readHandler = handler; + } + + void LocalServer::AddConnection(QLocalSocket* connection) + { + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Connection added: %s\n", m_serverName.toUtf8().constData()); + QObject::connect(connection, &QLocalSocket::readyRead, this, [this, connection]() { ReadFromConnection(connection); }); + QObject::connect(connection, &QLocalSocket::disconnected, this, [this, connection]() { DeleteConnection(connection); }); + } + + void LocalServer::ReadFromConnection(QLocalSocket* connection) + { + if (connection) + { + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Data received: %s\n", m_serverName.toUtf8().constData()); + QByteArray buffer = connection->readAll(); + if (m_readHandler) + { + m_readHandler(buffer); + } + } + } + + void LocalServer::DeleteConnection(QLocalSocket* connection) + { + if (connection) + { + AZ_TracePrintf("AtomToolsFramework::LocalServer", "Deleting connection: %s\n", m_serverName.toUtf8().constData()); + connection->deleteLater(); + } + } +} // namespace AtomToolsFramework + +#include diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Communication/LocalSocket.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Communication/LocalSocket.cpp new file mode 100644 index 0000000000..020998bf1a --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Communication/LocalSocket.cpp @@ -0,0 +1,86 @@ +/* + * 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 +#include +#include +#include + +namespace AtomToolsFramework +{ + LocalSocket::LocalSocket() + { + } + + LocalSocket::~LocalSocket() + { + Disconnect(); + } + + bool LocalSocket::Connect(const QString& serverName) + { + Disconnect(); + + m_serverName = serverName; + + AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Connecting to: %s\n", m_serverName.toUtf8().constData()); + m_socket.connectToServer(m_serverName); + + if (IsConnected()) + { + AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Waiting for connection to: %s\n", m_serverName.toUtf8().constData()); + if (m_socket.waitForConnected()) + { + AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Connected to: %s\n", m_serverName.toUtf8().constData()); + return true; + } + } + + AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Connecting failed: %s\n", m_serverName.toUtf8().constData()); + Disconnect(); + return false; + } + + void LocalSocket::Disconnect() + { + if (IsConnected()) + { + AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Disconnecting from: %s\n", m_serverName.toUtf8().constData()); + m_socket.disconnectFromServer(); + m_socket.waitForDisconnected(); + + AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Closing socket\n"); + m_socket.close(); + } + } + + bool LocalSocket::IsConnected() const + { + return m_socket.isOpen(); + } + + bool LocalSocket::Send(const QByteArray& buffer) + { + if (IsConnected()) + { + AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Sending data to: %s\n", m_serverName.toUtf8().constData()); + m_socket.write(buffer); + + AZ_TracePrintf("AtomToolsFramework::LocalSocket", "Waiting for write to: %s\n", m_serverName.toUtf8().constData()); + m_socket.waitForBytesWritten(); + return true; + } + return false; + } +} // namespace AtomToolsFramework + +#include diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index e8539711f7..d8ceccc724 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -10,6 +10,8 @@ # set(FILES + Include/AtomToolsFramework/Communication/LocalServer.h + Include/AtomToolsFramework/Communication/LocalSocket.h Include/AtomToolsFramework/Debug/TraceRecorder.h Include/AtomToolsFramework/DynamicProperty/DynamicProperty.h Include/AtomToolsFramework/DynamicProperty/DynamicPropertyGroup.h @@ -22,6 +24,8 @@ set(FILES Include/AtomToolsFramework/Util/MaterialPropertyUtil.h Include/AtomToolsFramework/Util/Util.h Include/AtomToolsFramework/Viewport/RenderViewportWidget.h + Source/Communication/LocalServer.cpp + Source/Communication/LocalSocket.cpp Source/Debug/TraceRecorder.cpp Source/DynamicProperty/DynamicProperty.cpp Source/DynamicProperty/DynamicPropertyGroup.cpp diff --git a/Gems/Atom/Tools/MaterialEditor/Code/CMakeLists.txt b/Gems/Atom/Tools/MaterialEditor/Code/CMakeLists.txt index 40d6a8f30a..134f605200 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/CMakeLists.txt +++ b/Gems/Atom/Tools/MaterialEditor/Code/CMakeLists.txt @@ -93,6 +93,7 @@ ly_add_target( ly_add_target( NAME MaterialEditor EXECUTABLE NAMESPACE Gem + AUTOMOC FILES_CMAKE materialeditor_files.cmake Source/Platform/${PAL_PLATFORM_NAME}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentModule.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentModule.cpp index a7aecf0b1f..b1a795b9f9 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentModule.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentModule.cpp @@ -13,7 +13,6 @@ #include #include -#include #include #include @@ -32,7 +31,6 @@ namespace MaterialEditor return AZ::ComponentTypeList{ azrtti_typeid(), azrtti_typeid(), - azrtti_typeid(), }; } } diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp index 2fd1aac211..dbb1d18e49 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.cpp @@ -109,7 +109,6 @@ namespace MaterialEditor void MaterialDocumentSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { - required.push_back(AZ_CRC("TargetManagerService", 0x6d5708bc)); required.push_back(AZ_CRC("AssetProcessorToolsConnection", 0x734669bc)); required.push_back(AZ_CRC("AssetDatabaseService", 0x3abf5601)); required.push_back(AZ_CRC("PropertyManagerService", 0x63a3d7ad)); @@ -135,31 +134,16 @@ namespace MaterialEditor m_documentMap.clear(); MaterialDocumentSystemRequestBus::Handler::BusConnect(); MaterialDocumentNotificationBus::Handler::BusConnect(); - AzFramework::TmMsgBus::Handler::BusConnect(AZ_CRC("OpenInMaterialEditor", 0x9f92aac8)); } void MaterialDocumentSystemComponent::Deactivate() { AZ::TickBus::Handler::BusDisconnect(); - AzFramework::TmMsgBus::Handler::BusDisconnect(); MaterialDocumentNotificationBus::Handler::BusDisconnect(); MaterialDocumentSystemRequestBus::Handler::BusDisconnect(); m_documentMap.clear(); } - void MaterialDocumentSystemComponent::OnReceivedMsg(AzFramework::TmMsgPtr msg) - { - if (msg->GetId() == AZ_CRC("OpenInMaterialEditor", 0x9f92aac8)) - { - const char* documentPath = reinterpret_cast(msg->GetCustomBlob()); - MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::OpenDocument, documentPath); - } - else - { - AZ_Assert(false, "We received a message of an unrecognized class type!"); - } - } - AZ::Uuid MaterialDocumentSystemComponent::CreateDocument() { auto document = AZStd::make_unique(); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h index b6c541421d..4b0ee424a7 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocumentSystemComponent.h @@ -16,7 +16,6 @@ #include #include #include -#include #include #include @@ -35,7 +34,6 @@ namespace MaterialEditor class MaterialDocumentSystemComponent : public AZ::Component , private AZ::TickBus::Handler - , private AzFramework::TmMsgBus::Handler , private MaterialDocumentNotificationBus::Handler , private MaterialDocumentSystemRequestBus::Handler { @@ -72,11 +70,6 @@ namespace MaterialEditor void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; //////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // AzFramework::TmMsgBus::Handler overrides... - void OnReceivedMsg(AzFramework::TmMsgPtr msg) override; - ////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////// // MaterialDocumentSystemRequestBus::Handler overrides... AZ::Uuid CreateDocument() override; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 66be1c23bb..ea82210814 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -90,6 +90,14 @@ namespace MaterialEditor }); } + MaterialEditorApplication::~MaterialEditorApplication() + { + AzToolsFramework::EditorPythonConsoleNotificationBus::Handler::BusDisconnect(); + AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusDisconnect(); + MaterialEditorWindowNotificationBus::Handler::BusDisconnect(); + AZ::Debug::TraceMessageBus::Handler::BusDisconnect(); + } + void MaterialEditorApplication::CreateReflectionManager() { Application::CreateReflectionManager(); @@ -299,12 +307,12 @@ namespace MaterialEditor return false; } - void MaterialEditorApplication::ProcessCommandLine() + void MaterialEditorApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) { const AZStd::string timeoputSwitchName = "timeout"; - if (m_commandLine.HasSwitch(timeoputSwitchName)) + if (commandLine.HasSwitch(timeoputSwitchName)) { - const AZStd::string& timeoutValue = m_commandLine.GetSwitchValue(timeoputSwitchName, 0); + const AZStd::string& timeoutValue = commandLine.GetSwitchValue(timeoputSwitchName, 0); const uint32_t timeoutInMs = atoi(timeoutValue.c_str()); AZ_Printf("MaterialEditor", "Timeout scheduled, shutting down in %u ms", timeoutInMs); QTimer::singleShot(timeoutInMs, [this] { @@ -315,10 +323,10 @@ namespace MaterialEditor // Process command line options for running one or more python scripts on startup const AZStd::string runPythonScriptSwitchName = "runpython"; - size_t runPythonScriptCount = m_commandLine.GetNumSwitchValues(runPythonScriptSwitchName); + size_t runPythonScriptCount = commandLine.GetNumSwitchValues(runPythonScriptSwitchName); for (size_t runPythonScriptIndex = 0; runPythonScriptIndex < runPythonScriptCount; ++runPythonScriptIndex) { - const AZStd::string runPythonScriptPath = m_commandLine.GetSwitchValue(runPythonScriptSwitchName, runPythonScriptIndex); + const AZStd::string runPythonScriptPath = commandLine.GetSwitchValue(runPythonScriptSwitchName, runPythonScriptIndex); AZStd::vector runPythonArgs; AZ_Printf("MaterialEditor", "Launching script: %s", runPythonScriptPath.c_str()); @@ -329,17 +337,17 @@ namespace MaterialEditor } // Process command line options for opening one or more material documents on startup - size_t openDocumentCount = m_commandLine.GetNumMiscValues(); + size_t openDocumentCount = commandLine.GetNumMiscValues(); for (size_t openDocumentIndex = 0; openDocumentIndex < openDocumentCount; ++openDocumentIndex) { - const AZStd::string openDocumentPath = m_commandLine.GetMiscValue(openDocumentIndex); + const AZStd::string openDocumentPath = commandLine.GetMiscValue(openDocumentIndex); AZ_Printf("MaterialEditor", "Opening document: %s", openDocumentPath.c_str()); MaterialDocumentSystemRequestBus::Broadcast(&MaterialDocumentSystemRequestBus::Events::OpenDocument, openDocumentPath); } const AZStd::string exitAfterCommandsSwitchName = "exitaftercommands"; - if (m_commandLine.HasSwitch(exitAfterCommandsSwitchName)) + if (commandLine.HasSwitch(exitAfterCommandsSwitchName)) { ExitMainLoop(); } @@ -409,9 +417,50 @@ namespace MaterialEditor bool MaterialEditorApplication::LaunchDiscoveryService() { - const QStringList arguments = { "-fail_silently" }; + // Determine if this is the first launch of the tool by attempting to connect to a running server + if (m_socket.Connect(QApplication::applicationName())) + { + // If the server was located, the application is already running. + // Forward commandline options to other application instance. + QByteArray buffer; + buffer.append("ProcessCommandLine:"); + for (int argi = 1; argi < m_argC; ++argi) + { + buffer.append(QString(m_argV[argi]).append("\n").toUtf8()); + } + m_socket.Send(buffer); + m_socket.Disconnect(); + return false; + } - return AtomToolsFramework::LaunchTool("GridHub", AZ_TRAIT_MATERIALEDITOR_EXT, arguments); + // Setup server to handle basic commands + m_server.SetReadHandler([this](const QByteArray& buffer) { + // Handle commmand line params from connected socket + if (buffer.startsWith("ProcessCommandLine:")) + { + // Remove header and parse commands + AZStd::string params(buffer.data(), buffer.size()); + params = params.substr(strlen("ProcessCommandLine:")); + + AZStd::vector tokens; + AZ::StringFunc::Tokenize(params, tokens, "\n"); + + if (!tokens.empty()) + { + AZ::CommandLine commandLine; + commandLine.Parse(tokens); + ProcessCommandLine(commandLine); + } + } + }); + + // Launch local server + if (!m_server.Connect(QApplication::applicationName())) + { + return false; + } + + return true; } void MaterialEditorApplication::StartInternal() @@ -421,10 +470,14 @@ namespace MaterialEditor return; } - //[GFX TODO][ATOM-415] Try to factor out some of this stuff with AtomSampleViewerApplication - WriteStartupLog(); + if (!LaunchDiscoveryService()) + { + ExitMainLoop(); + return; + } + AzToolsFramework::AssetDatabase::AssetDatabaseRequestsBus::Handler::BusConnect(); AzToolsFramework::AssetBrowser::AssetDatabaseLocationNotificationBus::Broadcast(&AzToolsFramework::AssetBrowser::AssetDatabaseLocationNotifications::OnDatabaseInitialized); @@ -434,8 +487,6 @@ namespace MaterialEditor LoadSettings(); - LaunchDiscoveryService(); - MaterialEditorWindowNotificationBus::Handler::BusConnect(); MaterialEditor::MaterialEditorWindowFactoryRequestBus::Broadcast( @@ -450,7 +501,7 @@ namespace MaterialEditor } // Delay execution of commands and scripts post initialization - QTimer::singleShot(0, [this]() { ProcessCommandLine(); }); + QTimer::singleShot(0, [this]() { ProcessCommandLine(m_commandLine); }); } bool MaterialEditorApplication::GetAssetDatabaseLocation(AZStd::string& result) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h index 63ccbf3cec..2c66fd7c16 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.h @@ -12,22 +12,20 @@ #pragma once - +#include +#include +#include +#include #include #include -#include #include - +#include #include #include #include - #include #include -#include -#include - #include #include @@ -51,7 +49,7 @@ namespace MaterialEditor using Base = AzFramework::Application; MaterialEditorApplication(int* argc, char*** argv); - virtual ~MaterialEditorApplication() = default; + virtual ~MaterialEditorApplication(); ////////////////////////////////////////////////////////////////////////// // AzFramework::Application @@ -110,7 +108,7 @@ namespace MaterialEditor void CompileCriticalAssets(); - void ProcessCommandLine(); + void ProcessCommandLine(const AZ::CommandLine& commandLine); void WriteStartupLog(); void LoadSettings(); @@ -138,5 +136,8 @@ namespace MaterialEditor bool m_activatedLocalUserSettings = false; QTimer m_timer; + + AtomToolsFramework::LocalSocket m_socket; + AtomToolsFramework::LocalServer m_server; }; } // namespace MaterialEditor diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp index 92d76c4373..1d420a35d3 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp @@ -1,30 +1,31 @@ /* -* 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. -* -*/ + * 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. + * + */ + +#if !defined(Q_MOC_RUN) +#include #include #include -#include -#include #include -#include #include -#include -#include +#include +#include #include +#include +#include -#include #include - -#include +#include +#endif int main(int argc, char** argv) { @@ -45,15 +46,16 @@ int main(int argc, char** argv) AzQtComponents::Utilities::HandleDpiAwareness(AzQtComponents::Utilities::SystemDpiAware); MaterialEditor::MaterialEditorApplication app(&argc, &argv); + + auto globalEventFilter = new AzQtComponents::GlobalEventFilter(&app); + app.installEventFilter(globalEventFilter); + AZ::IO::FixedMaxPath engineRootPath; if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) { settingsRegistry->Get(engineRootPath.Native(), AZ::SettingsRegistryMergeUtils::FilePathKey_EngineRootFolder); } - auto globalEventFilter = new AzQtComponents::GlobalEventFilter(&app); - app.installEventFilter(globalEventFilter); - AzQtComponents::StyleManager styleManager(&app); styleManager.initialize(&app, engineRootPath); @@ -62,3 +64,5 @@ int main(int argc, char** argv) app.Stop(); return 0; } + +#include "main.moc" diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentModule.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentModule.cpp index f2fd70c0e6..50b2cbb53a 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentModule.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentModule.cpp @@ -13,7 +13,6 @@ #include #include -#include #include #include @@ -32,7 +31,6 @@ namespace ShaderManagementConsole return AZ::ComponentTypeList{ azrtti_typeid(), azrtti_typeid(), - azrtti_typeid(), }; } } diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp index f0d72c61c3..31dabe2bac 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.cpp @@ -105,7 +105,6 @@ namespace ShaderManagementConsole void ShaderManagementConsoleDocumentSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) { - required.push_back(AZ_CRC("TargetManagerService", 0x6d5708bc)); required.push_back(AZ_CRC("AssetProcessorToolsConnection", 0x734669bc)); required.push_back(AZ_CRC("AssetDatabaseService", 0x3abf5601)); required.push_back(AZ_CRC("PropertyManagerService", 0x63a3d7ad)); @@ -130,13 +129,11 @@ namespace ShaderManagementConsole { m_documentMap.clear(); ShaderManagementConsoleDocumentSystemRequestBus::Handler::BusConnect(); - AzFramework::TmMsgBus::Handler::BusConnect(AZ_CRC("OpenInShaderManagementConsole", 0x9f92aac8)); } void ShaderManagementConsoleDocumentSystemComponent::Deactivate() { ShaderManagementConsoleDocumentSystemRequestBus::Handler::BusDisconnect(); - AzFramework::TmMsgBus::Handler::BusDisconnect(); m_documentMap.clear(); } @@ -159,19 +156,6 @@ namespace ShaderManagementConsole return m_documentMap.erase(documentId) != 0; } - void ShaderManagementConsoleDocumentSystemComponent::OnReceivedMsg(AzFramework::TmMsgPtr msg) - { - if (msg->GetId() == AZ_CRC("OpenInShaderManagementConsole", 0x9f92aac8)) - { - const char* documentPath = reinterpret_cast(msg->GetCustomBlob()); - ShaderManagementConsoleDocumentSystemRequestBus::Broadcast(&ShaderManagementConsoleDocumentSystemRequestBus::Events::OpenDocument, documentPath); - } - else - { - AZ_Assert(false, "We received a message of an unrecognized class type!"); - } - } - AZ::Uuid ShaderManagementConsoleDocumentSystemComponent::OpenDocument(AZStd::string_view path) { return OpenDocumentImpl(path, true); diff --git a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.h b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.h index 60c205aa72..2bd7306b8b 100644 --- a/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.h +++ b/Gems/Atom/Tools/ShaderManagementConsole/Code/Source/Document/ShaderManagementConsoleDocumentSystemComponent.h @@ -14,7 +14,6 @@ #include #include -#include #include #include @@ -30,7 +29,6 @@ namespace ShaderManagementConsole //! ShaderManagementConsoleDocumentSystemComponent is the central component of the Shader Management Console Core gem class ShaderManagementConsoleDocumentSystemComponent : public AZ::Component - , private AzFramework::TmMsgBus::Handler , private ShaderManagementConsoleDocumentSystemRequestBus::Handler { public: @@ -55,11 +53,6 @@ namespace ShaderManagementConsole void Deactivate() override; //////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // TmMsgBus::Handler overrides... - void OnReceivedMsg(AzFramework::TmMsgPtr msg) override; - ////////////////////////////////////////////////////////////////////////// - //////////////////////////////////////////////////////////////////////// // ShaderManagementConsoleDocumentSystemRequestBus::Handler overrides... AZ::Uuid CreateDocument() override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index 94dfb39419..c32f124456 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -93,7 +93,6 @@ namespace AZ void EditorMaterialSystemComponent::Activate() { - AzFramework::TargetManagerClient::Bus::Handler::BusConnect(); EditorMaterialSystemComponentRequestBus::Handler::BusConnect(); AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusConnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect(); @@ -105,7 +104,6 @@ namespace AZ void EditorMaterialSystemComponent::Deactivate() { - AzFramework::TargetManagerClient::Bus::Handler::BusDisconnect(); EditorMaterialSystemComponentRequestBus::Handler::BusDisconnect(); AzFramework::ApplicationLifecycleEvents::Bus::Handler::BusDisconnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusDisconnect(); @@ -123,36 +121,11 @@ namespace AZ void EditorMaterialSystemComponent::OpenInMaterialEditor(const AZStd::string& sourcePath) { - if (m_materialEditorTarget.IsValid()) - { - AzFramework::TmMsg openDocumentMsg(AZ_CRC("OpenInMaterialEditor", 0x9f92aac8)); - openDocumentMsg.AddCustomBlob(sourcePath.c_str(), sourcePath.size() + 1); - AzFramework::TargetManager::Bus::Broadcast(&AzFramework::TargetManager::SendTmMessage, m_materialEditorTarget, openDocumentMsg); - } - else - { - AZ_TracePrintf("MaterialComponent", "Launching Material Editor"); - - QStringList arguments; - arguments.append(sourcePath.c_str()); - AtomToolsFramework::LaunchTool("MaterialEditor", ".exe", arguments); - } - } - - void EditorMaterialSystemComponent::TargetJoinedNetwork(AzFramework::TargetInfo info) - { - if (AZ::StringFunc::Equal(info.GetDisplayName(), "MaterialEditor")) - { - m_materialEditorTarget = info; - } - } + AZ_TracePrintf("MaterialComponent", "Launching Material Editor"); - void EditorMaterialSystemComponent::TargetLeftNetwork(AzFramework::TargetInfo info) - { - if (AZ::StringFunc::Equal(info.GetDisplayName(), "MaterialEditor")) - { - m_materialEditorTarget = {}; - } + QStringList arguments; + arguments.append(sourcePath.c_str()); + AtomToolsFramework::LaunchTool("MaterialEditor", ".exe", arguments); } void EditorMaterialSystemComponent::OnApplicationAboutToStop() diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h index 09ad1c1b9c..cb1aac9163 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.h @@ -14,7 +14,6 @@ #include #include -#include #include #include @@ -32,7 +31,6 @@ namespace AZ class EditorMaterialSystemComponent : public AZ::Component , private EditorMaterialSystemComponentRequestBus::Handler - , private AzFramework::TargetManagerClient::Bus::Handler , private AzFramework::ApplicationLifecycleEvents::Bus::Handler , public AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler , public AzToolsFramework::EditorMenuNotificationBus::Handler @@ -57,10 +55,6 @@ namespace AZ //! EditorMaterialSystemComponentRequestBus::Handler overrides... void OpenInMaterialEditor(const AZStd::string& sourcePath) override; - //! AzFramework::TargetManagerClient::Bus::Handler overrides... - void TargetJoinedNetwork(AzFramework::TargetInfo info) override; - void TargetLeftNetwork(AzFramework::TargetInfo info) override; - // AzFramework::ApplicationLifecycleEvents overrides... void OnApplicationAboutToStop() override; @@ -74,9 +68,6 @@ namespace AZ void SetupThumbnails(); void TeardownThumbnails(); - // Material Editor target for interprocess communication with MaterialEditor - AzFramework::TargetInfo m_materialEditorTarget; - QAction* m_openMaterialEditorAction = nullptr; AZStd::unique_ptr m_materialBrowserInteractions; From f58f8805be0b4a233e94c1be05926e05d5176fc1 Mon Sep 17 00:00:00 2001 From: guthadam Date: Sun, 2 May 2021 17:16:07 -0500 Subject: [PATCH 028/185] Removed bad test code --- Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp index 1d420a35d3..8c55adba46 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/main.cpp @@ -64,5 +64,3 @@ int main(int argc, char** argv) app.Stop(); return 0; } - -#include "main.moc" From 9d0f9e9e3aab5ff58e696b9581f0ab14eb8b8f15 Mon Sep 17 00:00:00 2001 From: guthadam Date: Mon, 3 May 2021 00:13:45 -0500 Subject: [PATCH 029/185] ATOM-14065 fix problems with material editor details group property descriptions Moved the code that automatically appended a script variable name to a property description out of the dynamic property class and into the material property conversion utility functions. Added proper descriptions for the material type and parent material placeholder properties https://jira.agscollab.com/browse/ATOM-14065 --- .../Code/Source/DynamicProperty/DynamicProperty.cpp | 5 +---- .../Code/Source/Util/MaterialPropertyUtil.cpp | 7 +++++++ .../Code/Source/Document/MaterialDocument.cpp | 8 ++++++-- .../Source/Material/EditorMaterialComponentInspector.cpp | 5 ++++- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/DynamicProperty/DynamicProperty.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/DynamicProperty/DynamicProperty.cpp index 5784355498..8afd1dc8d5 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/DynamicProperty/DynamicProperty.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/DynamicProperty/DynamicProperty.cpp @@ -211,10 +211,7 @@ namespace AtomToolsFramework AZStd::string DynamicProperty::GetDescription() const { - return AZStd::string::format("%s%s(Script Name = '%s')", - m_config.m_description.c_str(), - m_config.m_description.empty() ? "" : "\n", - m_config.m_id.GetCStr()); + return m_config.m_description; } AZ::Crc32 DynamicProperty::GetVisibility() const diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/MaterialPropertyUtil.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/MaterialPropertyUtil.cpp index 952e241143..41a627bef7 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/MaterialPropertyUtil.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Util/MaterialPropertyUtil.cpp @@ -91,6 +91,13 @@ namespace AtomToolsFramework propertyConfig.m_vectorLabels = propertyDefinition.m_vectorLabels; propertyConfig.m_visible = propertyDefinition.m_visibility != AZ::RPI::MaterialPropertyVisibility::Hidden; propertyConfig.m_readOnly = propertyDefinition.m_visibility == AZ::RPI::MaterialPropertyVisibility::Disabled; + + // Update the description for material properties to include script name assuming id is set beforehand + propertyConfig.m_description = AZStd::string::format( + "%s%s(Script Name = '%s')", + propertyConfig.m_description.c_str(), + propertyConfig.m_description.empty() ? "" : "\n", + propertyConfig.m_id.GetCStr()); } void ConvertToPropertyConfig(AtomToolsFramework::DynamicPropertyConfig& propertyConfig, const AZ::RPI::MaterialPropertyDynamicMetadata& propertyMetaData) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp index 3919684864..288530a4e4 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Document/MaterialDocument.cpp @@ -762,6 +762,8 @@ namespace MaterialEditor // in the hierarchy are applied m_materialTypeSourceData.EnumerateProperties([this, &parentPropertyValues](const AZStd::string& groupNameId, const AZStd::string& propertyNameId, const auto& propertyDefinition) { AtomToolsFramework::DynamicPropertyConfig propertyConfig; + + // Assign id before conversion so it can be used in dynamic description propertyConfig.m_id = MaterialPropertyId(groupNameId, propertyNameId).GetCStr(); const auto& propertyIndex = m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); @@ -792,7 +794,8 @@ namespace MaterialEditor propertyConfig.m_nameId = "materialType"; propertyConfig.m_displayName = "Material Type"; propertyConfig.m_groupName = "Details"; - propertyConfig.m_description = propertyConfig.m_displayName; + propertyConfig.m_description = "The material type defines the layout, properties, default values, shader connections, and other " + "data needed to create and edit a derived material."; propertyConfig.m_defaultValue = AZStd::any(materialTypeAsset); propertyConfig.m_originalValue = propertyConfig.m_defaultValue; propertyConfig.m_parentValue = propertyConfig.m_defaultValue; @@ -806,7 +809,8 @@ namespace MaterialEditor propertyConfig.m_nameId = "parentMaterial"; propertyConfig.m_displayName = "Parent Material"; propertyConfig.m_groupName = "Details"; - propertyConfig.m_description = propertyConfig.m_displayName; + propertyConfig.m_description = + "The parent material provides an initial configuration whose properties are inherited and overriden by a derived material."; propertyConfig.m_defaultValue = AZStd::any(parentMaterialAsset); propertyConfig.m_originalValue = propertyConfig.m_defaultValue; propertyConfig.m_parentValue = propertyConfig.m_defaultValue; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp index f7915bbff4..03533e142f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentInspector.cpp @@ -245,9 +245,12 @@ namespace AZ for (const auto& propertyDefinition : propertyListItr->second) { AtomToolsFramework::DynamicPropertyConfig propertyConfig; - AtomToolsFramework::ConvertToPropertyConfig(propertyConfig, propertyDefinition); + // Assign id before conversion so it can be used in dynamic description propertyConfig.m_id = AZ::RPI::MaterialPropertyId(groupNameId, propertyDefinition.m_nameId).GetFullName(); + + AtomToolsFramework::ConvertToPropertyConfig(propertyConfig, propertyDefinition); + propertyConfig.m_groupName = groupDisplayName; const auto& propertyIndex = m_editData.m_materialAsset->GetMaterialPropertiesLayout()->FindPropertyIndex(propertyConfig.m_id); propertyConfig.m_showThumbnail = true; From 3cbbcf1877f8966eae117362bdde338783758a15 Mon Sep 17 00:00:00 2001 From: balibhan Date: Mon, 3 May 2021 12:10:33 +0530 Subject: [PATCH 030/185] 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 | 227 +- .../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, 11023 insertions(+), 23 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 +from base import TestAutomationBase -sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') +TEST_DIRECTORY = os.path.dirname(__file__) -from base import TestAutomationBase @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 fe88ae12b05b4676bda91811011826e7c1f70326 Mon Sep 17 00:00:00 2001 From: jackalbe <23512001+jackalbe@users.noreply.github.com> Date: Mon, 3 May 2021 10:02:04 -0500 Subject: [PATCH 031/185] {LYN-3365} GraphObjectProxy is now hidden from Script Canvas (#478) * GraphObjectProxy is now hidden from Script Canvas * the IGraphObject has been added to the BC Jira: https://jira.agscollab.com/browse/LYN-3365 Tests: manual testing the node type is not in the SC editor --- Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp index 4de42eb944..f2fda63ec4 100644 --- a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp @@ -25,9 +25,12 @@ namespace AZ AZ::BehaviorContext* behaviorContext = azrtti_cast(context); if (behaviorContext) { + behaviorContext->Class(); + behaviorContext->Class() ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Module, "scene.graph") + ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) ->Method("CastWithTypeName", &GraphObjectProxy::CastWithTypeName) ->Method("Invoke", &GraphObjectProxy::Invoke) ; From b5cf0f59fc0ab9bf411e26b229f1dddd90356655 Mon Sep 17 00:00:00 2001 From: jjjoness <82226755+jjjoness@users.noreply.github.com> Date: Mon, 3 May 2021 16:57:58 +0100 Subject: [PATCH 032/185] Moved the pragma below the copyright message. --- Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h b/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h index f0e74145ee..fbe45a3f75 100644 --- a/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h +++ b/Code/Tools/AssetProcessor/native/ui/JobTreeViewItemDelegate.h @@ -1,5 +1,3 @@ -#pragma once - /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. @@ -12,6 +10,8 @@ * */ +#pragma once + #if !defined(Q_MOC_RUN) #include #endif From 071a64280469e8292d6f8267ae14f1bb9d30b62f Mon Sep 17 00:00:00 2001 From: chcurran Date: Mon, 3 May 2021 09:37:23 -0700 Subject: [PATCH 033/185] Auto gen updates fixing property declarations. --- .../AutoGen/ScriptCanvasNodeable_Source.jinja | 24 +++++++------------ .../Framework/ScriptCanvasTestFixture.h | 2 ++ .../Nodeables/NodeableTestingLibrary.cpp | 4 +++- ...rReferenceExample.ScriptCanvasNodeable.xml | 22 +++++++++++++---- .../ValuePointerReferenceExample.cpp | 10 ++++++++ .../Nodeables/ValuePointerReferenceExample.h | 6 +++++ 6 files changed, 48 insertions(+), 20 deletions(-) diff --git a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja index 27498a2aec..71681ed73b 100644 --- a/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja +++ b/Gems/ScriptCanvas/Code/Include/ScriptCanvas/AutoGen/ScriptCanvasNodeable_Source.jinja @@ -186,21 +186,16 @@ void {{attribute_QualifiedName}}::Reflect(AZ::ReflectContext* context) ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) {% if attribute_Category is defined %} - ->Attribute(AZ::Edit::Attributes::Category, "{{ attribute_Category }}") + ->Attribute(AZ::Edit::Attributes::Category, "{{ attribute_Category }}") {%- endif %} - {% if attribute_Icon is defined %} - ->Attribute(AZ::Edit::Attributes::Icon, "{{ attribute_Icon }}") + ->Attribute(AZ::Edit::Attributes::Icon, "{{ attribute_Icon }}") {%- endif %} - {% if attribute_Deprecated is defined %} - ->Attribute(AZ::Edit::Attributes::Deprecated, "{{ attribute_Deprecated }}") + ->Attribute(AZ::Edit::Attributes::Deprecated, "{{ attribute_Deprecated }}") {%- endif %} - {% set uihandler = 'AZ::Edit::UIHandlers::Default' %} - -{% for Property in Class.iter('Property') %} -{% for item in Property.iter('PropertyData') %} +{% for item in Class.iter('Property') %} {% if item.attrib['UIHandler'] is defined %} {% set uihandler = item.attrib['UIHandler'] %} {% endif %} @@ -208,12 +203,11 @@ void {{attribute_QualifiedName}}::Reflect(AZ::ReflectContext* context) {% if item.attrib['Description'] is defined %} {% set description = item.attrib['Description'] %} {% endif %} - // {{ item.attrib['Name'] }} - ->DataElement({{ uihandler }}, &{{ attribute_Name }}::{{ Property.attrib['Name'] }}, "{{ item.attrib['Name'] }}", "{{ description }}") -{% for EditAttribute in Property.iter('EditAttribute') %} - ->Attribute({{ EditAttribute.attrib['Key'] }}, {{ EditAttribute.attrib['Value'] }}) -{% endfor %} -{% endfor %} + // {{ item.attrib['Name'] }} + ->DataElement({{ uihandler }}, &{{ attribute_Name }}::{{ item.attrib['Name'] }}, "{{ item.attrib['Name'] }}", "{{ description }}") +{% for EditAttribute in item.iter('EditAttribute') %} + ->Attribute({{ EditAttribute.attrib['Key'] }}, {{ EditAttribute.attrib['Value'] }}) +{% endfor %} {% endfor %} ; } diff --git a/Gems/ScriptCanvasTesting/Code/Source/Framework/ScriptCanvasTestFixture.h b/Gems/ScriptCanvasTesting/Code/Source/Framework/ScriptCanvasTestFixture.h index cb3c9cdccb..7f026edf58 100644 --- a/Gems/ScriptCanvasTesting/Code/Source/Framework/ScriptCanvasTestFixture.h +++ b/Gems/ScriptCanvasTesting/Code/Source/Framework/ScriptCanvasTestFixture.h @@ -122,6 +122,8 @@ namespace ScriptCanvasTests ::Nodes::InputTypeExampleNode::Reflect(m_behaviorContext); ::Nodes::BranchInputTypeExampleNode::Reflect(m_serializeContext); ::Nodes::BranchInputTypeExampleNode::Reflect(m_behaviorContext); + ::Nodes::PropertyExampleNode::Reflect(m_serializeContext); + ::Nodes::PropertyExampleNode::Reflect(m_behaviorContext); TestNodeableObject::Reflect(m_serializeContext); TestNodeableObject::Reflect(m_behaviorContext); diff --git a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/NodeableTestingLibrary.cpp b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/NodeableTestingLibrary.cpp index 6a9f7fd6c3..5d8574fb10 100644 --- a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/NodeableTestingLibrary.cpp +++ b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/NodeableTestingLibrary.cpp @@ -44,6 +44,7 @@ namespace ScriptCanvasTesting ScriptCanvas::Library::AddNodeToRegistry(nodeRegistry); ScriptCanvas::Library::AddNodeToRegistry(nodeRegistry); ScriptCanvas::Library::AddNodeToRegistry(nodeRegistry); + ScriptCanvas::Library::AddNodeToRegistry(nodeRegistry); } AZStd::vector NodeableTestingLibrary::GetComponentDescriptors() @@ -53,7 +54,8 @@ namespace ScriptCanvasTesting ::Nodes::BranchMethodSharedDataSlotExampleNode::CreateDescriptor(), ::Nodes::ReturnTypeExampleNode::CreateDescriptor(), ::Nodes::InputTypeExampleNode::CreateDescriptor(), - ::Nodes::BranchInputTypeExampleNode::CreateDescriptor() + ::Nodes::BranchInputTypeExampleNode::CreateDescriptor(), + ::Nodes::PropertyExampleNode::CreateDescriptor() }); } } diff --git a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.ScriptCanvasNodeable.xml b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.ScriptCanvasNodeable.xml index efebbefce7..0be3c8c81a 100644 --- a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.ScriptCanvasNodeable.xml +++ b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.ScriptCanvasNodeable.xml @@ -32,7 +32,7 @@ - + @@ -51,13 +51,27 @@ Namespace="None" Description="Example of passing as input by value, pointer and reference."> - + - + - + + + + + + + diff --git a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp index 154508d5f1..35fa1136f9 100644 --- a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp +++ b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp @@ -66,5 +66,15 @@ namespace ScriptCanvasTesting { input.clear(); } + + void PropertyExample::In() + { + for (auto& num : Numbers) + { + AZ_TracePrintf("ScriptCanvas", "%f", num); + } + + AZ_TracePrintf("ScriptCanvas", "Slang: %s", Slang.c_str()); + } } } diff --git a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.h b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.h index 7bcfed8bb4..8c19e1916c 100644 --- a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.h +++ b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.h @@ -48,5 +48,11 @@ namespace ScriptCanvasTesting { SCRIPTCANVAS_NODE(InputTypeExample); }; + + class PropertyExample + : public ScriptCanvas::Nodeable + { + SCRIPTCANVAS_NODE(PropertyExample); + }; } } From 3c7ca7269310959112c27da90a0af6ff698e15e7 Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Mon, 3 May 2021 18:45:35 +0200 Subject: [PATCH 034/185] [LYN-3269] EMotionFX Editor save changed files prompts users to save files to the cache (#469) * The asset source filename is now displayed instead of the product filename. * Fixed a stylesheet issue with screen scaling on 4K monitors for the saved changed files window. * Cleaned up surrounding code. --- .../Source/SaveChangedFilesManager.cpp | 41 ++++++++++++------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.cpp index 4824821a61..28a4fb9c92 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/SaveChangedFilesManager.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include #include @@ -398,33 +399,49 @@ namespace EMStudio const size_t numDirtyFiles = dirtyFileNames.size(); mTableWidget->setRowCount(static_cast(numDirtyFiles)); - AZStd::string extension, typeString, filenameText, path, filenameOnly; for (size_t i = 0; i < numDirtyFiles; ++i) { SaveDirtyFilesCallback::ObjectPointer object = mObjects[i]; + QString labelText; if (dirtyFileNames[i].empty()) { - filenameText = ""; + labelText = ""; } else { - AzFramework::StringFunc::Path::GetFullPath(dirtyFileNames[i].c_str(), path); - AzFramework::StringFunc::Path::GetFullFileName(dirtyFileNames[i].c_str(), filenameOnly); - - filenameText = AZStd::string::format("%s%s", path.c_str(), filenameOnly.c_str()); + const AZStd::string& productFilename = dirtyFileNames[i]; + + // Get the asset source name from the product filename. + bool sourceAssetFound = false; + AZStd::string sourceAssetFilename; + AzToolsFramework::AssetSystemRequestBus::BroadcastResult(sourceAssetFound, + &AzToolsFramework::AssetSystemRequestBus::Events::GetFullSourcePathFromRelativeProductPath, + productFilename, + sourceAssetFilename); + + const AZStd::string usedFilename = sourceAssetFound ? sourceAssetFilename : dirtyFileNames[i]; + + // Separate the path from the filename, so that we can display the filename in bold. + AZStd::string fullPath; + AzFramework::StringFunc::Path::GetFullPath(usedFilename.c_str(), fullPath); + AzFramework::StringFunc::RelativePath::Normalize(fullPath); // Add trailing slash in case it is missing + AZStd::string fullFilename; + AzFramework::StringFunc::Path::GetFullFileName(usedFilename.c_str(), fullFilename); + labelText = QString("%1%2").arg(fullPath.c_str(), fullFilename.c_str()); } // create the checkbox QCheckBox* checkbox = new QCheckBox(""); - checkbox->setStyleSheet("background: transparent; padding-left: 3px; max-width: 13px;"); + checkbox->setStyleSheet("background: transparent;"); checkbox->setChecked(true); // create the filename table item QLabel* filenameLabel = new QLabel(); - filenameLabel->setToolTip(filenameText.c_str()); - filenameLabel->setText(filenameText.c_str()); + filenameLabel->setToolTip(labelText); + filenameLabel->setText(labelText); + QString typeString; if (object.mMotion) { typeString = "Motion"; @@ -445,12 +462,8 @@ namespace EMStudio { typeString = "Workspace"; } - else - { - typeString = ""; - } - QTableWidgetItem* itemType = new QTableWidgetItem(typeString.c_str()); + QTableWidgetItem* itemType = new QTableWidgetItem(typeString); const int row = static_cast(i); itemType->setData(Qt::UserRole, row); From 893d4208c0ef1f529f71c64794c85e98841e759b Mon Sep 17 00:00:00 2001 From: Benjamin Jillich <43751992+amzn-jillich@users.noreply.github.com> Date: Mon, 3 May 2021 18:48:30 +0200 Subject: [PATCH 035/185] [LYN-3312] EMotionFX: Multi-threading dual quaternion software skinning / Moving the mouse while having many characters on screen makes the editor unusably slow (#506) Multi-threaded software skinning by splitting the mesh up into batches of 10,000 vertices, which results in 27 jobs being spawned and executed using a character asset from a customer having 262,676 vertices and a speed improvement of 12x on a 32-core machine. Single-threaded: 11,61 ms Multi-threaded (27 jobs): 0,96 ms * Created a SkinRange() function that can skin a part of the vertices. * The actual skinning is now using the job system to split up the skinning into several pieces and executes them in parallel. * Ported the bone info array to AzCore. * Fixed some issues with the mesh based bounds update in the actor instance. --- .../Code/EMotionFX/Source/ActorInstance.cpp | 8 +- .../EMotionFX/Source/DualQuatSkinDeformer.cpp | 306 +++++++----------- .../EMotionFX/Source/DualQuatSkinDeformer.h | 42 ++- .../Components/EditorActorComponent.cpp | 6 +- 4 files changed, 153 insertions(+), 209 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp index cfacdf9f09..ec1b00bda4 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/ActorInstance.cpp @@ -360,7 +360,7 @@ namespace EMotionFX ApplyMorphSetup(); UpdateSkinningMatrices(); UpdateAttachments(); - } + } // update the bounds when needed if (GetBoundsUpdateEnabled() && mBoundsUpdateType != BOUNDS_MESH_BASED) @@ -418,7 +418,8 @@ namespace EMotionFX } // Update the bounds when we are set to use mesh based bounds. - if (GetBoundsUpdateEnabled() == BOUNDS_MESH_BASED) + if (GetBoundsUpdateEnabled() && + GetBoundsUpdateType() == BOUNDS_MESH_BASED) { mBoundsUpdatePassedTime += timePassedInSeconds; if (mBoundsUpdatePassedTime >= mBoundsUpdateFrequency) @@ -449,7 +450,8 @@ namespace EMotionFX } // Update the bounds when we are set to use mesh based bounds. - if (GetBoundsUpdateEnabled() == BOUNDS_MESH_BASED) + if (GetBoundsUpdateEnabled() && + GetBoundsUpdateType() == BOUNDS_MESH_BASED) { mBoundsUpdatePassedTime += timePassedInSeconds; if (mBoundsUpdatePassedTime >= mBoundsUpdateFrequency) diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp index 73cbad195a..27cf34961f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.cpp @@ -10,7 +10,8 @@ * */ -// include the required headers +#include +#include #include "EMotionFXConfig.h" #include "DualQuatSkinDeformer.h" #include "Mesh.h" @@ -23,138 +24,143 @@ #include #include - namespace EMotionFX { AZ_CLASS_ALLOCATOR_IMPL(DualQuatSkinDeformer, DeformerAllocator, 0) - // constructor DualQuatSkinDeformer::DualQuatSkinDeformer(Mesh* mesh) : MeshDeformer(mesh) { - mBones.SetMemoryCategory(EMFX_MEMCATEGORY_GEOMETRY_DEFORMERS); } - - // destructor DualQuatSkinDeformer::~DualQuatSkinDeformer() { - mBones.Clear(); } + AZ::Outcome DualQuatSkinDeformer::FindLocalBoneIndex(uint32 nodeIndex) const + { + const size_t numBones = m_bones.size(); + for (size_t i = 0; i < numBones; ++i) + { + if (m_bones[i].mNodeNr == nodeIndex) + { + return AZ::Success(i); + } + } + + return AZ::Failure(); + } - // creation DualQuatSkinDeformer* DualQuatSkinDeformer::Create(Mesh* mesh) { return aznew DualQuatSkinDeformer(mesh); } - - // get the type id uint32 DualQuatSkinDeformer::GetType() const { return TYPE_ID; } - - // get the subtype id uint32 DualQuatSkinDeformer::GetSubType() const { return SUBTYPE_ID; } - - // clone this class MeshDeformer* DualQuatSkinDeformer::Clone(Mesh* mesh) { // create the new cloned deformer DualQuatSkinDeformer* result = aznew DualQuatSkinDeformer(mesh); // copy the bone info (for precalc/optimization reasons) - result->mBones = mBones; + result->m_bones = m_bones; // return the result return result; } - // the main method where all calculations are done - void DualQuatSkinDeformer::Update(ActorInstance* actorInstance, Node* node, float timeDelta) + void DualQuatSkinDeformer::Update(ActorInstance* actorInstance, [[maybe_unused]] Node* node, [[maybe_unused]] float timeDelta) { - AZ_UNUSED(node); - MCORE_UNUSED(timeDelta); - const Actor* actor = actorInstance->GetActor(); const Pose* pose = actorInstance->GetTransformData()->GetCurrentPose(); + const uint32 numVertices = mMesh->GetNumVertices(); - AZ::Vector3 newPos, newNormal, newTangent, newBitangent; - AZ::Vector3 vtxPos, normal, tangent, bitangent; - AZ::Vector3* positions = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_POSITIONS)); - AZ::Vector3* normals = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_NORMALS)); - AZ::Vector4* tangents = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_TANGENTS)); - AZ::Vector3* bitangents = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_BITANGENTS)); - AZ::u32* orgVerts = static_cast(mMesh->FindVertexData(Mesh::ATTRIB_ORGVTXNUMBERS)); - - // precalc the skinning matrices - const uint32 numBones = mBones.GetLength(); - for (uint32 i = 0; i < numBones; i++) + // pre-calculate the skinning matrices + for (BoneInfo& boneInfo : m_bones) { - const uint32 nodeIndex = mBones[i].mNodeNr; - Transform skinTransform = actor->GetInverseBindPoseTransform(nodeIndex); - skinTransform.Multiply(pose->GetModelSpaceTransform(nodeIndex)); - mBones[i].mDualQuat.FromRotationTranslation(skinTransform.mRotation, skinTransform.mPosition); + const uint32 nodeIndex = boneInfo.mNodeNr; + const Transform skinTransform = actor->GetInverseBindPoseTransform(nodeIndex) * pose->GetModelSpaceTransform(nodeIndex); + boneInfo.mDualQuat.FromRotationTranslation(skinTransform.mRotation, skinTransform.mPosition); } - // find the skinning layer - SkinningInfoVertexAttributeLayer* layer = (SkinningInfoVertexAttributeLayer*)mMesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); - MCORE_ASSERT(layer); + AZ::JobCompletion jobCompletion; + + // Split up the skinned vertices into batches. + const AZ::u32 numBatches = aznumeric_caster(ceilf(aznumeric_cast(numVertices) / aznumeric_cast(s_numVerticesPerBatch))); + for (AZ::u32 batchIndex = 0; batchIndex < numBatches; ++batchIndex) + { + const AZ::u32 startVertex = batchIndex * s_numVerticesPerBatch; + const AZ::u32 endVertex = AZStd::min(startVertex + s_numVerticesPerBatch, numVertices); + + // Create a job for every batch and skin them simultaneously. + AZ::JobContext* jobContext = nullptr; + AZ::Job* job = AZ::CreateJobFunction([this, startVertex, endVertex]() + { + SkinRange(mMesh, startVertex, endVertex, m_bones); + }, /*isAutoDelete=*/true, jobContext); + + job->SetDependent(&jobCompletion); + job->Start(); + } + + jobCompletion.StartAndWaitForCompletion(); + } + + void DualQuatSkinDeformer::SkinRange(Mesh* mesh, AZ::u32 startVertex, AZ::u32 endVertex, const AZStd::vector& boneInfos) + { + SkinningInfoVertexAttributeLayer* layer = (SkinningInfoVertexAttributeLayer*)mesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); + AZ_Assert(layer, "Cannot find skinning layer."); + + AZ::Vector3 newTangent; + AZ::Vector3 vtxPos, normal, tangent, bitangent; + AZ::u32 orgVertex; + float weight; + + AZ::Vector3* positions = static_cast(mesh->FindVertexData(Mesh::ATTRIB_POSITIONS)); + AZ::Vector3* normals = static_cast(mesh->FindVertexData(Mesh::ATTRIB_NORMALS)); + AZ::Vector4* tangents = static_cast(mesh->FindVertexData(Mesh::ATTRIB_TANGENTS)); + AZ::Vector3* bitangents = static_cast(mesh->FindVertexData(Mesh::ATTRIB_BITANGENTS)); + AZ::u32* orgVerts = static_cast(mesh->FindVertexData(Mesh::ATTRIB_ORGVTXNUMBERS)); // if there are tangents and bitangents to skin if (tangents && bitangents) { - const uint32 numVertices = mMesh->GetNumVertices(); - uint32 v = 0; - uint32 orgVertex; - - SkinInfluence* influence; - BoneInfo* boneInfo; - float weight; - for (v = 0; v < numVertices; ++v) + for (AZ::u32 v = startVertex; v < endVertex; ++v) { - // get the original vertex number - orgVertex = *(orgVerts++); - - // reset the skinned position - newPos = AZ::Vector3::CreateZero(); - newNormal = AZ::Vector3::CreateZero(); - newTangent = AZ::Vector3::CreateZero(); - newBitangent = AZ::Vector3::CreateZero(); - - const float tangentW = tangents->GetW(); - vtxPos.Set (positions->GetX(), positions->GetY(), positions->GetZ()); - normal.Set (normals->GetX(), normals->GetY(), normals->GetZ()); - tangent.Set (tangents->GetX(), tangents->GetY(), tangents->GetZ()); - bitangent.Set(bitangents->GetX(), bitangents->GetY(), bitangents->GetZ()); + orgVertex = orgVerts[v]; + vtxPos = positions[v]; + normal = normals[v]; + const float tangentW = tangents[v].GetW(); + tangent.Set(tangents[v].GetX(), tangents[v].GetY(), tangents[v].GetZ()); + bitangent = bitangents[v]; // process the skin influences for this vertex const size_t numInfluences = layer->GetNumInfluences(orgVertex); if (numInfluences > 0) { // get the pivot quat, used for the dot product check - const MCore::DualQuaternion& pivotQuat = mBones[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; + const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; // our skinning dual quaternion MCore::DualQuaternion skinQuat(AZ::Quaternion(0, 0, 0, 0), AZ::Quaternion(0, 0, 0, 0)); for (size_t i = 0; i < numInfluences; ++i) { - // get the influence - influence = layer->GetInfluence(orgVertex, i); - boneInfo = &mBones[ influence->GetBoneNr() ]; - weight = influence->GetWeight(); + SkinInfluence* influence = layer->GetInfluence(orgVertex, i); + weight = influence->GetWeight(); // check if we need to invert the dual quat - MCore::DualQuaternion& influenceQuat = mBones[ influence->GetBoneNr() ].mDualQuat; + MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].mDualQuat; if (influenceQuat.mReal.Dot(pivotQuat.mReal) < 0.0f) { influenceQuat *= -1.0f; @@ -168,74 +174,50 @@ namespace EMotionFX skinQuat.Normalize(); // perform skinning - newPos = skinQuat.TransformPoint(vtxPos); - newNormal = skinQuat.TransformVector(normal); - newTangent = skinQuat.TransformVector(tangent); - newBitangent = skinQuat.TransformVector(bitangent); + positions[v] = skinQuat.TransformPoint(vtxPos); + normals[v] = skinQuat.TransformVector(normal); + newTangent = skinQuat.TransformVector(tangent); + tangents[v].Set(newTangent.GetX(), newTangent.GetY(), newTangent.GetZ(), tangentW); + bitangents[v] = skinQuat.TransformVector(bitangent); } else { - // perform the skinning - newPos = vtxPos; - newNormal = normal; - newTangent = tangent; - newBitangent = bitangent; + // no skinning influences, just copy the values + positions[v] = vtxPos; + normals[v] = normal; + newTangent = tangent; + tangents[v].Set(newTangent.GetX(), newTangent.GetY(), newTangent.GetZ(), tangentW); + bitangents[v] = bitangent; } - - // output the skinned values - positions->Set (newPos.GetX(), newPos.GetY(), newPos.GetZ()); - positions++; - normals->Set (newNormal.GetX(), newNormal.GetY(), newNormal.GetZ()); - normals++; - tangents->Set (newTangent.GetX(), newTangent.GetY(), newTangent.GetZ(), tangentW); - tangents++; - bitangents->Set (newBitangent.GetX(), newBitangent.GetY(), newBitangent.GetZ()); - bitangents++; } } else if (tangents && !bitangents) // tangents but no bitangents { - const uint32 numVertices = mMesh->GetNumVertices(); - uint32 v = 0; - uint32 orgVertex; - - SkinInfluence* influence; - BoneInfo* boneInfo; - float weight; - for (v = 0; v < numVertices; ++v) + for (AZ::u32 v = startVertex; v < endVertex; ++v) { - // get the original vertex number - orgVertex = *(orgVerts++); - - // reset the skinned position - newPos = AZ::Vector3::CreateZero(); - newNormal = AZ::Vector3::CreateZero(); - newTangent = AZ::Vector3::CreateZero(); - - const float tangentW = tangents->GetW(); - vtxPos.Set (positions->GetX(), positions->GetY(), positions->GetZ()); - normal.Set (normals->GetX(), normals->GetY(), normals->GetZ()); - tangent.Set (tangents->GetX(), tangents->GetY(), tangents->GetZ()); + orgVertex = orgVerts[v]; + vtxPos = positions[v]; + normal = normals[v]; + const float tangentW = tangents[v].GetW(); + tangent.Set(tangents[v].GetX(), tangents[v].GetY(), tangents[v].GetZ()); // process the skin influences for this vertex const size_t numInfluences = layer->GetNumInfluences(orgVertex); if (numInfluences > 0) { // get the pivot quat, used for the dot product check - const MCore::DualQuaternion& pivotQuat = mBones[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; + const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; // our skinning dual quaternion MCore::DualQuaternion skinQuat(AZ::Quaternion(0, 0, 0, 0), AZ::Quaternion(0, 0, 0, 0)); for (size_t i = 0; i < numInfluences; ++i) { - // get the influence - influence = layer->GetInfluence(orgVertex, i); - boneInfo = &mBones[ influence->GetBoneNr() ]; - weight = influence->GetWeight(); + SkinInfluence* influence = layer->GetInfluence(orgVertex, i); + weight = influence->GetWeight(); // check if we need to invert the dual quat - MCore::DualQuaternion& influenceQuat = mBones[ influence->GetBoneNr() ].mDualQuat; + MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].mDualQuat; if (influenceQuat.mReal.Dot(pivotQuat.mReal) < 0.0f) { influenceQuat *= -1.0f; @@ -249,68 +231,46 @@ namespace EMotionFX skinQuat.Normalize(); // perform skinning - newPos = skinQuat.TransformPoint(vtxPos); - newNormal = skinQuat.TransformVector(normal); - newTangent = skinQuat.TransformVector(tangent); + positions[v] = skinQuat.TransformPoint(vtxPos); + normals[v] = skinQuat.TransformVector(normal); + newTangent = skinQuat.TransformVector(tangent); + tangents[v].Set(newTangent.GetX(), newTangent.GetY(), newTangent.GetZ(), tangentW); } else { - // perform the skinning - newPos = vtxPos; - newNormal = normal; - newTangent = tangent; + // no skinning influences, just copy the values + positions[v] = vtxPos; + normals[v] = normal; + newTangent = tangent; + tangents[v].Set(newTangent.GetX(), newTangent.GetY(), newTangent.GetZ(), tangentW); } - - // output the skinned values - positions->Set (newPos.GetX(), newPos.GetY(), newPos.GetZ()); - positions++; - normals->Set (newNormal.GetX(), newNormal.GetY(), newNormal.GetZ()); - normals++; - tangents->Set (newTangent.GetX(), newTangent.GetY(), newTangent.GetZ(), tangentW); - tangents++; } } else // there are no tangents and bitangents to skin { - const uint32 numVertices = mMesh->GetNumVertices(); - uint32 v = 0; - uint32 orgVertex; - - SkinInfluence* influence; - BoneInfo* boneInfo; - float weight; - - for (v = 0; v < numVertices; ++v) + for (AZ::u32 v = startVertex; v < endVertex; ++v) { - // get the original vertex number - orgVertex = *(orgVerts++); - - // reset the skinned position - newPos = AZ::Vector3::CreateZero(); - newNormal = AZ::Vector3::CreateZero(); - - vtxPos.Set(positions->GetX(), positions->GetY(), positions->GetZ()); - normal.Set(normals->GetX(), normals->GetY(), normals->GetZ()); + orgVertex = orgVerts[v]; + vtxPos = positions[v]; + normal = normals[v]; // process the skin influences for this vertex const size_t numInfluences = layer->GetNumInfluences(orgVertex); if (numInfluences > 0) { // get the pivot quat, used for the dot product check - const MCore::DualQuaternion& pivotQuat = mBones[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; + const MCore::DualQuaternion& pivotQuat = boneInfos[ layer->GetInfluence(orgVertex, 0)->GetBoneNr() ].mDualQuat; // our skinning dual quaternion MCore::DualQuaternion skinQuat(AZ::Quaternion(0, 0, 0, 0), AZ::Quaternion(0, 0, 0, 0)); for (size_t i = 0; i < numInfluences; ++i) { - // get the influence - influence = layer->GetInfluence(orgVertex, i); - boneInfo = &mBones[ influence->GetBoneNr() ]; - weight = influence->GetWeight(); + SkinInfluence* influence = layer->GetInfluence(orgVertex, i); + weight = influence->GetWeight(); // check if we need to invert the dual quat - MCore::DualQuaternion& influenceQuat = mBones[ influence->GetBoneNr() ].mDualQuat; + MCore::DualQuaternion influenceQuat = boneInfos[ influence->GetBoneNr() ].mDualQuat; if (influenceQuat.mReal.Dot(pivotQuat.mReal) < 0.0f) { influenceQuat *= -1.0f; @@ -324,26 +284,19 @@ namespace EMotionFX skinQuat.Normalize(); // perform skinning - newPos = skinQuat.TransformPoint(vtxPos); - newNormal = skinQuat.TransformVector(normal); + positions[v] = skinQuat.TransformPoint(vtxPos); + normals[v] = skinQuat.TransformVector(normal); } else { - // perform the skinning - newPos = vtxPos; - newNormal = normal; + // no skinning influences, just copy the values + positions[v] = vtxPos; + normals[v] = normal; } - - // output the skinned values - positions->Set(newPos.GetX(), newPos.GetY(), newPos.GetZ()); - positions++; - normals->Set(newNormal.GetX(), newNormal.GetY(), newNormal.GetZ()); - normals++; } } } - // initialize the mesh deformer void DualQuatSkinDeformer::Reinitialize(Actor* actor, Node* node, uint32 lodLevel) { @@ -352,7 +305,7 @@ namespace EMotionFX MCORE_UNUSED(lodLevel); // clear the bone information array, but don't free the currently allocated/reserved memory - mBones.Clear(false); + m_bones.clear(); // if there is no mesh if (mMesh == nullptr) @@ -360,13 +313,9 @@ namespace EMotionFX return; } - // get the attribute number SkinningInfoVertexAttributeLayer* skinningLayer = (SkinningInfoVertexAttributeLayer*)mMesh->FindSharedVertexAttributeLayer(SkinningInfoVertexAttributeLayer::TYPE_ID); MCORE_ASSERT(skinningLayer); - // reserve space for the bone array - //mBones.Reserve( actor->GetNumNodes() ); - // find out what bones this mesh uses const uint32 numOrgVerts = mMesh->GetNumOrgVertices(); for (uint32 i = 0; i < numOrgVerts; i++) @@ -379,26 +328,21 @@ namespace EMotionFX { SkinInfluence* influence = skinningLayer->GetInfluence(i, a); - // get the bone index in the array - uint32 boneIndex = FindLocalBoneIndex(influence->GetNodeNr()); - - // if the bone is not found in our array - if (boneIndex == MCORE_INVALIDINDEX32) + AZ::Outcome boneIndexOutcome = FindLocalBoneIndex(influence->GetNodeNr()); + if (boneIndexOutcome.IsSuccess()) + { + influence->SetBoneNr(boneIndexOutcome.GetValue()); + } + else { // add the bone to the array of bones in this deformer - mBones.AddEmptyExact(); - BoneInfo& lastBone = mBones.GetLast(); + BoneInfo lastBone; lastBone.mNodeNr = influence->GetNodeNr(); lastBone.mDualQuat.Identity(); - boneIndex = mBones.GetLength() - 1; + m_bones.emplace_back(lastBone); + influence->SetBoneNr(static_cast(m_bones.size() - 1)); } - - // set the bone number in the influence - influence->SetBoneNr(static_cast(boneIndex)); } } - - // get rid of all items in the used bones array - // mBones.Shrink(); } } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h index fc80256524..ec00f1186f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/DualQuatSkinDeformer.h @@ -12,13 +12,13 @@ #pragma once -// include the required headers +#include +#include #include "EMotionFXConfig.h" #include #include "Mesh.h" #include "MeshDeformer.h" - namespace EMotionFX { // forward declarations @@ -101,37 +101,47 @@ namespace EMotionFX * This is the number of different bones that the skinning information of the mesh where this deformer works on uses. * @result The number of bones. */ - MCORE_INLINE uint32 GetNumLocalBones() const { return mBones.GetLength(); } + MCORE_INLINE uint32 GetNumLocalBones() const { return static_cast(m_bones.size()); } /** * Get the node number of a given local bone. * @param index The local bone number, which must be in range of [0..GetNumLocalBones()-1]. * @result The node number, which is in range of [0..Actor::GetNumNodes()-1], depending on the actor where this deformer works on. */ - MCORE_INLINE uint32 GetLocalBone(uint32 index) const { return mBones[index].mNodeNr; } + MCORE_INLINE uint32 GetLocalBone(uint32 index) const { return m_bones[index].mNodeNr; } /** * Pre-allocate space for a given number of local bones. * This does not alter the value returned by GetNumLocalBones(). * @param numBones The number of bones to pre-allocate space for. */ - MCORE_INLINE void ReserveLocalBones(uint32 numBones) { mBones.Reserve(numBones); } - + MCORE_INLINE void ReserveLocalBones(uint32 numBones) { m_bones.reserve(numBones); } protected: /** - * Structure used for precalculating the skinning matrices. + * Structure used for pre-calculating the skinning matrices. */ struct EMFX_API BoneInfo { uint32 mNodeNr; /**< The node number. */ - MCore::DualQuaternion mDualQuat; /**< The dual quat of the precalculated matrix that contains the "globalMatrix * inverse(bindPoseMatrix)". */ + MCore::DualQuaternion mDualQuat; /**< The dual quat of the pre-calculated matrix that contains the "globalMatrix * inverse(bindPoseMatrix)". */ MCORE_INLINE BoneInfo() : mNodeNr(MCORE_INVALIDINDEX32) {} }; + AZStd::vector m_bones; /**< The array of bone information used for pre-calculation. */ + + /** + * Skin a part of the mesh. + * @param mesh The mesh to be skinned. + * @param startVertex The start vertex index to start skinning. + * @param endVertex The end vertex index for the range to be skinned. + * @param boneInfos The pre-calculated skinning matrices shared across the skinning process. + */ + static void SkinRange(Mesh* mesh, AZ::u32 startVertex, AZ::u32 endVertex, const AZStd::vector& boneInfos); - MCore::Array mBones; /**< The array of bone information used for precalculation. */ + //! Number of vertices per batch/job used for multi-threaded software skinning. + static constexpr AZ::u32 s_numVerticesPerBatch = 10000; /** * Default constructor. @@ -149,18 +159,6 @@ namespace EMotionFX * @param nodeIndex The node number to search for. * @result The index inside the mBones member array, which uses the given node. */ - MCORE_INLINE uint32 FindLocalBoneIndex(uint32 nodeIndex) const - { - const uint32 numBones = mBones.GetLength(); - for (uint32 i = 0; i < numBones; ++i) - { - if (mBones[i].mNodeNr == nodeIndex) - { - return i; - } - } - - return MCORE_INVALIDINDEX32; - } + AZ::Outcome FindLocalBoneIndex(uint32 nodeIndex) const; }; } // namespace EMotionFX diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index 3aa281c4c2..bcb1e3f300 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -650,7 +650,6 @@ namespace EMotionFX } distance = std::numeric_limits::max(); - bool isHit = false; // Get the MCore::Ray used by Mesh::Intersects // Convert the input source position and direction to a line segment by using the frustum depth as line length. @@ -659,12 +658,13 @@ namespace EMotionFX const AZ::Vector3 dest = src + dir * frustumDepth; const MCore::Ray ray(src, dest); - // Update the mesh deformers so the intersection test will hit the actor if it is being - // animated by a motion component that is previewing the animation in the editor + // Update the mesh deformers (apply software skinning and morphing) so the intersection test will hit the actor + // if it is being animated by a motion component that is previewing the animation in the editor. m_actorInstance->UpdateMeshDeformers(0.0f, true); const TransformData* transformData = m_actorInstance->GetTransformData(); const Pose* currentPose = transformData->GetCurrentPose(); + bool isHit = false; // Iterate through the meshes in the actor, looking for the closest hit const AZ::u32 lodLevel = m_actorInstance->GetLODLevel(); From d115c8904357ee330f2d305e9931db98f08a7c35 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Mon, 3 May 2021 11:48:48 -0500 Subject: [PATCH 036/185] Fixes for using the DebugDisplayRequestBus in game mode --- .../AtomDebugDisplayViewportInterface.cpp | 38 +- ...AtomDebugDisplayViewportInterface.cpp.orig | 1544 +++++++++++++++++ .../AtomDebugDisplayViewportInterface.h | 9 + .../AtomLyIntegration/AtomFont/FFont.h | 2 +- .../AtomFont/Code/Source/FFont.cpp | 13 +- .../CoreLights/EditorAreaLightComponent.cpp | 1 + 6 files changed, 1595 insertions(+), 12 deletions(-) create mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 690963e26b..871d75f194 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -244,9 +244,6 @@ namespace AZ::AtomBridge } //////////////////////////////////////////////////////////////////////// - // Partial implementation of the DebugDisplayRequestBus on Atom. - // Commented out function prototypes are waiting to be implemented. - // work tracked in [ATOM-3459] AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(AZ::RPI::ViewportContextPtr viewportContextPtr) { ResetRenderState(); @@ -272,9 +269,8 @@ namespace AZ::AtomBridge InitInternal(scene, nullptr); } - void AtomDebugDisplayViewportInterface::InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr) + void AtomDebugDisplayViewportInterface::UpdateAuxGeom(RPI::Scene* scene, AZ::RPI::View* view) { - AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); if (!scene) { m_auxGeomPtr = nullptr; @@ -286,20 +282,48 @@ namespace AZ::AtomBridge m_auxGeomPtr = nullptr; return; } - if (m_defaultInstance) + if (m_defaultInstance || !view) { m_auxGeomPtr = auxGeomFP->GetDrawQueue(); } else { - m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(viewportContextPtr->GetDefaultView().get()); + m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(view); } + } + + void AtomDebugDisplayViewportInterface::InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr) + { + AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); + UpdateAuxGeom(scene, viewportContextPtr ? viewportContextPtr->GetDefaultView().get() : nullptr); AzFramework::DebugDisplayRequestBus::Handler::BusConnect(m_viewportId); + if (!m_defaultInstance) + { + AZ::RPI::ViewportContextIdNotificationBus::Handler::BusConnect(viewportContextPtr->GetId()); + } + } + + + void AtomDebugDisplayViewportInterface::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) + { + ResetRenderState(); + if (m_defaultInstance) + { + RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); + UpdateAuxGeom(scene, nullptr); + } + else + { + auto viewportContextManager = AZ::Interface::Get(); + AZ::RPI::ViewportContextPtr viewportContextPtr = viewportContextManager->GetViewportContextById(m_viewportId); + UpdateAuxGeom(viewportContextPtr->GetRenderScene().get(), viewportContextPtr->GetDefaultView().get()); + } } AtomDebugDisplayViewportInterface::~AtomDebugDisplayViewportInterface() { AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); + AZ::RPI::ViewportContextIdNotificationBus::Handler::BusDisconnect(); m_viewportId = AzFramework::InvalidViewportId; m_auxGeomPtr = nullptr; } diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig new file mode 100644 index 0000000000..a4093ec937 --- /dev/null +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig @@ -0,0 +1,1544 @@ +/* +* 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 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +namespace // unnamed namespace to hold copies of Cry AuxGeom state enum's, this is to avoid creating a dependency on IRenderAuxGeom.h +{ + // Notes: + // Don't change the xxxShift values, they need to match the values from legacy cry rendering + // This also applies to the individual flags in EAuxGeomPublicRenderflags_*! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + enum EAuxGeomPublicRenderflagBitMasks + { + e_Mode2D3DShift = 31, + e_Mode2D3DMask = 0x1 << e_Mode2D3DShift, + + e_AlphaBlendingShift = 29, + e_AlphaBlendingMask = 0x3 << e_AlphaBlendingShift, + + e_DrawInFrontShift = 28, + e_DrawInFrontMask = 0x1 << e_DrawInFrontShift, + + e_FillModeShift = 26, + e_FillModeMask = 0x3 << e_FillModeShift, + + e_CullModeShift = 24, + e_CullModeMask = 0x3 << e_CullModeShift, + + e_DepthWriteShift = 23, + e_DepthWriteMask = 0x1 << e_DepthWriteShift, + + e_DepthTestShift = 22, + e_DepthTestMask = 0x1 << e_DepthTestShift, + + e_PublicParamsMask = e_Mode2D3DMask | e_AlphaBlendingMask | e_DrawInFrontMask | e_FillModeMask | + e_CullModeMask | e_DepthWriteMask | e_DepthTestMask + }; + + // Notes: + // e_Mode2D renders in normalized [0.. 1] screen space. + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_Mode2D3D + { + e_Mode3D = 0x0 << e_Mode2D3DShift, + e_Mode2D = 0x1 << e_Mode2D3DShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_AlphaBlendMode + { + e_AlphaNone = 0x0 << e_AlphaBlendingShift, + e_AlphaAdditive = 0x1 << e_AlphaBlendingShift, + e_AlphaBlended = 0x2 << e_AlphaBlendingShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_DrawInFrontMode + { + e_DrawInFrontOff = 0x0 << e_DrawInFrontShift, + e_DrawInFrontOn = 0x1 << e_DrawInFrontShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_FillMode + { + e_FillModeSolid = 0x0 << e_FillModeShift, + e_FillModeWireframe = 0x1 << e_FillModeShift, + e_FillModePoint = 0x2 << e_FillModeShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_CullMode + { + e_CullModeNone = 0x0 << e_CullModeShift, + e_CullModeFront = 0x1 << e_CullModeShift, + e_CullModeBack = 0x2 << e_CullModeShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_DepthWrite + { + e_DepthWriteOn = 0x0 << e_DepthWriteShift, + e_DepthWriteOff = 0x1 << e_DepthWriteShift, + }; + + // Notes: + // Don't change the xxxShift values blindly as they affect the rendering output + // that is two primitives have to be rendered after 3d primitives, alpha blended + // geometry have to be rendered after opaque ones, etc. + // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! + // Remarks: + // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) + // Check RenderAuxGeom.h in ../RenderDll/Common + // See also: + // EAuxGeomPublicRenderflagBitMasks + enum EAuxGeomPublicRenderflags_DepthTest + { + e_DepthTestOn = 0x0 << e_DepthTestShift, + e_DepthTestOff = 0x1 << e_DepthTestShift, + }; +}; + +namespace AZ::AtomBridge +{ + + //////////////////////////////////////////////////////////////////////// + SingleColorDynamicSizeLineHelper::SingleColorDynamicSizeLineHelper( + int estimatedNumLineSegments + ) + { + m_points.reserve(estimatedNumLineSegments * 2); + } + + void SingleColorDynamicSizeLineHelper::AddLineSegment( + const AZ::Vector3& lineStart, + const AZ::Vector3& lineEnd + ) + { + m_points.push_back(lineStart); + m_points.push_back(lineEnd); + } + + void SingleColorDynamicSizeLineHelper::Draw( + AZ::RPI::AuxGeomDrawPtr auxGeomDrawPtr, + const RenderState& rendState + ) const + { + if (auxGeomDrawPtr && !m_points.empty()) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = m_points.data(); + drawArgs.m_vertCount = aznumeric_cast(m_points.size()); + drawArgs.m_colors = &rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = rendState.m_lineWidth; + drawArgs.m_opacityType = rendState.m_opacityType; + drawArgs.m_depthTest = rendState.m_depthTest; + drawArgs.m_depthWrite = rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = rendState.m_viewProjOverrideIndex; + auxGeomDrawPtr->DrawLines( drawArgs ); + } + } + + void SingleColorDynamicSizeLineHelper::Draw2d( + AZ::RPI::AuxGeomDrawPtr auxGeomDrawPtr, + const RenderState& rendState + ) const + { + if (auxGeomDrawPtr && !m_points.empty()) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = m_points.data(); + drawArgs.m_vertCount = aznumeric_cast(m_points.size()); + drawArgs.m_colors = &rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = rendState.m_lineWidth; + drawArgs.m_opacityType = rendState.m_opacityType; + drawArgs.m_depthTest = rendState.m_depthTest; + drawArgs.m_depthWrite = rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = auxGeomDrawPtr->GetOrAdd2DViewProjOverride(); + auxGeomDrawPtr->DrawLines( drawArgs ); + } + } + + void SingleColorDynamicSizeLineHelper::Reset() + { + m_points.clear(); + } + //////////////////////////////////////////////////////////////////////// + + // Partial implementation of the DebugDisplayRequestBus on Atom. + // Commented out function prototypes are waiting to be implemented. + // work tracked in [ATOM-3459] + AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(AZ::RPI::ViewportContextPtr viewportContextPtr) + { + ResetRenderState(); + m_viewportId = viewportContextPtr->GetId(); + m_defaultInstance = false; + auto setupScene = [this](RPI::ScenePtr scene) + { + auto viewportContextManager = AZ::Interface::Get(); + AZ::RPI::ViewportContextPtr viewportContextPtr = viewportContextManager->GetViewportContextById(m_viewportId); + InitInternal(scene.get(), viewportContextPtr); + }; + setupScene(viewportContextPtr->GetRenderScene()); + m_sceneChangeHandler = AZ::RPI::ViewportContext::SceneChangedEvent::Handler(setupScene); + viewportContextPtr->ConnectSceneChangedHandler(m_sceneChangeHandler); + } + + AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(uint32_t defaultInstanceAddress) + { + ResetRenderState(); + m_viewportId = defaultInstanceAddress; + m_defaultInstance = true; + RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); + InitInternal(scene, nullptr); + } + + void AtomDebugDisplayViewportInterface::InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr) + { + AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); + if (!scene) + { + m_auxGeomPtr = nullptr; + return; + } + auto auxGeomFP = scene->GetFeatureProcessor(); + if (!auxGeomFP) + { + m_auxGeomPtr = nullptr; + return; + } + if (m_defaultInstance) + { + m_auxGeomPtr = auxGeomFP->GetDrawQueue(); + } + else + { + m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(viewportContextPtr->GetDefaultView().get()); + } + AzFramework::DebugDisplayRequestBus::Handler::BusConnect(m_viewportId); + } + + AtomDebugDisplayViewportInterface::~AtomDebugDisplayViewportInterface() + { + AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); + m_viewportId = AzFramework::InvalidViewportId; + m_auxGeomPtr = nullptr; + } + + void AtomDebugDisplayViewportInterface::ResetRenderState() + { + m_rendState = RenderState(); + for (int index = 0; index < RenderState::TransformStackSize; ++index) + { + m_rendState.m_transformStack[index] = AZ::Matrix3x4::Identity(); + } + } + + void AtomDebugDisplayViewportInterface::SetColor(float r, float g, float b, float a) + { + m_rendState.m_color = AZ::Color(r, g, b, a); + } + + void AtomDebugDisplayViewportInterface::SetColor(const AZ::Color& color) + { + m_rendState.m_color = color; + } + + void AtomDebugDisplayViewportInterface::SetColor(const AZ::Vector4& color) + { + m_rendState.m_color = AZ::Color(color); + } + + void AtomDebugDisplayViewportInterface::SetAlpha(float a) + { + m_rendState.m_color.SetA(a); + if (a < 1.0f) + { + m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Opaque; + } + else + { + m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Translucent; + } + } + + void AtomDebugDisplayViewportInterface::DrawQuad( + const AZ::Vector3& p1, + const AZ::Vector3& p2, + const AZ::Vector3& p3, + const AZ::Vector3& p4) + { + if (m_auxGeomPtr) + { + AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; + AZ::Vector3 triangles[6]; + triangles[0] = wsPoints[0]; + triangles[1] = wsPoints[1]; + triangles[2] = wsPoints[2]; + triangles[3] = wsPoints[2]; + triangles[4] = wsPoints[3]; + triangles[5] = wsPoints[0]; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = triangles; + drawArgs.m_vertCount = 6; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawQuad(float width, float height) + { + if (!m_auxGeomPtr || width <= 0.0f || height <= 0.0f) + { + return; + } + + m_auxGeomPtr->DrawQuad( + width, + height, + GetCurrentTransform(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex); + } + + void AtomDebugDisplayViewportInterface::DrawWireQuad( + const AZ::Vector3& p1, + const AZ::Vector3& p2, + const AZ::Vector3& p3, + const AZ::Vector3& p4) + { + if (m_auxGeomPtr) + { + AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = wsPoints; + drawArgs.m_vertCount = 4; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawPolylines(drawArgs, AZ::RPI::AuxGeomDraw::PolylineEnd::Closed); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireQuad(float width, float height) + { + if (!m_auxGeomPtr || width <= 0.0f || height <= 0.0f) + { + return; + } + + m_auxGeomPtr->DrawQuad( + width, + height, + GetCurrentTransform(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex); + } + + void AtomDebugDisplayViewportInterface::DrawQuadGradient( + const AZ::Vector3& p1, + const AZ::Vector3& p2, + const AZ::Vector3& p3, + const AZ::Vector3& p4, + const AZ::Vector4& firstColor, + const AZ::Vector4& secondColor) + { + if (m_auxGeomPtr) + { + AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; + AZ::Vector3 triangles[6]; + AZ::Color colors[6]; + triangles[0] = wsPoints[0]; colors[0] = firstColor; + triangles[1] = wsPoints[1]; colors[1] = firstColor; + triangles[2] = wsPoints[2]; colors[2] = secondColor; + triangles[3] = wsPoints[2]; colors[3] = secondColor; + triangles[4] = wsPoints[3]; colors[4] = secondColor; + triangles[5] = wsPoints[0]; colors[5] = firstColor; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = triangles; + drawArgs.m_vertCount = 6; + drawArgs.m_colors = colors; + drawArgs.m_colorCount = 6; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawTri(const AZ::Vector3& p1, const AZ::Vector3& p2, const AZ::Vector3& p3) + { + if (m_auxGeomPtr) + { + AZ::Vector3 verts[3] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3)}; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = verts; + drawArgs.m_vertCount = 3; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawTriangles(const AZStd::vector& vertices, const AZ::Color& color) + { + if (m_auxGeomPtr) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = vertices.data(); + drawArgs.m_vertCount = aznumeric_cast(vertices.size()); + drawArgs.m_colors = &color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawTrianglesIndexed( + const AZStd::vector& vertices, + const AZStd::vector& indices, + const AZ::Color& color) + { + if (m_auxGeomPtr) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicIndexedDrawArguments drawArgs; + drawArgs.m_verts = vertices.data(); + drawArgs.m_vertCount = aznumeric_cast(vertices.size()); + drawArgs.m_indices = indices.data(); + drawArgs.m_indexCount = aznumeric_cast(indices.size()); + drawArgs.m_colors = &color; + drawArgs.m_colorCount = 1; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawTriangles(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireBox(const AZ::Vector3& min, const AZ::Vector3& max) + { + if (m_auxGeomPtr) + { + m_auxGeomPtr->DrawAabb( + AZ::Aabb::CreateFromMinMax(min, max), + GetCurrentTransform(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawSolidBox(const AZ::Vector3& min, const AZ::Vector3& max) + { + if (m_auxGeomPtr) + { + m_auxGeomPtr->DrawAabb( + AZ::Aabb::CreateFromMinMax(min, max), + GetCurrentTransform(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex); + } + } + + void AtomDebugDisplayViewportInterface::DrawSolidOBB( + const AZ::Vector3& center, + const AZ::Vector3& axisX, + const AZ::Vector3& axisY, + const AZ::Vector3& axisZ, + const AZ::Vector3& halfExtents) + { + if (m_auxGeomPtr) + { + AZ::Quaternion rotation = AZ::Quaternion::CreateFromMatrix3x3(AZ::Matrix3x3::CreateFromColumns(axisX, axisY, axisZ)); + AZ::Obb obb = AZ::Obb::CreateFromPositionRotationAndHalfLengths(center, rotation, halfExtents); + m_auxGeomPtr->DrawObb( + obb, + AZ::Vector3::CreateZero(), + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex); + } + } + + void AtomDebugDisplayViewportInterface::DrawPoint(const AZ::Vector3& p, int nSize) + { + if (m_auxGeomPtr) + { + AZ::Vector3 wsPoint = ToWorldSpacePosition(p); + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = &wsPoint; + drawArgs.m_vertCount = 1; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = aznumeric_cast(nSize); + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawPoints(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawLine(const AZ::Vector3& p1, const AZ::Vector3& p2) + { + if (m_auxGeomPtr) + { + AZ::Vector3 verts[2] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2)}; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = verts; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawLine(const AZ::Vector3& p1, const AZ::Vector3& p2, const AZ::Vector4& col1, const AZ::Vector4& col2) + { + if (m_auxGeomPtr) + { + AZ::Vector3 verts[2] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2)}; + AZ::Color colors[2] = {col1, col2}; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = verts; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = colors; + drawArgs.m_colorCount = 2; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawLines(const AZStd::vector& lines, const AZ::Color& color) + { + if (m_auxGeomPtr) + { + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = lines.data(); + drawArgs.m_vertCount = aznumeric_cast(lines.size()); + drawArgs.m_colors = &color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawPolyLine(const AZ::Vector3* pnts, int numPoints, bool cycled) + { + if (m_auxGeomPtr) + { + AZStd::vector wsPoints(static_cast(numPoints)); + for (int index = 0; index < numPoints; ++index) + { + wsPoints[index] = ToWorldSpacePosition(pnts[index]); + } + AZ::RPI::AuxGeomDraw::PolylineEnd polylineEnd = cycled ? AZ::RPI::AuxGeomDraw::PolylineEnd::Closed : AZ::RPI::AuxGeomDraw::PolylineEnd::Open; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = wsPoints.data(); + drawArgs.m_vertCount = aznumeric_cast(numPoints); + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + m_auxGeomPtr->DrawPolylines(drawArgs, polylineEnd); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireQuad2d(const AZ::Vector2& p1, const AZ::Vector2& p2, float z) + { + if (m_auxGeomPtr) + { + AZ::Vector3 points[4]; + points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); + points[1] = AZ::Vector3(p2.GetX(), p1.GetY(), z); + points[2] = AZ::Vector3(p2.GetX(), p2.GetY(), z); + points[3] = AZ::Vector3(p1.GetX(), p2.GetY(), z); + + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = points; + drawArgs.m_vertCount = 4; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); + m_auxGeomPtr->DrawPolylines(drawArgs, AZ::RPI::AuxGeomDraw::PolylineEnd::Closed); + } + } + + void AtomDebugDisplayViewportInterface::DrawLine2d(const AZ::Vector2& p1, const AZ::Vector2& p2, float z) + { + if (m_auxGeomPtr) + { + AZ::Vector3 points[2]; + points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); + points[1] = AZ::Vector3(p2.GetX(), p2.GetY(), z); + + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = points; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawLine2dGradient(const AZ::Vector2& p1, const AZ::Vector2& p2, float z, const AZ::Vector4& firstColor, const AZ::Vector4& secondColor) + { + if (m_auxGeomPtr) + { + AZ::Vector3 points[2]; + points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); + points[1] = AZ::Vector3(p2.GetX(), p2.GetY(), z); + AZ::Color colors[2] = {firstColor, secondColor}; + + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = points; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = colors; + drawArgs.m_colorCount = 2; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); + m_auxGeomPtr->DrawLines(drawArgs); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireCircle2d(const AZ::Vector2& center, float radius, float z) + { + if (m_auxGeomPtr) + { + // Draw axis aligned arc + constexpr float angularStepDegrees = 10.0f; + constexpr float startAngleDegrees = 0.0f; + constexpr float sweepAngleDegrees = 360.0f; + const float stepAngle = DegToRad(angularStepDegrees); + const float startAngle = DegToRad(startAngleDegrees); + const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; + SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + AZ::Vector3 pos = AZ::Vector3(center.GetX(), center.GetY(), z); + CreateAxisAlignedArc( + lines, + stepAngle, + startAngle, + stopAngle, + pos, + radiusV3, + CircleAxis::CircleAxisZ + ); + lines.Draw2d(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawArc( + const AZ::Vector3& pos, + float radius, + float startAngleDegrees, + float sweepAngleDegrees, + float angularStepDegrees, + int referenceAxis) + { + if (m_auxGeomPtr) + { + // Draw axis aligned arc + const float stepAngle = DegToRad(angularStepDegrees); + const float startAngle = DegToRad(startAngleDegrees); + const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; + SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + CreateAxisAlignedArc( + lines, + stepAngle, + startAngle, + stopAngle, + pos, + radiusV3, + static_cast(referenceAxis) + ); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawArc( + const AZ::Vector3& pos, + float radius, + float startAngleDegrees, + float sweepAngleDegrees, + float angularStepDegrees, + const AZ::Vector3& fixedAxis) + { + if (m_auxGeomPtr) + { + // Draw arbitraty axis arc + const float stepAngle = DegToRad(angularStepDegrees); + const float startAngle = DegToRad(startAngleDegrees); + const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; + SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + CreateArbitraryAxisArc( + lines, + stepAngle, + startAngle, + stopAngle, + pos, + radiusV3, + fixedAxis + ); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawCircle(const AZ::Vector3& pos, float radius, int nUnchangedAxis) + { + if (m_auxGeomPtr) + { + // Draw circle with default radius. + const float step = DegToRad(10.0f); + const float maxAngle = DegToRad(360.0f) + step; + SingleColorStaticSizeLineHelper<40> lines; // hard code 40 lines until DegToRad is constexpr. + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + CreateAxisAlignedArc( + lines, + step, + 0.0f, + maxAngle, + pos, + radiusV3, + static_cast(nUnchangedAxis)); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawHalfDottedCircle(const AZ::Vector3& pos, float radius, const AZ::Vector3& viewPos, int nUnchangedAxis) + { + if (m_auxGeomPtr) + { + // Draw circle with single radius. + const float step = DegToRad(10.0f); + const float maxAngle = DegToRad(360.0f) + step; + SingleColorStaticSizeLineHelper<40> lines; // hard code 40 lines until DegToRad is constexpr. + + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); + const AZ::Vector3 worldView = ToWorldSpacePosition(viewPos); + const AZ::Vector3 worldDir = worldView - worldPos; + + CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, radiusV3, static_cast(nUnchangedAxis%CircleAxisMax), + [&worldPos, &worldDir](const AZ::Vector3& lineStart, const AZ::Vector3& lineEnd, int segmentIndex) + { + AZ_UNUSED(lineEnd); + const float dot = (lineStart - worldPos).Dot(worldDir); + const bool facing = dot > 0.0f; + // if so skip every other line to produce a dotted effect + if (facing || segmentIndex % 2 == 0) + { + return true; + } + return false; + }); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawCone(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius, float height, bool drawShaded) + { + if (m_auxGeomPtr) + { + const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); + const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); + m_auxGeomPtr->DrawCone( + worldPos, + worldDir, + radius, + height, + m_rendState.m_color, + drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireCylinder(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) + { + if (m_auxGeomPtr) + { + const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); + const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); + m_auxGeomPtr->DrawCylinder( + worldCenter, + worldAxis, + radius, + height, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawSolidCylinder( + const AZ::Vector3& center, + const AZ::Vector3& axis, + float radius, + float height, + bool drawShaded) + { + if (m_auxGeomPtr) + { + const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); + const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); + m_auxGeomPtr->DrawCylinder( + worldCenter, + worldAxis, + radius, + height, + m_rendState.m_color, + drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireCapsule( + const AZ::Vector3& center, + const AZ::Vector3& axis, + float radius, + float heightStraightSection) + { + if (m_auxGeomPtr && radius > FLT_EPSILON && axis.GetLengthSq() > FLT_EPSILON) + { + AZ::Vector3 axisNormalized = axis.GetNormalizedEstimate(); + SingleColorStaticSizeLineHelper<(16+1) * 5> lines; // 360/22.5 = 16, 5 possible calls to CreateArbitraryAxisArc + AZ::Vector3 radiusV3 = AZ::Vector3(radius); + float stepAngle = DegToRad(22.5f); + float Deg0 = DegToRad(0.0f); + + + // Draw cylinder part (or just a circle around the middle) + if (heightStraightSection > FLT_EPSILON) + { + DrawWireCylinder(center, axis, radius, heightStraightSection); + } + else + { + float Deg360 = DegToRad(360.0f); + CreateArbitraryAxisArc( + lines, + stepAngle, + Deg0, + Deg360, + center, + radiusV3, + axisNormalized + ); + } + + float Deg90 = DegToRad(90.0f); + float Deg180 = DegToRad(180.0f); + + AZ::Vector3 ortho1Normalized, ortho2Normalized; + CalcBasisVectors(axisNormalized, ortho1Normalized, ortho2Normalized); + AZ::Vector3 centerToTopCircleCenter = axisNormalized * heightStraightSection * 0.5f; + AZ::Vector3 topCenter = center + centerToTopCircleCenter; + AZ::Vector3 bottomCenter = center - centerToTopCircleCenter; + + // Draw top cap as two criss-crossing 180deg arcs + CreateArbitraryAxisArc( + lines, + stepAngle, + Deg90, + Deg90 + Deg180, + topCenter, + radiusV3, + ortho1Normalized + ); + + CreateArbitraryAxisArc( + lines, + stepAngle, + Deg180, + Deg180 + Deg180, + topCenter, + radiusV3, + ortho2Normalized + ); + + // Draw bottom cap + CreateArbitraryAxisArc( + lines, + stepAngle, + -Deg90, + -Deg90 + Deg180, + bottomCenter, + radiusV3, + ortho1Normalized + ); + + CreateArbitraryAxisArc( + lines, + stepAngle, + Deg0, + Deg0 + Deg180, + bottomCenter, + radiusV3, + ortho2Normalized + ); + + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireSphere(const AZ::Vector3& pos, float radius) + { + if (m_auxGeomPtr) + { + + m_auxGeomPtr->DrawSphere( + ToWorldSpacePosition(pos), + radius, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Line, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireSphere(const AZ::Vector3& pos, const AZ::Vector3 radius) + { + if (m_auxGeomPtr) + { + // This matches Cry behavior, the DrawWireSphere above may need modifying to use the same approach. + // Draw 3 axis aligned circles + const float step = DegToRad(10.0f); + const float maxAngle = DegToRad(360.0f) + step; + SingleColorStaticSizeLineHelper<40*3> lines; // hard code to 40 lines * 3 circles until DegToRad is constexpr. + + // Z Axis + AZ::Vector3 axisRadius(radius.GetX(), radius.GetY(), 0.0f); + CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisZ); + + // X Axis + axisRadius = AZ::Vector3(0.0f, radius.GetY(), radius.GetZ()); + CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisX); + + // Y Axis + axisRadius = AZ::Vector3(radius.GetX(), 0.0f, radius.GetZ()); + CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisY); + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawWireDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) + { + if (m_auxGeomPtr) + { + + // Draw 3 axis aligned circles + const float stepAngle = DegToRad(11.25f); + const float startAngle = DegToRad(0.0f); + const float stopAngle = DegToRad(360.0f) + startAngle; + SingleColorDynamicSizeLineHelper lines(2+static_cast(360.0f/11.25f)); // num disk segments + 1 for azis line + 1 for spare + const AZ::Vector3 radiusV3 = AZ::Vector3(radius); + CreateArbitraryAxisArc( + lines, + stepAngle, + startAngle, + stopAngle, + pos, + radiusV3, + dir + ); + + lines.AddLineSegment(ToWorldSpacePosition(pos), ToWorldSpacePosition(pos + dir * (radius * 0.2f))); // 0.2f comes from Code\Sandbox\Editor\Objects\DisplayContextShared.inl DisplayContext::DrawWireDisk + lines.Draw(m_auxGeomPtr, m_rendState); + } + } + + void AtomDebugDisplayViewportInterface::DrawBall(const AZ::Vector3& pos, float radius, bool drawShaded) + { + if (m_auxGeomPtr) + { + // get the max scaled radius in case the transform on the stack is scaled non-uniformly + const float transformedRadiusX = ToWorldSpaceVector(AZ::Vector3(radius, 0.0f, 0.0f)).GetLengthEstimate(); + const float transformedRadiusY = ToWorldSpaceVector(AZ::Vector3(0.0f, radius, 0.0f)).GetLengthEstimate(); + const float transformedRadiusZ = ToWorldSpaceVector(AZ::Vector3(0.0f, 0.0f, radius)).GetLengthEstimate(); + const float maxTransformedRadius = + AZ::GetMax(transformedRadiusX, AZ::GetMax(transformedRadiusY, transformedRadiusZ)); + + AZ::RPI::AuxGeomDraw::DrawStyle drawStyle = drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid; + m_auxGeomPtr->DrawSphere( + ToWorldSpacePosition(pos), + maxTransformedRadius, + m_rendState.m_color, + drawStyle, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) + { + if (m_auxGeomPtr) + { + const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); + const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); + m_auxGeomPtr->DrawDisk( + worldPos, + worldDir, + radius, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + + void AtomDebugDisplayViewportInterface::DrawArrow(const AZ::Vector3& src, const AZ::Vector3& trg, float headScale, bool dualEndedArrow) + { + if (m_auxGeomPtr) + { + float f2dScale = 1.0f; + float arrowLen = 0.4f * headScale; + float arrowRadius = 0.1f * headScale; + // if (flags & DISPLAY_2D) + // { + // f2dScale = 1.2f * ToWorldSpaceVector(Vec3(1, 0, 0)).GetLength(); + // } + AZ::Vector3 dir = trg - src; + dir = ToWorldSpaceVector(dir.GetNormalized()); + AZ::Vector3 verts[2] = {ToWorldSpacePosition(src), ToWorldSpacePosition(trg)}; + AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; + drawArgs.m_verts = verts; + drawArgs.m_vertCount = 2; + drawArgs.m_colors = &m_rendState.m_color; + drawArgs.m_colorCount = 1; + drawArgs.m_size = m_rendState.m_lineWidth; + drawArgs.m_opacityType = m_rendState.m_opacityType; + drawArgs.m_depthTest = m_rendState.m_depthTest; + drawArgs.m_depthWrite = m_rendState.m_depthWrite; + drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; + if (!dualEndedArrow) + { + verts[1] -= dir * arrowLen; + m_auxGeomPtr->DrawLines(drawArgs); + m_auxGeomPtr->DrawCone( + verts[1], + dir, + arrowRadius * f2dScale, + arrowLen * f2dScale, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + else + { + verts[0] += dir * arrowLen; + verts[1] -= dir * arrowLen; + m_auxGeomPtr->DrawLines(drawArgs); + m_auxGeomPtr->DrawCone( + verts[0], + -dir, + arrowRadius * f2dScale, + arrowLen * f2dScale, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + m_auxGeomPtr->DrawCone( + verts[1], + dir, + arrowRadius * f2dScale, + arrowLen * f2dScale, + m_rendState.m_color, + AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, + m_rendState.m_depthTest, + m_rendState.m_depthWrite, + m_rendState.m_faceCullMode, + m_rendState.m_viewProjOverrideIndex + ); + } + } + } + + void AtomDebugDisplayViewportInterface::DrawTextLabel( + const AZ::Vector3& pos, + float size, + const char* text, + const bool center, + int srcOffsetX [[maybe_unused]], + int srcOffsetY [[maybe_unused]]) + { + // abort draw if draw is invalid or font query interface is missing. + if (!text || size == 0.0f || !AZ::Interface::Get()) + { + return; + } + + AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); + // abort draw if font draw interface is missing + if (!fontDrawInterface) + { + return; + } + // if 2d draw need to project pos to screen first + AzFramework::TextDrawParameters params; + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works + params.m_position = pos; + params.m_color = m_rendState.m_color; + params.m_scale = AZ::Vector2(size); + params.m_hAlign = center ? AzFramework::TextHorizontalAlignment::Center : AzFramework::TextHorizontalAlignment::Left; //! Horizontal text alignment + params.m_monospace = false; //! disable character proportional spacing + params.m_depthTest = false; //! Test character against the depth buffer + params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution + params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger + params.m_multiline = true; //! text respects ascii newline characters + + fontDrawInterface->DrawScreenAlignedText3d(params, text); + } + + void AtomDebugDisplayViewportInterface::Draw2dTextLabel( + float x, + float y, + float size, + const char* text, + bool center) + { +<<<<<<< HEAD + // abort draw if draw is invalid or font query interface is missing. + if (!text || size == 0.0f || !AZ::Interface::Get()) + { + return; + } + + AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); + // abort draw if font draw interface is missing + if (!fontDrawInterface) +======= + auto fontQueryInterface = AZ::Interface::Get(); + if (!fontQueryInterface) + { + return; + } + AzFramework::FontDrawInterface* fontDrawInterface = fontQueryInterface->GetDefaultFontDrawInterface(); + if (!fontDrawInterface || !text || size == 0.0f) +>>>>>>> upstream/main + { + return; + } + // if 2d draw need to project pos to screen first + AzFramework::TextDrawParameters params; + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works + params.m_position = AZ::Vector3(x, y, 1.0f); + params.m_color = m_rendState.m_color; + params.m_scale = AZ::Vector2(size); + params.m_hAlign = center ? AzFramework::TextHorizontalAlignment::Center : AzFramework::TextHorizontalAlignment::Left; //! Horizontal text alignment + params.m_monospace = false; //! disable character proportional spacing + params.m_depthTest = false; //! Test character against the depth buffer + params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution + params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger + params.m_multiline = true; //! text respects ascii newline characters + + fontDrawInterface->DrawScreenAlignedText2d(params, text); + } + + void AtomDebugDisplayViewportInterface::DrawTextOn2DBox( + const AZ::Vector3& pos [[maybe_unused]], + const char* text [[maybe_unused]], + float textScale [[maybe_unused]], + const AZ::Vector4& TextColor [[maybe_unused]], + const AZ::Vector4& TextBackColor [[maybe_unused]]) + { + AZ_Assert(false, "Unexpected use of legacy api, please file a feature request with the rendering team to get this implemented!"); + } + // unhandledled on Atom - virtual void DrawTextureLabel(ITexture* texture, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; + // void AtomDebugDisplayViewportInterface::DrawTextureLabel(int textureId, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; + + void AtomDebugDisplayViewportInterface::SetLineWidth(float width) + { + AZ_Assert(width >= 0.0f && width <= 255.0f, "Width (%f) exceeds allowable range [0 - 255]", width); + m_rendState.m_lineWidth = static_cast(width); + } + + bool AtomDebugDisplayViewportInterface::IsVisible(const AZ::Aabb& bounds) + { + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + const AZ::Matrix4x4& worldToClip = viewportContext->GetDefaultView()->GetWorldToClipMatrix(); + AZ::Frustum frustum = AZ::Frustum::CreateFromMatrixColumnMajor(worldToClip, Frustum::ReverseDepth::True); + return frustum.IntersectAabb(bounds) != AZ::IntersectResult::Exterior; + } + // int AtomDebugDisplayViewportInterface::SetFillMode(int nFillMode) override; + float AtomDebugDisplayViewportInterface::GetLineWidth() + { + return m_rendState.m_lineWidth; + } + + float AtomDebugDisplayViewportInterface::GetAspectRatio() + { + AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); + auto windowSize = viewportContext->GetViewportSize(); + return aznumeric_cast(windowSize.m_width)/aznumeric_cast(windowSize.m_height); + } + + void AtomDebugDisplayViewportInterface::DepthTestOff() + { + m_rendState.m_depthTest = AZ::RPI::AuxGeomDraw::DepthTest::Off; + } + + void AtomDebugDisplayViewportInterface::DepthTestOn() + { + m_rendState.m_depthTest = AZ::RPI::AuxGeomDraw::DepthTest::On; + } + + void AtomDebugDisplayViewportInterface::DepthWriteOff() + { + m_rendState.m_depthWrite = AZ::RPI::AuxGeomDraw::DepthWrite::Off; + } + + void AtomDebugDisplayViewportInterface::DepthWriteOn() + { + m_rendState.m_depthWrite = AZ::RPI::AuxGeomDraw::DepthWrite::On; + } + + void AtomDebugDisplayViewportInterface::CullOff() + { + m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::None; + } + + void AtomDebugDisplayViewportInterface::CullOn() + { + m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::Back; + } + + bool AtomDebugDisplayViewportInterface::SetDrawInFrontMode(bool on) + { + AZ_UNUSED(on); + return false; + } + + AZ::u32 AtomDebugDisplayViewportInterface::GetState() + { + return ConvertRenderStateToCry(); + } + + AZ::u32 AtomDebugDisplayViewportInterface::SetState(AZ::u32 state) + { + uint32_t currentState = ConvertRenderStateToCry(); + uint32_t changedState = (state & e_PublicParamsMask) ^ currentState; + + if (changedState & e_Mode2D3DMask) + { + // this is the only way to turn on 2d Mode under Atom + if (state & e_Mode2D) + { + AZ_Assert((currentState & e_DrawInFrontOn) == 0 && (changedState & e_DrawInFrontOn) == 0, "Atom doesnt support Draw In Front and 2d at the same time"); + m_rendState.m_viewProjOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); + m_rendState.m_2dMode = true; + } + else // switch back to mode 3d + { + m_rendState.m_viewProjOverrideIndex = -1; + m_rendState.m_2dMode = false; + } + } + + if (changedState & e_AlphaBlendingMask) + { + switch (state&e_AlphaBlendingMask) + { + case e_AlphaNone: + m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Opaque; + break; + case e_AlphaAdditive: + [[fallthrough]]; // Additive not currently supported in Atom AuxGeom implementation + case e_AlphaBlended: + m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Translucent; + break; + } + } + + if (changedState & e_DrawInFrontMask) + { + AZ_Assert( // either state is turning DrawInFront off or Mode 2D has to be off + (state & e_DrawInFrontOn) == 0 || + ((currentState & e_Mode2D) == 0 && (changedState & e_Mode2D) == 0), + "Atom doesnt support Draw In Front and 2d at the same time"); + SetDrawInFrontMode(changedState & e_DrawInFrontOn); + } + + if (changedState & e_CullModeMask) + { + switch (state & e_CullModeMask) + { + case e_CullModeNone: + CullOff(); + break; + case e_CullModeFront: + // Currently no other way to set front face culling in DebugDisplayRequestBus + m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::Front; + break; + case e_CullModeBack: + CullOn(); + break; + } + } + + if (changedState & e_DepthWriteMask) + { + if (state & e_DepthWriteOff) + { + DepthWriteOff(); + } + else + { + DepthWriteOn(); + } + } + + if (changedState & e_DepthTestMask) + { + if (state & e_DepthTestOff) + { + DepthTestOff(); + } + else + { + DepthTestOn(); + } + } + + return currentState; + } + + void AtomDebugDisplayViewportInterface::PushMatrix(const AZ::Transform& tm) + { + AZ_Assert(m_rendState.m_currentTransform < RenderState::TransformStackSize, "Exceeded AtomDebugDisplayViewportInterface matrix stack size"); + if (m_rendState.m_currentTransform < RenderState::TransformStackSize) + { + m_rendState.m_currentTransform++; + m_rendState.m_transformStack[m_rendState.m_currentTransform] = m_rendState.m_transformStack[m_rendState.m_currentTransform - 1] * AZ::Matrix3x4::CreateFromTransform(tm); + } + } + + void AtomDebugDisplayViewportInterface::PopMatrix() + { + AZ_Assert(m_rendState.m_currentTransform > 0, "Underflowed AtomDebugDisplayViewportInterface matrix stack"); + if (m_rendState.m_currentTransform > 0) + { + m_rendState.m_currentTransform--; + } + } + + const AZ::Matrix3x4& AtomDebugDisplayViewportInterface::GetCurrentTransform() const + { + return m_rendState.m_transformStack[m_rendState.m_currentTransform]; + } + + AZ::RPI::ViewportContextPtr AtomDebugDisplayViewportInterface::GetViewportContext() const + { + auto viewContextManager = AZ::Interface::Get(); + if (m_defaultInstance) + { + return viewContextManager->GetViewportContextByName(viewContextManager->GetDefaultViewportContextName()); + } + else + { + return viewContextManager->GetViewportContextById(m_viewportId); + } + } + + uint32_t AtomDebugDisplayViewportInterface::ConvertRenderStateToCry() const + { + uint32_t result = 0; + + result |= m_rendState.m_2dMode ? e_Mode2D : e_Mode3D; + result |= m_rendState.m_opacityType == AZ::RPI::AuxGeomDraw::OpacityType::Opaque ? e_AlphaNone : e_AlphaBlended; + result |= m_rendState.m_drawInFront ? e_DrawInFrontOn : e_DrawInFrontOff; + result |= m_rendState.m_depthTest == AZ::RPI::AuxGeomDraw::DepthTest::On ? e_DepthTestOn : e_DepthTestOff; + result |= m_rendState.m_depthWrite == AZ::RPI::AuxGeomDraw::DepthWrite::On ? e_DepthWriteOn : e_DepthWriteOff; + switch (m_rendState.m_faceCullMode) + { + case AZ::RPI::AuxGeomDraw::FaceCullMode::None: + result |= e_CullModeNone; + break; + case AZ::RPI::AuxGeomDraw::FaceCullMode::Front: + result |= e_CullModeFront; + break; + case AZ::RPI::AuxGeomDraw::FaceCullMode::Back: + result |= e_CullModeBack; + break; + default: + AZ_Assert(false, "Trying to convert an unknown culling mode to cry!"); + break; + } + + return result; + } +} diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h index 021d816ca4..4520b60041 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h @@ -25,6 +25,7 @@ #include #include #include +#include namespace AZ::AtomBridge { @@ -121,6 +122,7 @@ namespace AZ::AtomBridge class AtomDebugDisplayViewportInterface final : public AzFramework::DebugDisplayRequestBus::Handler + , public AZ::RPI::ViewportContextIdNotificationBus::Handler { public: AZ_RTTI(AtomDebugDisplayViewportInterface, "{09AF6A46-0100-4FBF-8F94-E6B221322D14}", AzFramework::DebugDisplayRequestBus::Handler); @@ -198,6 +200,12 @@ namespace AZ::AtomBridge void PopMatrix() override; private: + + // ViewportContextIdNotificationBus handlers + void OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) override; + + + // internal helper functions using LineSegmentFilterFunc = AZStd::function; enum CircleAxis { @@ -245,6 +253,7 @@ namespace AZ::AtomBridge const AZ::Matrix3x4& GetCurrentTransform() const; + void UpdateAuxGeom(RPI::Scene* scene, AZ::RPI::View* view); void InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr); AZ::RPI::ViewportContextPtr GetViewportContext() const; diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h index 8e60cc2055..fd66534197 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h +++ b/Gems/AtomLyIntegration/AtomFont/Code/Include/AtomLyIntegration/AtomFont/FFont.h @@ -226,7 +226,7 @@ namespace AZ private: virtual ~FFont(); - bool InitFont(); + bool InitFont(AZ::RPI::Scene* renderScene); bool InitTexture(); bool InitCache(); diff --git a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp index 20879876e7..d36307e4ec 100644 --- a/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp +++ b/Gems/AtomLyIntegration/AtomFont/Code/Source/FFont.cpp @@ -99,7 +99,7 @@ AZ::RPI::WindowContextSharedPtr AZ::FFont::GetDefaultWindowContext() const return {}; } -bool AZ::FFont::InitFont() +bool AZ::FFont::InitFont(AZ::RPI::Scene* renderScene) { auto initializationState = InitializationState::Uninitialized; // Do an atomic transition to Initializing if we're in the Uninitialized state. @@ -111,8 +111,13 @@ bool AZ::FFont::InitFont() return initializationState == InitializationState::Initialized; } + if (!renderScene) + { + return false; + } + // Create and initialize DynamicDrawContext for font draw - AZ::RPI::Ptr dynamicDraw = m_atomFont->GetOrCreateDynamicDrawForScene(GetDefaultViewportContext()->GetRenderScene().get()); + AZ::RPI::Ptr dynamicDraw = m_atomFont->GetOrCreateDynamicDrawForScene(renderScene); // Save draw srg input indices for later use Data::Instance drawSrg = dynamicDraw->NewDrawSrg(); @@ -299,7 +304,7 @@ void AZ::FFont::DrawStringUInternal( const TextDrawContext& ctx) { // Lazily ensure we're initialized before attempting to render. - if (!InitFont()) + if (!viewportContext || !InitFont(viewportContext->GetRenderScene().get())) { return; } @@ -1623,7 +1628,7 @@ void AZ::FFont::ScaleCoord(const RHI::Viewport& viewport, float& x, float& y) co void AZ::FFont::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstrapScene) { - InitFont(); + InitFont(bootstrapScene); } static void SetCommonContextFlags(AZ::TextDrawContext& ctx, const AzFramework::TextDrawParameters& params) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp index 8c5f6d6836..a77bcfdd12 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp @@ -336,6 +336,7 @@ namespace AZ bool needsFullRefresh = HandleLightTypeChange(); LmbrCentral::EditorShapeComponentRequestsBus::Event(GetEntityId(), &LmbrCentral::EditorShapeComponentRequests::SetShapeColor, m_controller.m_configuration.m_color); + LmbrCentral::EditorShapeComponentRequestsBus::Event(GetEntityId(), &LmbrCentral::EditorShapeComponentRequests::SetShapeWireframeColor, m_controller.m_configuration.m_color); // If photometric unit changes, convert the intensities so the actual intensity doesn't change. m_controller.ConvertToIntensityMode(m_controller.m_configuration.m_intensityMode); From 2e4545d2890e1fa14600842ecdb1cd6ee2d67422 Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Mon, 3 May 2021 10:01:20 -0700 Subject: [PATCH 037/185] Fix iOS Crash --- .../ImguiAtom/Code/Source/DebugConsole.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Gems/AtomLyIntegration/ImguiAtom/Code/Source/DebugConsole.cpp b/Gems/AtomLyIntegration/ImguiAtom/Code/Source/DebugConsole.cpp index 49ed813ed8..8ae7c30c6a 100644 --- a/Gems/AtomLyIntegration/ImguiAtom/Code/Source/DebugConsole.cpp +++ b/Gems/AtomLyIntegration/ImguiAtom/Code/Source/DebugConsole.cpp @@ -126,7 +126,12 @@ namespace AZ SetFilter(inputFilter); // Bind our custom log handler. - AZ::Interface::Get()->BindLogHandler(m_logHandler); + AZ::ILogger* loggerInstance = AZ::Interface::Get(); + AZ_Assert(loggerInstance, "Failed to get ILogger instance. Log handler not bound.") + if (loggerInstance) + { + loggerInstance->BindLogHandler(m_logHandler); + } // Connect to receive render tick events. auto atomViewportRequests = AZ::Interface::Get(); From f6479aca98f14b1d371fa438903cc6fdedf54898 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Mon, 3 May 2021 11:37:08 -0700 Subject: [PATCH 038/185] Fixed ATOM-15434 "Decal + POM (Grey outline issue)" Made sure the depth and shadow shaders enable parallax calculations when alpha clipping is enabled (instead of only when parallax POM is enabled). Moved the alpha calculations to be *after* the parallax calculations. Factored out ShouldHandleParallax() and ShouldHandleParallaxInDepthShaders() utility functions, which help us ensure consistent application of parallax calculations across the various shaders in each material type. Removed some dead code in a couple shaders where dirToCamera was calculated but not used. Also did ATOM-15034 "Remove Opacity From Multi-Layer Material Types For Now" rather than addressing whatever additional alpha cutout issues might be present on multilayer materials. Testing: AtomSampleViewer full test suite. Added a new AtomSampleViewer screenshot test for alpha clipping with parallax (separate repo). Addional testing of relevant properties in Matirial Editor. Tested updated StandardMultilayerPBR in Editor.exe where I had shadows and clipping against other geometry. --- .../Materials/Types/EnhancedPBR_Common.azsli | 17 +++ .../Types/EnhancedPBR_DepthPass_WithPS.azsl | 20 ++-- .../Types/EnhancedPBR_ForwardPass.azsl | 10 +- .../Types/EnhancedPBR_Shadowmap_WithPS.azsl | 34 ++---- .../Types/StandardMultilayerPBR.materialtype | 106 +----------------- .../Types/StandardMultilayerPBR_Common.azsli | 27 ++++- ...tandardMultilayerPBR_DepthPass_WithPS.azsl | 15 +-- .../StandardMultilayerPBR_ForwardPass.azsl | 51 +++------ .../StandardMultilayerPBR_ShaderEnable.lua | 39 +++++++ ...tandardMultilayerPBR_Shadowmap_WithPS.azsl | 17 +-- .../Materials/Types/StandardPBR_Common.azsli | 16 +++ .../Types/StandardPBR_DepthPass_WithPS.azsl | 18 ++- .../Types/StandardPBR_ForwardPass.azsl | 10 +- .../Types/StandardPBR_Shadowmap_WithPS.azsl | 32 ++---- 14 files changed, 167 insertions(+), 245 deletions(-) create mode 100644 Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ShaderEnable.lua diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli index fd6961c50d..314f15e8e1 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli @@ -14,6 +14,8 @@ #include #include +#include +#include #include "MaterialInputs/BaseColorInput.azsli" #include "MaterialInputs/RoughnessInput.azsli" @@ -107,3 +109,18 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } + +COMMON_OPTIONS_PARALLAX() + +bool ShouldHandleParallax() +{ + // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scattering is enabled. + return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap; +} + +bool ShouldHandleParallaxInDepthShaders() +{ + // The depth pass shaders need to calculate parallax when the result could affect the depth buffer, or when + // parallax could affect texel clipping. + return ShouldHandleParallax() && (o_parallax_enablePixelDepthOffset || o_opacity_mode == OpacityMode::Cutout); +} diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl index 5d6c0fafd8..1aeed26697 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_DepthPass_WithPS.azsl @@ -11,7 +11,6 @@ */ #include -#include #include "./EnhancedPBR_Common.azsli" #include #include @@ -56,7 +55,7 @@ VSDepthOutput MainVS(VSInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -75,15 +74,9 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Clip Alpha - float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + + if(ShouldHandleParallaxInDepthShaders()) { // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; @@ -97,5 +90,12 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } + + // Clip Alpha + float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; + float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; + float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); + CheckClipping(alpha, MaterialSrg::m_opacityFactor); + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index 7d50cbf69b..09a16556d6 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -26,8 +26,8 @@ COMMON_OPTIONS_NORMAL() COMMON_OPTIONS_CLEAR_COAT() COMMON_OPTIONS_OCCLUSION() COMMON_OPTIONS_EMISSIVE() -COMMON_OPTIONS_PARALLAX() COMMON_OPTIONS_DETAIL_MAPS() +// Note COMMON_OPTIONS_PARALLAX is in StandardPBR_Common.azsli because it's needed by all StandardPBR shaders. // Alpha #include "MaterialInputs/AlphaInput.azsli" @@ -67,7 +67,6 @@ struct VSOutput float2 m_detailUv[UvSetCount] : UV3; }; -#include #include #include @@ -88,8 +87,11 @@ VSOutput EnhancedPbr_ForwardPassVS(VSInput IN) // but we would need to address how it works with the parallax code below that indexes into the m_detailUV array. OUT.m_detailUv[0] = mul(MaterialSrg::m_detailUvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_detailUv[1] = mul(MaterialSrg::m_detailUvMatrix, float3(IN.m_uv1, 1.0)).xy; + + // Shadow coords will be calculated in the pixel shader in this case + bool skipShadowCoords = ShouldHandleParallax() && o_parallax_enablePixelDepthOffset; - VertexHelper(IN, OUT, worldPosition, o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset); + VertexHelper(IN, OUT, worldPosition, skipShadowCoords); return OUT; } @@ -119,7 +121,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float bool displacementIsClipped = false; // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled - if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap) + if(ShouldHandleParallax()) { // GetParallaxInput applies an tangent offset to the UV. We want to apply the same offset to the detailUv (note: this needs to be tested with content) // The math is: offset = newUv - oldUv; detailUv += offset; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl index e344886c4b..70b3f51804 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Shadowmap_WithPS.azsl @@ -13,7 +13,6 @@ #include #include #include "EnhancedPBR_Common.azsli" -#include #include #include #include @@ -55,8 +54,8 @@ VertexOutput MainVS(VertexInput IN) // By design, only UV0 is allowed to apply transforms. OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -76,27 +75,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Clip Alpha - float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - - float3 dirToCamera; - if(ViewSrg::m_projectionMatrix[0].w) - { - // orthographic projection (directional light) - // No view position, use light direction - dirToCamera = ViewSrg::m_viewMatrix[2].xyz; - } - else - { - dirToCamera = ViewSrg::m_worldPosition.xyz - IN.m_worldPosition; - } - - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + + if(ShouldHandleParallaxInDepthShaders()) { static const float ShadowMapDepthBias = 0.000001; @@ -114,5 +95,12 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) OUT.m_depth += ShadowMapDepthBias; } + + // Clip Alpha + float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; + float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; + float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); + CheckClipping(alpha, MaterialSrg::m_opacityFactor); + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index 7610a4c9db..780a055c78 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -18,11 +18,6 @@ "displayName": "Parallax Settings", "description": "Properties for configuring the parallax effect, applied to all layers." }, - { - "id": "opacity", - "displayName": "Opacity", - "description": "Properties for configuring the materials transparency." - }, { "id": "uv", "displayName": "UVs", @@ -410,73 +405,6 @@ } } ], - "opacity": [ - { - "id": "mode", - "displayName": "Opacity Mode", - "description": "Opacity mode for this texture.", - "type": "Enum", - "enumValues": [ "Opaque", "Cutout", "Blended" ], - "defaultValue": "Opaque", - "connection": { - "type": "ShaderOption", - "id": "o_opacity_mode" - } - }, - { - "id": "alphaSource", - "displayName": "Alpha Source", - "description": "Source texture of alpha value.", - "type": "Enum", - "enumValues": [ "Packed", "Split", "None" ], - "defaultValue": "Packed", - "connection": { - "type": "ShaderOption", - "id": "o_opacity_source" - } - }, - { - "id": "textureMap", - "displayName": "Texture Map", - "description": "Texture map for defining surface opacity.", - "type": "Image", - "connection": { - "type": "ShaderInput", - "id": "m_opacityMap" - } - }, - { - "id": "textureMapUv", - "displayName": "UV", - "description": "Opacity texture map UV set", - "type": "Enum", - "enumIsUv": true, - "defaultValue": "Tiled", - "connection": { - "type": "ShaderInput", - "id": "m_opacityMapUvIndex" - } - }, - { - "id": "factor", - "displayName": "Factor", - "description": "Factor for cutout threshold and blending", - "type": "Float", - "min": 0.0, - "max": 1.0, - "defaultValue": 0.5, - "connection": { - "type": "ShaderInput", - "id": "m_opacityFactor" - } - }, - { - "id": "doubleSided", - "displayName": "Double-sided", - "description": "Whether to render back-faces or just front-faces.", - "type": "Bool" - } - ], "uv": [ { "id": "center", @@ -2851,16 +2779,7 @@ { "file": "Shaders/MotionVector/SkinnedMeshMotionVector.shader", "tag": "SkinnedMeshMotionVector" - }, - // Used by the light culling system to produce accurate depth bounds for this object when it uses blended transparency - { - "file": "Shaders/Depth/DepthPassTransparentMin.shader", - "tag": "DepthPassTransparentMin" - }, - { - "file": "Shaders/Depth/DepthPassTransparentMax.shader", - "tag": "DepthPassTransparentMax" - } + } ], "functors": [ //############################################################################################## @@ -2885,7 +2804,7 @@ { "type": "Lua", "args": { - "file": "StandardPBR_ShaderEnable.lua" + "file": "StandardMultilayerPBR_ShaderEnable.lua" } }, { @@ -2925,27 +2844,6 @@ "file": "StandardPBR_SubsurfaceState.lua" } }, - { - "type": "Lua", - "args": { - "file": "StandardPBR_HandleOpacityDoubleSided.lua" - } - }, - { - "type": "OverrideDrawList", - "args": { - "triggerProperty": "opacity.mode", - "triggerValue": "Blended", - "shaderIndex": 1, - "drawList": "transparent" - } - }, - { - "type": "Lua", - "args": { - "file": "StandardPBR_HandleOpacityMode.lua" - } - }, //############################################################################################## // Layer 1 Functors //############################################################################################## diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli index db3ec45e0c..93cf9fdb7c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli @@ -14,6 +14,7 @@ #include #include +#include #include "MaterialInputs/BaseColorInput.azsli" #include "MaterialInputs/RoughnessInput.azsli" @@ -26,6 +27,8 @@ #include "MaterialInputs/ParallaxInput.azsli" #include "MaterialInputs/UvSetCount.azsli" +// ------ ShaderResourceGroup ---------------------------------------- + #define DEFINE_LAYER_SRG_INPUTS(prefix) \ COMMON_SRG_INPUTS_BASE_COLOR(prefix) \ COMMON_SRG_INPUTS_ROUGHNESS(prefix) \ @@ -64,10 +67,6 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial float3x3 m_uvMatrixInverse; float4 m_pad5; // [GFX TODO][ATOM-14595] This is a workaround for a data stomping bug. Remove once it's fixed. - float m_opacityFactor; - Texture2D m_opacityMap; - uint m_opacityMapUvIndex; - Sampler m_sampler { AddressU = Wrap; @@ -109,6 +108,8 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial uint m_transmissionThicknessMapUvIndex; } +// ------ Shader Options ---------------------------------------- + enum class DebugDrawMode { None, BlendMaskValues, DepthMaps }; option DebugDrawMode o_debugDrawMode; @@ -121,6 +122,8 @@ option BlendMaskSource o_blendSource; // [GFX TODO][ATOM-14475]: Come up with a more elegant way to associate the isBound flag with the input stream. option bool o_blendMask_isBound; +// ------ Blend Utilities ---------------------------------------- + //! Returns the BlendMaskSource that will actually be used when rendering (not necessarily the same BlendMaskSource specified by the user) BlendMaskSource GetFinalBlendMaskSource() { @@ -181,6 +184,22 @@ float3 BlendLayers(float3 layer1, float3 layer2, float3 layer3, float3 blendMask return layer1 * blendMaskValues.r + layer2 * blendMaskValues.g + layer3 * blendMaskValues.b; } +// ------ Parallax Utilities ---------------------------------------- + +bool ShouldHandleParallax() +{ + // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scattering is enabled. + // Also, all the debug draw modes avoid parallax (they early-return before parallax code actually) so you can see exactly where the various maps appear on the surface UV space. + return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_debugDrawMode == DebugDrawMode::None; +} + +bool ShouldHandleParallaxInDepthShaders() +{ + // The depth pass shaders need to calculate parallax when the result could affect the depth buffer (or when + // parallax could affect texel clipping but we don't have alpha/clipping support in multilayer PBR). + return ShouldHandleParallax() && o_parallax_enablePixelDepthOffset; +} + // These static values are used to pass extra data to the GetDepth callback function during the parallax depth search. static float3 s_blendMaskFromVertexStream; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl index 8e25292e9c..bc8045f412 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl @@ -11,12 +11,10 @@ */ #include -#include #include #include #include -#include "MaterialInputs/AlphaInput.azsli" #include "MaterialInputs/ParallaxInput.azsli" @@ -72,7 +70,7 @@ VSDepthOutput MainVS(VSInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -101,18 +99,9 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Alpha - float2 layer1_baseColorUV = IN.m_uv[MaterialSrg::m_layer1_m_baseColorMapUvIndex]; - float2 layer2_baseColorUV = IN.m_uv[MaterialSrg::m_layer2_m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - // [GFX TODO][ATOM-14589] Figure out how to deal with opacity, instead of just hard-coding to layer1 - float alpha = SampleAlpha(MaterialSrg::m_layer1_m_baseColorMap, MaterialSrg::m_opacityMap, layer1_baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - if(o_debugDrawMode == DebugDrawMode::None && o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl index 05a40d0f9d..3f49152c1c 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -42,7 +42,6 @@ DEFINE_LAYER_OPTIONS(o_layer1_) DEFINE_LAYER_OPTIONS(o_layer2_) DEFINE_LAYER_OPTIONS(o_layer3_) -#include "MaterialInputs/AlphaInput.azsli" #include "MaterialInputs/SubsurfaceInput.azsli" #include "MaterialInputs/TransmissionInput.azsli" #include "StandardMultilayerPBR_Common.azsli" @@ -83,7 +82,7 @@ struct VSOutput float3 m_blendMask : UV7; }; -#include +#include // TODO: Remove this after OpacityMode is removed from LightingModel #include #include @@ -107,9 +106,8 @@ VSOutput ForwardPassVS(VSInput IN) OUT.m_blendMask = float3(1,1,1); } - // We can skip per-vertex shadow coords when parallax is enabled because we need to calculate per-pixel shadow coords anyway. - // We cannot skip shadow coords when o_debugDrawMode is on because some debug draw modes return before parallax. - bool skipShadowCoords = o_debugDrawMode == DebugDrawMode::None && o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset; + // Shadow coords will be calculated in the pixel shader in this case + bool skipShadowCoords = ShouldHandleParallax() && o_parallax_enablePixelDepthOffset; VertexHelper(IN, OUT, worldPosition, skipShadowCoords); return OUT; @@ -157,7 +155,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Parallax ------- // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled - if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled) + if(ShouldHandleParallax()) { GetDepth_Setup(IN.m_blendMask); @@ -199,15 +197,6 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // Now that any parallax has been calculated, we calculate the blend factors for any layers that are impacted by the parallax. float3 blendMaskValues = GetBlendMaskValues(IN.m_uv[MaterialSrg::m_blendMaskUvIndex], IN.m_blendMask); - // ------- Alpha & Clip ------- - - float2 layer1_baseColorUv = uvLayer1[MaterialSrg::m_layer1_m_baseColorMapUvIndex]; - float2 layer2_baseColorUv = uvLayer2[MaterialSrg::m_layer2_m_baseColorMapUvIndex]; - float2 layer3_baseColorUv = uvLayer3[MaterialSrg::m_layer3_m_baseColorMapUvIndex]; - float2 opacityUv = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - // [GFX TODO][ATOM-14589] Figure out how to deal with opacity, instead of just hard-coding to layer1 - float alpha = GetAlphaInputAndClip(MaterialSrg::m_layer1_m_baseColorMap, MaterialSrg::m_opacityMap, layer1_baseColorUv, opacityUv, MaterialSrg::m_sampler, MaterialSrg::m_opacityFactor, o_opacity_source); - // ------- Normal ------- float3 layer1_normalFactor = MaterialSrg::m_layer1_m_normalFactor * blendMaskValues.r; @@ -226,6 +215,10 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 normalWS = normalize(TangentSpaceToWorld(normalTS, IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex])); // ------- Base Color ------- + + float2 layer1_baseColorUv = uvLayer1[MaterialSrg::m_layer1_m_baseColorMapUvIndex]; + float2 layer2_baseColorUv = uvLayer2[MaterialSrg::m_layer2_m_baseColorMapUvIndex]; + float2 layer3_baseColorUv = uvLayer3[MaterialSrg::m_layer3_m_baseColorMapUvIndex]; float3 layer1_sampledColor = GetBaseColorInput(MaterialSrg::m_layer1_m_baseColorMap, MaterialSrg::m_sampler, layer1_baseColorUv, MaterialSrg::m_layer1_m_baseColor.rgb, o_layer1_o_baseColor_useTexture); float3 layer2_sampledColor = GetBaseColorInput(MaterialSrg::m_layer2_m_baseColorMap, MaterialSrg::m_sampler, layer2_baseColorUv, MaterialSrg::m_layer2_m_baseColor.rgb, o_layer2_o_baseColor_useTexture); @@ -352,34 +345,18 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float // ------- Lighting Calculation ------- const float2 anisotropy = 0.0; // Does not affect calculations unless 'o_enableAnisotropy' is enabled + const float alpha = 1.0; PbrLightingOutput lightingOutput = PbrLighting(IN, baseColor, metallic, roughness, specularF0Factor, normalWS, tangents[0], bitangents[0], anisotropy, - emissive, diffuseAmbientOcclusion, specularOcclusion, transmissionTintThickness, MaterialSrg::m_transmissionParams, clearCoatFactor, clearCoatRoughness, clearCoatNormal, alpha, o_opacity_mode); - - // ------- Opacity ------- + emissive, diffuseAmbientOcclusion, specularOcclusion, transmissionTintThickness, MaterialSrg::m_transmissionParams, clearCoatFactor, clearCoatRoughness, clearCoatNormal, alpha, OpacityMode::Opaque); - if (o_opacity_mode == OpacityMode::Blended) - { - // [GFX_TODO ATOM-13187] PbrLighting shouldn't be writing directly to render targets. It's confusing when - // specular is being added to diffuse just because we're calling render target 0 "diffuse". - - // For blended mode, we do (dest * alpha) + (source * 1.0). This allows the specular - // to be added on top of the diffuse, but then the diffuse must be pre-multiplied. - // It's done this way because surface transparency doesn't really change specular response (eg, glass). - lightingOutput.m_diffuseColor.rgb *= lightingOutput.m_diffuseColor.w; // pre-multiply diffuse - lightingOutput.m_diffuseColor.rgb += lightingOutput.m_specularColor.rgb; // add specular - } - else - { - // Pack factor and quality, drawback: because of precision limit of float16 cannot represent exact 1, maximum representable value is 0.9961 - uint factorAndQuality = dot(round(float2(saturate(surfaceScatteringFactor), MaterialSrg::m_subsurfaceScatteringQuality) * 255), float2(256, 1)); - lightingOutput.m_diffuseColor.w = factorAndQuality * (o_enableSubsurfaceScattering ? 1.0 : -1.0); - lightingOutput.m_scatterDistance = MaterialSrg::m_scatterDistance; - } + // Pack factor and quality, drawback: because of precision limit of float16 cannot represent exact 1, maximum representable value is 0.9961 + uint factorAndQuality = dot(round(float2(saturate(surfaceScatteringFactor), MaterialSrg::m_subsurfaceScatteringQuality) * 255), float2(256, 1)); + lightingOutput.m_diffuseColor.w = factorAndQuality * (o_enableSubsurfaceScattering ? 1.0 : -1.0); + lightingOutput.m_scatterDistance = MaterialSrg::m_scatterDistance; - return lightingOutput; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ShaderEnable.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ShaderEnable.lua new file mode 100644 index 0000000000..69df610ab2 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ShaderEnable.lua @@ -0,0 +1,39 @@ +-------------------------------------------------------------------------------------- +-- +-- 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. +-- +-- +---------------------------------------------------------------------------------------------------- + +function GetMaterialPropertyDependencies() + return {"parallax.enable", "parallax.pdo"} +end + +function Process(context) + local parallaxEnabled = context:GetMaterialPropertyValue_bool("parallax.enable") + local parallaxPdoEnabled = context:GetMaterialPropertyValue_bool("parallax.pdo") + + local depthPass = context:GetShaderByTag("DepthPass") + local shadowMap = context:GetShaderByTag("Shadowmap") + local forwardPassEDS = context:GetShaderByTag("ForwardPass_EDS") + local depthPassWithPS = context:GetShaderByTag("DepthPass_WithPS") + local shadowMapWitPS = context:GetShaderByTag("Shadowmap_WithPS") + local forwardPass = context:GetShaderByTag("ForwardPass") + + local shadingAffectsDepth = parallaxEnabled and parallaxPdoEnabled; + + depthPass:SetEnabled(not shadingAffectsDepth) + shadowMap:SetEnabled(not shadingAffectsDepth) + forwardPassEDS:SetEnabled(not shadingAffectsDepth) + + depthPassWithPS:SetEnabled(shadingAffectsDepth) + shadowMapWitPS:SetEnabled(shadingAffectsDepth) + forwardPass:SetEnabled(shadingAffectsDepth) +end diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl index 0c9c186a11..6fa721ef47 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl @@ -12,12 +12,10 @@ #include #include -#include #include #include #include -#include "MaterialInputs/AlphaInput.azsli" #include "MaterialInputs/ParallaxInput.azsli" #include "MaterialInputs/ParallaxInput.azsli" @@ -71,7 +69,7 @@ VertexOutput MainVS(VertexInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -100,18 +98,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Alpha - float2 layer1_baseColorUV = IN.m_uv[MaterialSrg::m_layer1_m_baseColorMapUvIndex]; - float2 layer2_baseColorUV = IN.m_uv[MaterialSrg::m_layer2_m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - // [GFX TODO][ATOM-14589] Figure out how to deal with opacity, instead of just hard-coding to layer1 - float alpha = SampleAlpha(MaterialSrg::m_layer1_m_baseColorMap, MaterialSrg::m_opacityMap, layer1_baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - if(o_debugDrawMode == DebugDrawMode::None && o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; @@ -132,6 +121,6 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) OUT.m_depth = depth; } - + return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli index 70137a88c1..ee1533cf16 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli @@ -14,6 +14,8 @@ #include #include +#include +#include #include "MaterialInputs/BaseColorInput.azsli" #include "MaterialInputs/RoughnessInput.azsli" @@ -97,3 +99,17 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } +COMMON_OPTIONS_PARALLAX() + +bool ShouldHandleParallax() +{ + // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scattering is enabled. + return !o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap; +} + +bool ShouldHandleParallaxInDepthShaders() +{ + // The depth pass shaders need to calculate parallax when the result could affect the depth buffer, or when + // parallax could affect texel clipping. + return ShouldHandleParallax() && (o_parallax_enablePixelDepthOffset || o_opacity_mode == OpacityMode::Cutout); +} diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl index 3c04e9b391..5d0498dbe9 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_DepthPass_WithPS.azsl @@ -11,7 +11,6 @@ */ #include -#include #include "./StandardPBR_Common.azsli" #include #include @@ -57,7 +56,7 @@ VSDepthOutput MainVS(VSInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -76,16 +75,9 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Alpha - float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { // We support two UV streams, but only a single stream of tangent/bitangent. So for UV[1+] we generated the tangent/bitangent in screen-space. float3 tangents[UvSetCount] = { IN.m_tangent.xyz, float3(0, 0, 0) }; @@ -99,7 +91,13 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, OUT.m_depth); } + + // Alpha + float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; + float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; + float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); + CheckClipping(alpha, MaterialSrg::m_opacityFactor); return OUT; } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index d55b865a27..4d12eb181d 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -26,7 +26,7 @@ COMMON_OPTIONS_NORMAL() COMMON_OPTIONS_CLEAR_COAT() COMMON_OPTIONS_OCCLUSION() COMMON_OPTIONS_EMISSIVE() -COMMON_OPTIONS_PARALLAX() +// Note COMMON_OPTIONS_PARALLAX is in StandardPBR_Common.azsli because it's needed by all StandardPBR shaders. // Alpha #include "MaterialInputs/AlphaInput.azsli" @@ -66,7 +66,6 @@ struct VSOutput float2 m_uv[UvSetCount] : UV1; }; -#include #include #include @@ -80,7 +79,10 @@ VSOutput StandardPbr_ForwardPassVS(VSInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - VertexHelper(IN, OUT, worldPosition, o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset); + // Shadow coords will be calculated in the pixel shader in this case + bool skipShadowCoords = ShouldHandleParallax() && o_parallax_enablePixelDepthOffset; + + VertexHelper(IN, OUT, worldPosition, skipShadowCoords); return OUT; } @@ -110,7 +112,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float bool displacementIsClipped = false; // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled - if(!o_enableSubsurfaceScattering && o_parallax_feature_enabled && o_useDepthMap) + if(ShouldHandleParallax()) { float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl index 8f33b4cec6..cad951b5b5 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Shadowmap_WithPS.azsl @@ -13,7 +13,6 @@ #include #include #include "StandardPBR_Common.azsli" -#include #include #include #include @@ -57,7 +56,7 @@ VertexOutput MainVS(VertexInput IN) OUT.m_uv[0] = mul(MaterialSrg::m_uvMatrix, float3(IN.m_uv0, 1.0)).xy; OUT.m_uv[1] = IN.m_uv1; - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { OUT.m_worldPosition = worldPosition.xyz; @@ -77,28 +76,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) { PSDepthOutput OUT; - // Alpha - float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; - float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; - float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); - - CheckClipping(alpha, MaterialSrg::m_opacityFactor); - OUT.m_depth = IN.m_position.z; - float3 dirToCamera; - if(ViewSrg::m_projectionMatrix[0].w) - { - // orthographic projection (directional light) - // No view position, use light direction - dirToCamera = ViewSrg::m_viewMatrix[2].xyz; - } - else - { - dirToCamera = ViewSrg::m_worldPosition.xyz - IN.m_worldPosition; - } - - if(o_parallax_feature_enabled && o_parallax_enablePixelDepthOffset) + if(ShouldHandleParallaxInDepthShaders()) { static const float ShadowMapDepthBias = 0.000001; @@ -116,5 +96,13 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) OUT.m_depth += ShadowMapDepthBias; } + + // Alpha + float2 baseColorUV = IN.m_uv[MaterialSrg::m_baseColorMapUvIndex]; + float2 opacityUV = IN.m_uv[MaterialSrg::m_opacityMapUvIndex]; + float alpha = SampleAlpha(MaterialSrg::m_baseColorMap, MaterialSrg::m_opacityMap, baseColorUV, opacityUV, MaterialSrg::m_sampler, o_opacity_source); + + CheckClipping(alpha, MaterialSrg::m_opacityFactor); + return OUT; } From 9292d2e63f4121c9986d7c01481257d67e3177cb Mon Sep 17 00:00:00 2001 From: guthadam Date: Mon, 3 May 2021 13:43:34 -0500 Subject: [PATCH 039/185] LYN-3133 Adding material editor asset path dependencies to Automated Testing project Some of these changes may not be necessary but comparing against the Atom Test project https://jira.agscollab.com/browse/LYN-3133 --- AutomatedTesting/Registry/assets_scan_folders.setreg | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/AutomatedTesting/Registry/assets_scan_folders.setreg b/AutomatedTesting/Registry/assets_scan_folders.setreg index 5394d381a3..91061f3337 100644 --- a/AutomatedTesting/Registry/assets_scan_folders.setreg +++ b/AutomatedTesting/Registry/assets_scan_folders.setreg @@ -38,6 +38,13 @@ "Gems/PrimitiveAssets" ] }, + "MaterialEditor": + { + "SourcePaths": + [ + "Gems/Atom/Tools/MaterialEditor" + ] + }, "UiBasics": { "SourcePaths": From 954e158454edf141ae8b4e2e11dacfc993fe1576 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 3 May 2021 15:21:27 -0400 Subject: [PATCH 040/185] Adding nullptr checks in Gems/ for Get3DEngine() --- .../Editor/Source/Components/EditorSystemComponent.cpp | 2 +- .../Code/Source/EditorOccluderAreaComponent.cpp | 4 ++-- Gems/Visibility/Code/Source/EditorPortalComponent.cpp | 9 ++++++--- Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp | 9 ++++++--- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp index 516b958adb..10b824b127 100644 --- a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp +++ b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp @@ -48,7 +48,7 @@ namespace PhysX AzToolsFramework::EditorRequests::Bus::BroadcastResult(editor, &AzToolsFramework::EditorRequests::GetEditor); ISurfaceTypeEnumerator* surfaceTypeEnumerator = nullptr; - if (editor) + if (editor && editor->Get3DEngine()) { surfaceTypeEnumerator = editor->Get3DEngine()->GetMaterialManager()->GetSurfaceTypeManager()->GetEnumerator(); } diff --git a/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.cpp b/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.cpp index 9a88799a31..a4065b711f 100644 --- a/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.cpp +++ b/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.cpp @@ -161,7 +161,7 @@ namespace Visibility EditorOccluderAreaComponent::~EditorOccluderAreaComponent() { - if (m_area) + if (m_area && GetIEditor()->Get3DEngine()) { GetIEditor()->Get3DEngine()->DeleteVisArea(m_area); m_area = nullptr; @@ -220,7 +220,7 @@ namespace Visibility /// Configuration are set. void EditorOccluderAreaComponent::UpdateOccluderAreaObject() { - if (m_area) + if (m_area && GetIEditor()->Get3DEngine()) { AZStd::array verts; diff --git a/Gems/Visibility/Code/Source/EditorPortalComponent.cpp b/Gems/Visibility/Code/Source/EditorPortalComponent.cpp index 4e1b07991a..d33828514b 100644 --- a/Gems/Visibility/Code/Source/EditorPortalComponent.cpp +++ b/Gems/Visibility/Code/Source/EditorPortalComponent.cpp @@ -209,7 +209,7 @@ namespace Visibility EditorPortalComponent::~EditorPortalComponent() { - if (m_area) + if (m_area && GetIEditor()->Get3DEngine()) { // reset the listener vis area in the unlucky case that we are deleting the // vis area where the listener is currently in @@ -232,7 +232,7 @@ namespace Visibility // This means that dynamic slices cannot effectively contain vis-areas until we fix the core rendering system to allow that. const auto visGUID = static_cast(entityId); - if(!m_area && GetIEditor()) + if(!m_area && GetIEditor() && GetIEditor()->Get3DEngine()) { m_area = GetIEditor()->Get3DEngine()->CreateVisArea(visGUID); } @@ -453,7 +453,10 @@ namespace Visibility verts[i] = m_cryCachedWorldTransform.TransformPoint(verts[i]); } - GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &verts[0], verts.size(), name.c_str(), info, true); + if (GetIEditor()->Get3DEngine()) + { + GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &verts[0], verts.size(), name.c_str(), info, true); + } AzFramework::EntityBoundsUnionRequestBus::Broadcast( &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); diff --git a/Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp b/Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp index 48045d9023..fcf2241cd3 100644 --- a/Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp +++ b/Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp @@ -188,7 +188,7 @@ namespace Visibility EditorVisAreaComponent::~EditorVisAreaComponent() { - if (m_area) + if (m_area && GetIEditor()->Get3DEngine()) { // Reset the listener vis area in the unlucky case that we are deleting the // vis area where the listener is currently in @@ -209,7 +209,7 @@ namespace Visibility // This means that dynamic slices cannot effectively contain vis areas until we fix the core rendering system to allow that. const auto visGUID = AZ::u64(entityId); - if(!m_area && GetIEditor()) + if(!m_area && GetIEditor() && GetIEditor()->Get3DEngine()) { m_area = GetIEditor()->Get3DEngine()->CreateVisArea(visGUID); } @@ -347,7 +347,10 @@ namespace Visibility const AZStd::string name = AZStd::string("vis-area_") + GetEntity()->GetName(); - GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &points[0], points.size(), name.c_str(), info, true); + if (GetIEditor()->Get3DEngine()) + { + GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &points[0], points.size(), name.c_str(), info, true); + } AzFramework::EntityBoundsUnionRequestBus::Broadcast( &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); From cc4712aa2592320495093024a28a85b7b960fcdf Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 3 May 2021 15:37:16 -0400 Subject: [PATCH 041/185] Deleted Visibility gem, it was Cry only gem --- Gems/CMakeLists.txt | 1 - .../Components/EditorSystemComponent.cpp | 5 - .../Disabled/OccluderArea_white.png | 3 - .../Components/Disabled/Portal_white.png | 3 - .../Components/Disabled/VisArea_white.png | 3 - .../Editor/Icons/Components/OccluderArea.svg | 15 - .../Assets/Editor/Icons/Components/Portal.svg | 15 - .../Components/Viewport/OccluderArea.png | 3 - .../Icons/Components/Viewport/Portal.png | 3 - .../Icons/Components/Viewport/VisArea.png | 3 - .../Editor/Icons/Components/VisArea.svg | 15 - Gems/Visibility/CMakeLists.txt | 12 - Gems/Visibility/Code/CMakeLists.txt | 105 --- .../Include/EditorOccluderAreaComponentBus.h | 54 -- .../Code/Include/EditorPortalComponentBus.h | 60 -- .../Code/Include/EditorVisAreaComponentBus.h | 66 -- .../Code/Include/OccluderAreaComponentBus.h | 37 - .../Code/Include/PortalComponentBus.h | 43 - .../Code/Include/VisAreaComponentBus.h | 38 - .../Source/EditorOccluderAreaComponent.cpp | 437 ---------- .../Code/Source/EditorOccluderAreaComponent.h | 129 --- .../EditorOccluderAreaComponentMode.cpp | 85 -- .../Source/EditorOccluderAreaComponentMode.h | 53 -- .../Code/Source/EditorPortalComponent.cpp | 788 ------------------ .../Code/Source/EditorPortalComponent.h | 148 ---- .../Code/Source/EditorPortalComponentMode.cpp | 85 -- .../Code/Source/EditorPortalComponentMode.h | 53 -- .../Code/Source/EditorVisAreaComponent.cpp | 632 -------------- .../Code/Source/EditorVisAreaComponent.h | 144 ---- .../Source/EditorVisAreaComponentMode.cpp | 120 --- .../Code/Source/EditorVisAreaComponentMode.h | 58 -- .../Code/Source/OccluderAreaComponent.cpp | 115 --- .../Code/Source/OccluderAreaComponent.h | 79 -- .../Code/Source/PortalComponent.cpp | 182 ---- Gems/Visibility/Code/Source/PortalComponent.h | 92 -- .../Code/Source/VisAreaComponent.cpp | 137 --- .../Visibility/Code/Source/VisAreaComponent.h | 79 -- Gems/Visibility/Code/Source/VisibilityGem.cpp | 39 - Gems/Visibility/Code/Source/VisibilityGem.h | 27 - .../Code/Source/Visibility_precompiled.cpp | 12 - .../Code/Source/Visibility_precompiled.h | 19 - Gems/Visibility/Code/Tests/VisibilityTest.cpp | 184 ---- .../Code/visibility_editor_files.cmake | 22 - .../Code/visibility_editor_shared_files.cmake | 21 - .../Code/visibility_editor_tests_files.cmake | 22 - Gems/Visibility/Code/visibility_files.cmake | 24 - .../Code/visibility_shared_files.cmake | 15 - Gems/Visibility/gem.json | 13 - Gems/Visibility/preview.png | 3 - 49 files changed, 4301 deletions(-) delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/Disabled/OccluderArea_white.png delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/Disabled/Portal_white.png delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/Disabled/VisArea_white.png delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/OccluderArea.svg delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/Portal.svg delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/Viewport/OccluderArea.png delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/Viewport/Portal.png delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/Viewport/VisArea.png delete mode 100644 Gems/Visibility/Assets/Editor/Icons/Components/VisArea.svg delete mode 100644 Gems/Visibility/CMakeLists.txt delete mode 100644 Gems/Visibility/Code/CMakeLists.txt delete mode 100644 Gems/Visibility/Code/Include/EditorOccluderAreaComponentBus.h delete mode 100644 Gems/Visibility/Code/Include/EditorPortalComponentBus.h delete mode 100644 Gems/Visibility/Code/Include/EditorVisAreaComponentBus.h delete mode 100644 Gems/Visibility/Code/Include/OccluderAreaComponentBus.h delete mode 100644 Gems/Visibility/Code/Include/PortalComponentBus.h delete mode 100644 Gems/Visibility/Code/Include/VisAreaComponentBus.h delete mode 100644 Gems/Visibility/Code/Source/EditorOccluderAreaComponent.cpp delete mode 100644 Gems/Visibility/Code/Source/EditorOccluderAreaComponent.h delete mode 100644 Gems/Visibility/Code/Source/EditorOccluderAreaComponentMode.cpp delete mode 100644 Gems/Visibility/Code/Source/EditorOccluderAreaComponentMode.h delete mode 100644 Gems/Visibility/Code/Source/EditorPortalComponent.cpp delete mode 100644 Gems/Visibility/Code/Source/EditorPortalComponent.h delete mode 100644 Gems/Visibility/Code/Source/EditorPortalComponentMode.cpp delete mode 100644 Gems/Visibility/Code/Source/EditorPortalComponentMode.h delete mode 100644 Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp delete mode 100644 Gems/Visibility/Code/Source/EditorVisAreaComponent.h delete mode 100644 Gems/Visibility/Code/Source/EditorVisAreaComponentMode.cpp delete mode 100644 Gems/Visibility/Code/Source/EditorVisAreaComponentMode.h delete mode 100644 Gems/Visibility/Code/Source/OccluderAreaComponent.cpp delete mode 100644 Gems/Visibility/Code/Source/OccluderAreaComponent.h delete mode 100644 Gems/Visibility/Code/Source/PortalComponent.cpp delete mode 100644 Gems/Visibility/Code/Source/PortalComponent.h delete mode 100644 Gems/Visibility/Code/Source/VisAreaComponent.cpp delete mode 100644 Gems/Visibility/Code/Source/VisAreaComponent.h delete mode 100644 Gems/Visibility/Code/Source/VisibilityGem.cpp delete mode 100644 Gems/Visibility/Code/Source/VisibilityGem.h delete mode 100644 Gems/Visibility/Code/Source/Visibility_precompiled.cpp delete mode 100644 Gems/Visibility/Code/Source/Visibility_precompiled.h delete mode 100644 Gems/Visibility/Code/Tests/VisibilityTest.cpp delete mode 100644 Gems/Visibility/Code/visibility_editor_files.cmake delete mode 100644 Gems/Visibility/Code/visibility_editor_shared_files.cmake delete mode 100644 Gems/Visibility/Code/visibility_editor_tests_files.cmake delete mode 100644 Gems/Visibility/Code/visibility_files.cmake delete mode 100644 Gems/Visibility/Code/visibility_shared_files.cmake delete mode 100644 Gems/Visibility/gem.json delete mode 100644 Gems/Visibility/preview.png diff --git a/Gems/CMakeLists.txt b/Gems/CMakeLists.txt index b6bda8c16e..3b630cfd2f 100644 --- a/Gems/CMakeLists.txt +++ b/Gems/CMakeLists.txt @@ -37,7 +37,6 @@ add_subdirectory(MessagePopup) add_subdirectory(PhysX) add_subdirectory(PhysXDebug) add_subdirectory(ScriptEvents) -add_subdirectory(Visibility) add_subdirectory(AssetValidation) add_subdirectory(VirtualGamepad) add_subdirectory(SaveData) diff --git a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp index 10b824b127..05ac4b1363 100644 --- a/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp +++ b/Gems/PhysX/Code/Editor/Source/Components/EditorSystemComponent.cpp @@ -48,11 +48,6 @@ namespace PhysX AzToolsFramework::EditorRequests::Bus::BroadcastResult(editor, &AzToolsFramework::EditorRequests::GetEditor); ISurfaceTypeEnumerator* surfaceTypeEnumerator = nullptr; - if (editor && editor->Get3DEngine()) - { - surfaceTypeEnumerator = editor->Get3DEngine()->GetMaterialManager()->GetSurfaceTypeManager()->GetEnumerator(); - } - if (surfaceTypeEnumerator) { // Enumerate through CryEngine surface types and create a Physics API material for each of them diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/OccluderArea_white.png b/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/OccluderArea_white.png deleted file mode 100644 index 5554bfc38e..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/OccluderArea_white.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:46757cf327aa9ed60ded1f3025140bc065569634f69e5aaba0b83086fa7642e0 -size 786 diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/Portal_white.png b/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/Portal_white.png deleted file mode 100644 index fc72adc85e..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/Portal_white.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:44150d202f318598e939bf29a543b6edaa0d2cf7455989a2d0da916ba7c83384 -size 833 diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/VisArea_white.png b/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/VisArea_white.png deleted file mode 100644 index 48a7af896a..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/Disabled/VisArea_white.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:44570118c315725d13affcc87b0eb4fb01f01cf67f9da0a4e066a347e096a36f -size 757 diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/OccluderArea.svg b/Gems/Visibility/Assets/Editor/Icons/Components/OccluderArea.svg deleted file mode 100644 index aa8840a798..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/OccluderArea.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - icon / Rendering / OccluderArea - Created with Sketch. - - - - - - - - - - diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/Portal.svg b/Gems/Visibility/Assets/Editor/Icons/Components/Portal.svg deleted file mode 100644 index 967a891222..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/Portal.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - icon / Rendering / Portal - Created with Sketch. - - - - - - - - - - diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/OccluderArea.png b/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/OccluderArea.png deleted file mode 100644 index 3e98e852dd..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/OccluderArea.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7288c80d906ec59271ccd4db168d318f4c5b4fd65fca6077acbf4aaeb76b9e24 -size 4081 diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/Portal.png b/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/Portal.png deleted file mode 100644 index b7198e5803..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/Portal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:486816ea8e6cb090f8d78e26d9ed6a73aca8e5d6c5fb6bcb3cb2fff8277053db -size 4687 diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/VisArea.png b/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/VisArea.png deleted file mode 100644 index e2d0c7f803..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/Viewport/VisArea.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:aca391fc79c7b5400465bcdaa3a1c21a0fbb3dd042420b6511ecf568048ee6ec -size 4558 diff --git a/Gems/Visibility/Assets/Editor/Icons/Components/VisArea.svg b/Gems/Visibility/Assets/Editor/Icons/Components/VisArea.svg deleted file mode 100644 index 389f4cf35d..0000000000 --- a/Gems/Visibility/Assets/Editor/Icons/Components/VisArea.svg +++ /dev/null @@ -1,15 +0,0 @@ - - - - icon / Rendering / VisArea - Created with Sketch. - - - - - - - - - - diff --git a/Gems/Visibility/CMakeLists.txt b/Gems/Visibility/CMakeLists.txt deleted file mode 100644 index 20a680bce9..0000000000 --- a/Gems/Visibility/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/Visibility/Code/CMakeLists.txt b/Gems/Visibility/Code/CMakeLists.txt deleted file mode 100644 index c8650eea79..0000000000 --- a/Gems/Visibility/Code/CMakeLists.txt +++ /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. -# - -ly_add_target( - NAME Visibility.Static STATIC - NAMESPACE Gem - FILES_CMAKE - visibility_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Source - PUBLIC - Include - BUILD_DEPENDENCIES - PUBLIC - Legacy::CryCommon -) - -ly_add_target( - NAME Visibility ${PAL_TRAIT_MONOLITHIC_DRIVEN_MODULE_TYPE} - NAMESPACE Gem - FILES_CMAKE - visibility_shared_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Source - PUBLIC - Include - BUILD_DEPENDENCIES - PRIVATE - Gem::Visibility.Static -) - -if(PAL_TRAIT_BUILD_HOST_TOOLS) - - ly_add_target( - NAME Visibility.Editor.Static STATIC - NAMESPACE Gem - FILES_CMAKE - visibility_editor_files.cmake - COMPILE_DEFINITIONS - PUBLIC - VISIBILITY_EDITOR - INCLUDE_DIRECTORIES - PRIVATE - Source - PUBLIC - Include - BUILD_DEPENDENCIES - PUBLIC - Legacy::Editor.Headers - Legacy::EditorCore - AZ::AzToolsFramework - Gem::Visibility.Static - ) - - ly_add_target( - NAME Visibility.Editor GEM_MODULE - - NAMESPACE Gem - FILES_CMAKE - visibility_editor_shared_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Source - PUBLIC - Include - BUILD_DEPENDENCIES - PRIVATE - Gem::Visibility.Editor.Static - ) -endif() - -################################################################################ -# Tests -################################################################################ -if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - if(PAL_TRAIT_BUILD_HOST_TOOLS) - ly_add_target( - NAME Visibility.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE Gem - FILES_CMAKE - visibility_editor_tests_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Tests - Source - BUILD_DEPENDENCIES - PRIVATE - AZ::AzTest - Gem::Visibility.Editor.Static - ) - ly_add_googletest( - NAME Gem::Visibility.Editor.Tests - ) - endif() -endif() diff --git a/Gems/Visibility/Code/Include/EditorOccluderAreaComponentBus.h b/Gems/Visibility/Code/Include/EditorOccluderAreaComponentBus.h deleted file mode 100644 index f2714691cb..0000000000 --- a/Gems/Visibility/Code/Include/EditorOccluderAreaComponentBus.h +++ /dev/null @@ -1,54 +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 "OccluderAreaComponentBus.h" - -namespace Visibility -{ - /// Request bus for the EditorOccluderComponent. - class EditorOccluderAreaRequests - : public OccluderAreaRequests - , public AZ::FixedVertices - { - public: - virtual void SetDisplayFilled(bool displayFilled) = 0; - virtual void SetCullDistRatio(float cullDistRatio) = 0; - virtual void SetUseInIndoors(bool inDoors) = 0; - virtual void SetDoubleSide(bool doubleSided) = 0; - virtual void UpdateOccluderAreaObject() = 0; - - protected: - ~EditorOccluderAreaRequests() = default; - }; - - /// Type to inherit to implement EditorOccluderAreaComponentRequests - using EditorOccluderAreaRequestBus = AZ::EBus; - - /// Editor notification bus for EditorOccluderAreaComponent. - class EditorOccluderAreaNotifications - : public AZ::ComponentBus - { - public: - virtual void OnVerticesChangedInspector() {} - - protected: - ~EditorOccluderAreaNotifications() = default; - }; - - /// Type to inherit to implement EditorOccluderAreaNotifications. - using EditorOccluderAreaNotificationBus = AZ::EBus; - -} // namespace Visibility diff --git a/Gems/Visibility/Code/Include/EditorPortalComponentBus.h b/Gems/Visibility/Code/Include/EditorPortalComponentBus.h deleted file mode 100644 index c4ab43d8a0..0000000000 --- a/Gems/Visibility/Code/Include/EditorPortalComponentBus.h +++ /dev/null @@ -1,60 +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 "PortalComponentBus.h" - -namespace Visibility -{ - /// Request bus for the EditorPortalComponent. - class EditorPortalRequests - : public PortalRequests - , public AZ::FixedVertices - { - public: - virtual void SetHeight(float height) = 0; - virtual void SetDisplayFilled(bool filled) = 0; - virtual void SetAffectedBySun(bool affectedBySun) = 0; - virtual void SetViewDistRatio(float viewDistRatio) = 0; - virtual void SetSkyOnly(bool skyOnly) = 0; - virtual void SetOceanIsVisible(bool oceanVisible) = 0; - virtual void SetUseDeepness(bool useDeepness) = 0; - virtual void SetDoubleSide(bool doubleSided) = 0; - virtual void SetLightBlending(bool lightBending) = 0; - virtual void SetLightBlendValue(float lightBendAmount) = 0; - virtual void UpdatePortalObject() = 0; - - protected: - ~EditorPortalRequests() = default; - }; - - /// Type to inherit to implement EditorPortalComponentRequests - using EditorPortalRequestBus = AZ::EBus; - - /// Editor notification bus for EditorPortalComponent. - class EditorPortalNotifications - : public AZ::ComponentBus - { - public: - virtual void OnVerticesChangedInspector() {} - - protected: - ~EditorPortalNotifications() = default; - }; - - /// Type to inherit to implement EditorPortalNotifications. - using EditorPortalNotificationBus = AZ::EBus; - -} // namespace Visibility diff --git a/Gems/Visibility/Code/Include/EditorVisAreaComponentBus.h b/Gems/Visibility/Code/Include/EditorVisAreaComponentBus.h deleted file mode 100644 index 6803ea77a6..0000000000 --- a/Gems/Visibility/Code/Include/EditorVisAreaComponentBus.h +++ /dev/null @@ -1,66 +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 "VisAreaComponentBus.h" - -namespace Visibility -{ - /// Request bus for the EditorVisAreaComponent. - class EditorVisAreaComponentRequests - : public VisAreaComponentRequests - , public AZ::VariableVertices - { - public: - virtual void SetHeight(float height) = 0; - virtual void SetDisplayFilled(bool filled) = 0; - virtual void SetAffectedBySun(bool affectedBySun) = 0; - virtual void SetViewDistRatio(float viewDistRatio) = 0; - virtual void SetOceanIsVisible(bool oceanVisible) = 0; - virtual void UpdateVisAreaObject() = 0; - }; - - /// Type to inherit to implement EditorVisAreaComponentRequests. - using EditorVisAreaComponentRequestBus = AZ::EBus; - - /// Notification bus for the EditorVisAreaComponent. - class EditorVisAreaComponentNotifications - : public AZ::ComponentBus - , public AZ::VertexContainerNotificationInterface - { - public: - /// Called when a new vertex is added to the vis area. - void OnVertexAdded(size_t /*index*/) override {} - - /// Called when a vertex is removed from the vis area. - void OnVertexRemoved(size_t /*index*/) override {} - - /// Called when a vertex is updated. - void OnVertexUpdated(size_t /*index*/) override {} - - /// Called when all vertices on the vis area are set. - void OnVerticesSet(const AZStd::vector& /*vertices*/) override {} - - /// Called when all vertices are removed from the vis area. - void OnVerticesCleared() override {} - - protected: - ~EditorVisAreaComponentNotifications() = default; - }; - - /// Type to inherit to implement EditorVisAreaComponentNotifications. - using EditorVisAreaComponentNotificationBus = AZ::EBus; - -} // namespace Visibility diff --git a/Gems/Visibility/Code/Include/OccluderAreaComponentBus.h b/Gems/Visibility/Code/Include/OccluderAreaComponentBus.h deleted file mode 100644 index 21b66c14c1..0000000000 --- a/Gems/Visibility/Code/Include/OccluderAreaComponentBus.h +++ /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. -* -*/ - -#pragma once - -#include -#include -#include - -namespace Visibility -{ - /// Request bus for the OccluderAreaComponent. - class OccluderAreaRequests - { - public: - virtual bool GetDisplayFilled() = 0; - virtual float GetCullDistRatio() = 0; - virtual bool GetUseInIndoors() = 0; - virtual bool GetDoubleSide() = 0; - - protected: - ~OccluderAreaRequests() = default; - }; - - /// Type to inherit to implement OccluderAreaRequests. - using OccluderAreaRequestBus = AZ::EBus; - -} // namespace Visibility diff --git a/Gems/Visibility/Code/Include/PortalComponentBus.h b/Gems/Visibility/Code/Include/PortalComponentBus.h deleted file mode 100644 index 7de4cb4e80..0000000000 --- a/Gems/Visibility/Code/Include/PortalComponentBus.h +++ /dev/null @@ -1,43 +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 - -namespace Visibility -{ - // Request bus for the PortalComponent. - class PortalRequests - { - public: - virtual float GetHeight() = 0; - virtual bool GetDisplayFilled() = 0; - virtual bool GetAffectedBySun() = 0; - virtual float GetViewDistRatio() = 0; - virtual bool GetSkyOnly() = 0; - virtual bool GetOceanIsVisible() = 0; - virtual bool GetUseDeepness() = 0; - virtual bool GetDoubleSide() = 0; - virtual bool GetLightBlending() = 0; - virtual float GetLightBlendValue() = 0; - - protected: - ~PortalRequests() = default; - }; - - /// Type to inherit to implement PortalRequests. - using PortalRequestBus = AZ::EBus; - -} // namespace Visibility diff --git a/Gems/Visibility/Code/Include/VisAreaComponentBus.h b/Gems/Visibility/Code/Include/VisAreaComponentBus.h deleted file mode 100644 index 632e68ffc5..0000000000 --- a/Gems/Visibility/Code/Include/VisAreaComponentBus.h +++ /dev/null @@ -1,38 +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 - -namespace Visibility -{ - /// Request bus for the VisAreaComponent. - class VisAreaComponentRequests - { - public: - virtual float GetHeight() = 0; - virtual bool GetDisplayFilled() = 0; - virtual bool GetAffectedBySun() = 0; - virtual float GetViewDistRatio() = 0; - virtual bool GetOceanIsVisible() = 0; - - protected: - ~VisAreaComponentRequests() = default; - }; - - /// Type to inherit to implement VisAreaComponentRequests. - using VisAreaComponentRequestBus = AZ::EBus; - -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.cpp b/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.cpp deleted file mode 100644 index a4065b711f..0000000000 --- a/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.cpp +++ /dev/null @@ -1,437 +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 "Visibility_precompiled.h" -#include "EditorOccluderAreaComponent.h" -#include "EditorOccluderAreaComponentMode.h" - -#include -#include -#include -#include -#include -#include - -// Include files needed for writing DisplayEntity functions that access the DisplayContext directly. -#include - -#include "MathConversion.h" - -namespace Visibility -{ - void EditorOccluderAreaComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides) - { - provides.push_back(AZ_CRC("EditorOccluderAreaService", 0xf943e16a)); - provides.push_back(AZ_CRC("OccluderAreaService", 0x2fefad66)); - provides.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); - } - - void EditorOccluderAreaComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires) - { - requires.push_back(AZ_CRC("TransformService", 0x8ee22c50)); - } - - void EditorOccluderAreaComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) - { - dependent.push_back(AZ_CRC("QuadShapeService", 0xe449b0fc)); - } - - void EditorOccluderAreaComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("EditorOccluderAreaService", 0xf943e16a)); - incompatible.push_back(AZ_CRC("OccluderAreaService", 0x2fefad66)); - incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); - } - - void EditorOccluderAreaConfiguration::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1); - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class("OccluderArea Configuration", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true); - - editContext->Class("OccluderArea Configuration", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &OccluderAreaConfiguration::m_displayFilled, "DisplayFilled", "Display the Occlude Area as a filled quad.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &OccluderAreaConfiguration::OnChange) - ->DataElement(AZ::Edit::UIHandlers::Default, &OccluderAreaConfiguration::m_cullDistRatio, "CullDistRatio", "The range of the culling effect.") - ->Attribute(AZ::Edit::Attributes::Max, 100.0f) - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &OccluderAreaConfiguration::OnChange) - ->DataElement(AZ::Edit::UIHandlers::Default, &OccluderAreaConfiguration::m_useInIndoors, "UseInIndoors", "Should this occluder work inside VisAreas.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &OccluderAreaConfiguration::OnChange) - ->DataElement(AZ::Edit::UIHandlers::Default, &OccluderAreaConfiguration::m_doubleSide, "DoubleSide", "Should this occlude from both sides.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &OccluderAreaConfiguration::OnChange) - ->DataElement(AZ::Edit::UIHandlers::Default, &OccluderAreaConfiguration::m_vertices, "Vertices", "Points that make up the OccluderArea.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &OccluderAreaConfiguration::OnVerticesChange) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ; - } - } - } - - void EditorOccluderAreaComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(2) - ->Field("m_config", &EditorOccluderAreaComponent::m_config) - ->Field("ComponentMode", &EditorOccluderAreaComponent::m_componentModeDelegate) - ; - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class("OccluderArea", "An area that blocks objects behind it from rendering.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Rendering") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/OccluderArea.png") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/OccluderArea.svg") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->Attribute(AZ::Edit::Attributes::HelpPageURL, "http://docs.aws.amazon.com/console/lumberyard/userguide/occluder-area-component") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorOccluderAreaComponent::m_config, "m_config", "No Description") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorOccluderAreaComponent::m_componentModeDelegate, "Component Mode", "OccluderArea Component Mode") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ; - } - } - - if (auto behaviorContext = azrtti_cast(context)) - { - behaviorContext->EBus("EditorOccluderAreaRequestBus") - ->Event("SetDisplayFilled", &EditorOccluderAreaRequestBus::Events::SetDisplayFilled) - ->Event("GetDisplayFilled", &EditorOccluderAreaRequestBus::Events::GetDisplayFilled) - ->VirtualProperty("DisplayFilled", "GetDisplayFilled", "SetDisplayFilled") - - ->Event("SetCullDistRatio", &EditorOccluderAreaRequestBus::Events::SetCullDistRatio) - ->Event("GetCullDistRatio", &EditorOccluderAreaRequestBus::Events::GetCullDistRatio) - ->VirtualProperty("CullDistRatio", "GetCullDistRatio", "SetCullDistRatio") - - ->Event("SetUseInIndoors", &EditorOccluderAreaRequestBus::Events::SetUseInIndoors) - ->Event("GetUseInIndoors", &EditorOccluderAreaRequestBus::Events::GetUseInIndoors) - ->VirtualProperty("UseInIndoors", "GetUseInIndoors", "SetUseInIndoors") - - ->Event("SetDoubleSide", &EditorOccluderAreaRequestBus::Events::SetDoubleSide) - ->Event("GetDoubleSide", &EditorOccluderAreaRequestBus::Events::GetDoubleSide) - ->VirtualProperty("DoubleSide", "GetDoubleSide", "SetDoubleSide") - ; - - behaviorContext->Class()->RequestBus("EditorOccluderAreaRequestBus"); - } - - EditorOccluderAreaConfiguration::Reflect(context); - } - - void EditorOccluderAreaConfiguration::OnChange() - { - EditorOccluderAreaRequestBus::Event(m_entityId, &EditorOccluderAreaRequests::UpdateOccluderAreaObject); - } - - void EditorOccluderAreaConfiguration::OnVerticesChange() - { - EditorOccluderAreaRequestBus::Event( - m_entityId, &EditorOccluderAreaRequests::UpdateOccluderAreaObject); - EditorOccluderAreaNotificationBus::Event( - m_entityId, &EditorOccluderAreaNotifications::OnVerticesChangedInspector); - } - - void EditorOccluderAreaConfiguration::SetEntityId(const AZ::EntityId entityId) - { - m_entityId = entityId; - } - - EditorOccluderAreaComponent::~EditorOccluderAreaComponent() - { - if (m_area && GetIEditor()->Get3DEngine()) - { - GetIEditor()->Get3DEngine()->DeleteVisArea(m_area); - m_area = nullptr; - } - } - - void EditorOccluderAreaComponent::Activate() - { - Base::Activate(); - - const AZ::EntityId entityId = GetEntityId(); - m_config.SetEntityId(entityId); - - // NOTE: We create the vis-area here at activate, but destroy it in the destructor. - // We have to do this, otherwise the vis-area is not saved into the level. - // Unfortunately, at this time we cannot create the vis-areas at game runtime. - // This means that dynamic slices cannot effectively contain vis areas until we fix - // the core rendering system to allow that. - const auto visGUID = static_cast(entityId); - if(!m_area && GetIEditor()) - { - m_area = GetIEditor()->Get3DEngine()->CreateVisArea(visGUID); - } - - m_componentModeDelegate.ConnectWithSingleComponentMode< - EditorOccluderAreaComponent, EditorOccluderAreaComponentMode>( - AZ::EntityComponentIdPair(entityId, GetId()), this); - - EditorOccluderAreaRequestBus::Handler::BusConnect(entityId); - AZ::FixedVerticesRequestBus::Handler::BusConnect(entityId); - AZ::TransformNotificationBus::Handler::BusConnect(entityId); - AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(entityId); - AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusConnect(entityId); - AzFramework::BoundsRequestBus::Handler::BusConnect(entityId); - - UpdateOccluderAreaObject(); - } - - void EditorOccluderAreaComponent::Deactivate() - { - m_componentModeDelegate.Disconnect(); - - AzFramework::BoundsRequestBus::Handler::BusDisconnect(); - AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusDisconnect(); - AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); - AZ::TransformNotificationBus::Handler::BusDisconnect(); - AZ::FixedVerticesRequestBus::Handler::BusDisconnect(); - EditorOccluderAreaRequestBus::Handler::BusDisconnect(); - - Base::Deactivate(); - } - - /// Update the object runtime after changes to the Configuration. - /// Called by the default RequestBus SetXXX implementations, - /// and used to initially set up the object the first time the - /// Configuration are set. - void EditorOccluderAreaComponent::UpdateOccluderAreaObject() - { - if (m_area && GetIEditor()->Get3DEngine()) - { - AZStd::array verts; - - const Matrix34& wtm = AZTransformToLYTransform(GetWorldTM()); - for (size_t i = 0; i < m_config.m_vertices.size(); ++i) - { - verts[i] = wtm.TransformPoint(AZVec3ToLYVec3(m_config.m_vertices[i])); - } - - SVisAreaInfo info; - info.fHeight = 0; - info.vAmbientColor = Vec3(0, 0, 0); - info.bAffectedByOutLights = false; - info.bSkyOnly = false; - info.fViewDistRatio = m_config.m_cullDistRatio; - info.bDoubleSide = m_config.m_doubleSide; - info.bUseDeepness = false; - info.bUseInIndoors = m_config.m_useInIndoors; - info.bOceanIsVisible = false; - info.fPortalBlending = -1.0f; - - const AZStd::string name = AZStd::string("OcclArea_") + GetEntity()->GetName(); - GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &verts[0], verts.size(), name.c_str(), info, false); - - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); - } - } - - void EditorOccluderAreaComponent::SetDisplayFilled(const bool value) - { - m_config.m_displayFilled = value; - UpdateOccluderAreaObject(); - } - - bool EditorOccluderAreaComponent::GetDisplayFilled() - { - return m_config.m_displayFilled; - } - - void EditorOccluderAreaComponent::SetCullDistRatio(const float value) - { - m_config.m_cullDistRatio = value; - UpdateOccluderAreaObject(); - } - - float EditorOccluderAreaComponent::GetCullDistRatio() - { - return m_config.m_cullDistRatio; - } - - void EditorOccluderAreaComponent::SetUseInIndoors(const bool value) - { - m_config.m_useInIndoors = value; - UpdateOccluderAreaObject(); - } - - bool EditorOccluderAreaComponent::GetUseInIndoors() - { - return m_config.m_useInIndoors; - } - - void EditorOccluderAreaComponent::SetDoubleSide(const bool value) - { - m_config.m_doubleSide = value; - UpdateOccluderAreaObject(); - } - - bool EditorOccluderAreaComponent::GetDoubleSide() - { - return m_config.m_doubleSide; - } - - bool EditorOccluderAreaComponent::GetVertex(const size_t index, AZ::Vector3& vertex) const - { - if (index < m_config.m_vertices.size()) - { - vertex = m_config.m_vertices[index]; - return true; - } - - return false; - } - - bool EditorOccluderAreaComponent::UpdateVertex(const size_t index, const AZ::Vector3& vertex) - { - if (index < m_config.m_vertices.size()) - { - m_config.m_vertices[index] = vertex; - return true; - } - - return false; - } - - void EditorOccluderAreaComponent::OnTransformChanged(const AZ::Transform& /*local*/, [[maybe_unused]] const AZ::Transform& world) - { - UpdateOccluderAreaObject(); - } - - void EditorOccluderAreaComponent::DisplayEntityViewport( - [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) - { - const AZ::Transform worldFromLocal = GetWorldTM(); - const AZ::Vector4 color(0.5f, 0.25f, 0.0f, 1.0f); - const AZ::Vector4 selectedColor(1.0f, 0.5f, 0.0f, 1.0f); - const float previousLineWidth = debugDisplay.GetLineWidth(); - - debugDisplay.DepthWriteOff(); - debugDisplay.PushMatrix(worldFromLocal); - debugDisplay.SetColor(IsSelected() ? selectedColor : color); - debugDisplay.SetLineWidth(5.0f); - debugDisplay.SetAlpha(0.8f); - - for (size_t i = 2; i < 4; i++) - { - // draw the plane - if (m_config.m_displayFilled) - { - debugDisplay.SetAlpha(0.3f); - debugDisplay.CullOff(); - debugDisplay.DrawTri(m_config.m_vertices[0], m_config.m_vertices[i - 1], m_config.m_vertices[i]); - debugDisplay.CullOn(); - debugDisplay.SetAlpha(0.8f); - } - - debugDisplay.DrawLine(m_config.m_vertices[i - 2], m_config.m_vertices[i - 1]); - debugDisplay.DrawLine(m_config.m_vertices[i - 1], m_config.m_vertices[i]); - } - - // draw the closing line - debugDisplay.DrawLine(m_config.m_vertices[3], m_config.m_vertices[0]); - - if (m_componentModeDelegate.AddedToComponentMode()) - { - AzToolsFramework::VertexContainerDisplay::DisplayVertexContainerIndices( - debugDisplay, AzToolsFramework::FixedVerticesArray(m_config.m_vertices), - GetWorldTM(), AZ::Vector3::CreateOne(), IsSelected()); - } - - debugDisplay.DepthWriteOn(); - debugDisplay.SetLineWidth(previousLineWidth); - debugDisplay.PopMatrix(); - } - - void EditorOccluderAreaComponent::BuildGameEntity(AZ::Entity* gameEntity) - { - gameEntity->CreateComponent(m_config); - } - - AZ::Aabb EditorOccluderAreaComponent::GetEditorSelectionBoundsViewport( - const AzFramework::ViewportInfo& /*viewportInfo*/) - { - return GetWorldBounds(); - } - - bool EditorOccluderAreaComponent::EditorSelectionIntersectRayViewport( - const AzFramework::ViewportInfo& /*viewportInfo*/, const AZ::Vector3& src, - const AZ::Vector3& dir, float& distance) - { - const float rayLength = 1000.0f; - AZ::Vector3 scaledDir = dir * rayLength; - AZ::Vector3 end = src + scaledDir; - float t; - float intermediateT = std::numeric_limits::max(); - bool didHit = false; - - // Transform verts to world space for tris test - AZStd::array verts; - const AZ::Transform& wtm = GetWorldTM(); - for (size_t i = 0; i < m_config.m_vertices.size(); ++i) - { - verts[i] = wtm.TransformPoint(m_config.m_vertices[i]); - } - - AZ::Vector3 normal; - for (AZ::u8 i = 2; i < 4; ++i) - { - if (AZ::Intersect::IntersectSegmentTriangleCCW(src, end, verts[0], verts[i - 1], verts[i], normal, t) > 0) - { - intermediateT = AZStd::GetMin(t, intermediateT); - didHit = true; - } - //Else if here as we shouldn't successfully ccw and cw intersect at the same time - else if (AZ::Intersect::IntersectSegmentTriangle(src, end, verts[0], verts[i - 1], verts[i], normal, t) > 0) - { - intermediateT = AZStd::GetMin(t, intermediateT); - didHit = true; - } - } - - if (didHit) - { - distance = intermediateT * rayLength; - } - return didHit; - } - - AZ::Aabb EditorOccluderAreaComponent::GetWorldBounds() - { - return GetLocalBounds().GetTransformedAabb(GetWorldTM()); - } - - AZ::Aabb EditorOccluderAreaComponent::GetLocalBounds() - { - AZ::Aabb bbox = AZ::Aabb::CreateNull(); - for (const auto& vertex : m_config.m_vertices) - { - bbox.AddPoint(vertex); - } - return bbox; - } -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.h b/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.h deleted file mode 100644 index 0ac6528bc7..0000000000 --- a/Gems/Visibility/Code/Source/EditorOccluderAreaComponent.h +++ /dev/null @@ -1,129 +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 "OccluderAreaComponent.h" -#include "EditorOccluderAreaComponentBus.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Visibility -{ - class EditorOccluderAreaComponent; - - class EditorOccluderAreaConfiguration - : public OccluderAreaConfiguration - { - public: - AZ_TYPE_INFO_LEGACY(EditorOccluderAreaConfiguration, "{032F466F-25CB-5460-AC2F-B04236C87878}", OccluderAreaConfiguration); - AZ_CLASS_ALLOCATOR(EditorOccluderAreaConfiguration, AZ::SystemAllocator, 0); - - static void Reflect(AZ::ReflectContext* context); - - void OnChange() override; - void OnVerticesChange() override; - - void SetEntityId(AZ::EntityId entityId); - - private: - AZ::EntityId m_entityId; - }; - - class EditorOccluderAreaComponent - : public AzToolsFramework::Components::EditorComponentBase - , private EditorOccluderAreaRequestBus::Handler - , private AZ::FixedVerticesRequestBus::Handler - , private AzFramework::EntityDebugDisplayEventBus::Handler - , private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler - , private AZ::TransformNotificationBus::Handler - , public AzFramework::BoundsRequestBus::Handler - { - friend class EditorOccluderAreaConfiguration; - - using Base = AzToolsFramework::Components::EditorComponentBase; - - public: - AZ_COMPONENT(EditorOccluderAreaComponent, "{1A209C7C-6C06-5AE6-AD60-22CD8D0DAEE3}", AzToolsFramework::Components::EditorComponentBase); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires); - static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - - static void Reflect(AZ::ReflectContext* context); - - EditorOccluderAreaComponent() = default; - EditorOccluderAreaComponent(const EditorOccluderAreaComponent&) = delete; - EditorOccluderAreaComponent& operator=(const EditorOccluderAreaComponent&) = delete; - ~EditorOccluderAreaComponent(); - - // AZ::Component overrides ... - void Activate() override; - void Deactivate() override; - void BuildGameEntity(AZ::Entity* gameEntity) override; - - // TransformNotificationBus overrides ... - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - - // EditorComponentSelectionRequestsBus overrides ... - AZ::Aabb GetEditorSelectionBoundsViewport( - const AzFramework::ViewportInfo& viewportInfo) override; - bool EditorSelectionIntersectRayViewport( - const AzFramework::ViewportInfo& viewportInfo, const AZ::Vector3& src, - const AZ::Vector3& dir, float& distance) override; - bool SupportsEditorRayIntersect() override { return true; } - - // BoundsRequestBus overrides ... - AZ::Aabb GetWorldBounds() override; - AZ::Aabb GetLocalBounds() override; - - /// EditorOccluderAreaRequestBus overrides ... - void SetDisplayFilled(bool value) override; - bool GetDisplayFilled() override; - void SetCullDistRatio(float value) override; - float GetCullDistRatio() override; - void SetUseInIndoors(bool value) override; - bool GetUseInIndoors() override; - void SetDoubleSide(bool value) override; - bool GetDoubleSide() override; - bool GetVertex(size_t index, AZ::Vector3& vertex) const override; - bool UpdateVertex(size_t index, const AZ::Vector3& vertex) override; - size_t Size() const override { return m_config.m_vertices.size(); } - void UpdateOccluderAreaObject() override; - - private: - friend EditorOccluderAreaConfiguration; - - // AzFramework::EntityDebugDisplayEventBus overrides ... - void DisplayEntityViewport( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; - - // Reflected members - EditorOccluderAreaConfiguration m_config; - - using ComponentModeDelegate = AzToolsFramework::ComponentModeFramework::ComponentModeDelegate; - ComponentModeDelegate m_componentModeDelegate; ///< Responsible for detecting ComponentMode activation - ///< and creating a concrete ComponentMode. - - // Unreflected members - IVisArea* m_area = nullptr; - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorOccluderAreaComponentMode.cpp b/Gems/Visibility/Code/Source/EditorOccluderAreaComponentMode.cpp deleted file mode 100644 index 0ab51d362a..0000000000 --- a/Gems/Visibility/Code/Source/EditorOccluderAreaComponentMode.cpp +++ /dev/null @@ -1,85 +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 "Visibility_precompiled.h" -#include "EditorOccluderAreaComponentMode.h" - -#include - -namespace Visibility -{ - AZ_CLASS_ALLOCATOR_IMPL(EditorOccluderAreaComponentMode, AZ::SystemAllocator, 0) - - EditorOccluderAreaComponentMode::EditorOccluderAreaComponentMode( - const AZ::EntityComponentIdPair& entityComponentIdPair, AZ::Uuid componentType) - : EditorBaseComponentMode(entityComponentIdPair, componentType) - { - CreateManipulators(); - - AZ::TransformNotificationBus::Handler::BusConnect(entityComponentIdPair.GetEntityId()); - EditorOccluderAreaNotificationBus::Handler::BusConnect(entityComponentIdPair.GetEntityId()); - } - - EditorOccluderAreaComponentMode::~EditorOccluderAreaComponentMode() - { - EditorOccluderAreaNotificationBus::Handler::BusDisconnect(); - AZ::TransformNotificationBus::Handler::BusDisconnect(); - - m_vertexSelection.Destroy(); - } - - void EditorOccluderAreaComponentMode::CreateManipulators() - { - using namespace AzToolsFramework; - - m_vertexSelection.Create( - AZ::EntityComponentIdPair(GetEntityId(), GetComponentId()), g_mainManipulatorManagerId, - AZStd::make_unique(), - TranslationManipulators::Dimensions::Three, - ConfigureTranslationManipulatorAppearance3d); - - m_vertexSelection.SetVertexPositionsUpdatedCallback([this]() - { - EditorOccluderAreaRequestBus::Event( - GetEntityId(), &EditorOccluderAreaRequests::UpdateOccluderAreaObject); - }); - } - - void EditorOccluderAreaComponentMode::OnTransformChanged( - const AZ::Transform& /*local*/, const AZ::Transform& world) - { - m_vertexSelection.RefreshSpace(world); - } - - void EditorOccluderAreaComponentMode::OnVerticesChangedInspector() - { - m_vertexSelection.RefreshLocal(); - } - - void EditorOccluderAreaComponentMode::Refresh() - { - // destroy and recreate manipulators when container is modified (vertices are added or removed) - m_vertexSelection.Destroy(); - CreateManipulators(); - } - - AZStd::vector EditorOccluderAreaComponentMode::PopulateActionsImpl() - { - return m_vertexSelection.ActionOverrides(); - } - - bool EditorOccluderAreaComponentMode::HandleMouseInteraction( - const AzToolsFramework::ViewportInteraction::MouseInteractionEvent& mouseInteraction) - { - return m_vertexSelection.HandleMouse(mouseInteraction); - } -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorOccluderAreaComponentMode.h b/Gems/Visibility/Code/Source/EditorOccluderAreaComponentMode.h deleted file mode 100644 index babef3bccc..0000000000 --- a/Gems/Visibility/Code/Source/EditorOccluderAreaComponentMode.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. -* -*/ - -#pragma once - -#include -#include -#include - -#include "EditorOccluderAreaComponentBus.h" - -namespace Visibility -{ - class EditorOccluderAreaComponentMode - : public AzToolsFramework::ComponentModeFramework::EditorBaseComponentMode - , private AZ::TransformNotificationBus::Handler - , private EditorOccluderAreaNotificationBus::Handler - { - public: - AZ_CLASS_ALLOCATOR_DECL - - EditorOccluderAreaComponentMode( - const AZ::EntityComponentIdPair& entityComponentIdPair, AZ::Uuid componentType); - ~EditorOccluderAreaComponentMode(); - - private: - // EditorBaseComponentMode - void Refresh() override; - AZStd::vector PopulateActionsImpl() override; - bool HandleMouseInteraction( - const AzToolsFramework::ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; - - // Manipulator handling - void CreateManipulators(); - - // TransformNotificationBus - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - - // OccluderAreaNotificationBus - void OnVerticesChangedInspector() override; - - AzToolsFramework::EditorVertexSelectionFixed m_vertexSelection; ///< Handles all manipulator interactions with vertices. - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorPortalComponent.cpp b/Gems/Visibility/Code/Source/EditorPortalComponent.cpp deleted file mode 100644 index d33828514b..0000000000 --- a/Gems/Visibility/Code/Source/EditorPortalComponent.cpp +++ /dev/null @@ -1,788 +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 "Visibility_precompiled.h" -#include "EditorPortalComponent.h" -#include "EditorPortalComponentMode.h" - -#include - -// Include files needed for writing DisplayEntity functions that access the DisplayContext directly. -#include - -#include -#include -#include -#include -#include - -namespace Visibility -{ - void EditorPortalComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("EditorPortalService", 0x6ead38f6)); - provided.push_back(AZ_CRC("PortalService", 0x06076210)); - provided.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); - } - - void EditorPortalComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); - } - - void EditorPortalComponent::GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) - { - dependent.push_back(AZ_CRC("QuadShapeService", 0xe449b0fc)); - } - - void EditorPortalComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("SphereShapeService", 0x90c8dc80)); - incompatible.push_back(AZ_CRC("SplineShapeService", 0x4d4b94a2)); - incompatible.push_back(AZ_CRC("PolygonPrismShapeService", 0x1cbc4ed4)); - incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); - } - - void EditorPortalConfiguration::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1); - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class("Portal Configuration", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true); - - editContext->Class("Portal Configuration", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_height, "Height", "How tall the Portal is.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_displayFilled, "DisplayFilled", "Display the Portal as a filled volume.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_affectedBySun, "AffectedBySun", "Allows sunlight to affect objects inside the Portal.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_viewDistRatio, "ViewDistRatio", "Specifies how far the Portal is rendered.") - ->Attribute(AZ::Edit::Attributes::Max, 100.000000) - ->Attribute(AZ::Edit::Attributes::Min, 0.000000) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_skyOnly, "SkyOnly", "Only the Sky Box will render when looking outside the Portal.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_oceanIsVisible, "OceanIsVisible", "Ocean will be visible when looking outside the Portal.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_useDeepness, "UseDeepness", "Portal will be treated as an object with volume rather than a plane.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_doubleSide, "DoubleSide", "Cameras will be able to look through the portal from both sides.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_lightBlending, "LightBlending", "Light from neighboring VisAreas will blend into the Portal.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_lightBlendValue, "LightBlendValue", "How much to blend lights from neighboring VisAreas.") - ->Attribute(AZ::Edit::Attributes::Max, 1.000000) - ->Attribute(AZ::Edit::Attributes::Min, 0.000000) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnChange) - ->DataElement( - AZ::Edit::UIHandlers::Default, &PortalConfiguration::m_vertices, "Vertices", "Points that make up the floor of the Portal.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &PortalConfiguration::OnVerticesChange) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ; - } - } - } - - void EditorPortalComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(2) - ->Field("m_config", &EditorPortalComponent::m_config) - ->Field("ComponentMode", &EditorPortalComponent::m_componentModeDelegate) - ; - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class("Portal", "An area that describes a visibility portal between VisAreas.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Rendering") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/Portal.png") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/Portal.svg") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->Attribute(AZ::Edit::Attributes::HelpPageURL, "http://docs.aws.amazon.com/console/lumberyard/userguide/portal-component") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorPortalComponent::m_config, "m_config", "No Description") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorPortalComponent::m_componentModeDelegate, "Component Mode", "Portal Component Mode") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ; - } - } - - if (auto behaviorContext = azrtti_cast(context)) - { - behaviorContext->EBus("EditorPortalRequestBus") - ->Event("SetHeight", &EditorPortalRequestBus::Events::SetHeight) - ->Event("GetHeight", &EditorPortalRequestBus::Events::GetHeight) - ->VirtualProperty("Height", "GetHeight", "SetHeight") - - ->Event("SetDisplayFilled", &EditorPortalRequestBus::Events::SetDisplayFilled) - ->Event("GetDisplayFilled", &EditorPortalRequestBus::Events::GetDisplayFilled) - ->VirtualProperty("DisplayFilled", "GetDisplayFilled", "SetDisplayFilled") - - ->Event("SetAffectedBySun", &EditorPortalRequestBus::Events::SetAffectedBySun) - ->Event("GetAffectedBySun", &EditorPortalRequestBus::Events::GetAffectedBySun) - ->VirtualProperty("AffectedBySun", "GetAffectedBySun", "SetAffectedBySun") - - ->Event("SetViewDistRatio", &EditorPortalRequestBus::Events::SetViewDistRatio) - ->Event("GetViewDistRatio", &EditorPortalRequestBus::Events::GetViewDistRatio) - ->VirtualProperty("ViewDistRatio", "GetViewDistRatio", "SetViewDistRatio") - - ->Event("SetSkyOnly", &EditorPortalRequestBus::Events::SetSkyOnly) - ->Event("GetSkyOnly", &EditorPortalRequestBus::Events::GetSkyOnly) - ->VirtualProperty("SkyOnly", "GetSkyOnly", "SetSkyOnly") - - ->Event("SetOceanIsVisible", &EditorPortalRequestBus::Events::SetOceanIsVisible) - ->Event("GetOceanIsVisible", &EditorPortalRequestBus::Events::GetOceanIsVisible) - ->VirtualProperty("OceanIsVisible", "GetOceanIsVisible", "SetOceanIsVisible") - - ->Event("SetUseDeepness", &EditorPortalRequestBus::Events::SetUseDeepness) - ->Event("GetUseDeepness", &EditorPortalRequestBus::Events::GetUseDeepness) - ->VirtualProperty("UseDeepness", "GetUseDeepness", "SetUseDeepness") - - ->Event("SetDoubleSide", &EditorPortalRequestBus::Events::SetDoubleSide) - ->Event("GetDoubleSide", &EditorPortalRequestBus::Events::GetDoubleSide) - ->VirtualProperty("DoubleSide", "GetDoubleSide", "SetDoubleSide") - - ->Event("SetLightBlending", &EditorPortalRequestBus::Events::SetLightBlending) - ->Event("GetLightBlending", &EditorPortalRequestBus::Events::GetLightBlending) - ->VirtualProperty("LightBlending", "GetLightBlending", "SetLightBlending") - - ->Event("SetLightBlendValue", &EditorPortalRequestBus::Events::SetLightBlendValue) - ->Event("GetLightBlendValue", &EditorPortalRequestBus::Events::GetLightBlendValue) - ->VirtualProperty("LightBlendValue", "GetLightBlendValue", "SetLightBlendValue") - ; - - behaviorContext->Class()->RequestBus("EditorPortalRequestBus"); - } - - EditorPortalConfiguration::Reflect(context); - } - - void EditorPortalConfiguration::OnChange() - { - EditorPortalRequestBus::Event(m_entityId, &EditorPortalRequests::UpdatePortalObject); - } - - void EditorPortalConfiguration::OnVerticesChange() - { - EditorPortalRequestBus::Event(m_entityId, &EditorPortalRequests::UpdatePortalObject); - EditorPortalNotificationBus::Event(m_entityId, &EditorPortalNotifications::OnVerticesChangedInspector); - } - - void EditorPortalConfiguration::SetEntityId(const AZ::EntityId entityId) - { - m_entityId = entityId; - } - - EditorPortalComponent::~EditorPortalComponent() - { - if (m_area && GetIEditor()->Get3DEngine()) - { - // reset the listener vis area in the unlucky case that we are deleting the - // vis area where the listener is currently in - // Audio: do we still need this? - GetIEditor()->Get3DEngine()->DeleteVisArea(m_area); - m_area = nullptr; - } - } - - void EditorPortalComponent::Activate() - { - Base::Activate(); - - const AZ::EntityId entityId = GetEntityId(); - m_config.SetEntityId(entityId); - - // NOTE: We create the vis-area here at activated, but destroy it in the destructor. - // We have to do this, otherwise the vis-area is not saved into the level. - // Unfortunately, at this time we cannot create the vis-areas at game runtime. - // This means that dynamic slices cannot effectively contain vis-areas until we fix the core rendering system to allow that. - - const auto visGUID = static_cast(entityId); - if(!m_area && GetIEditor() && GetIEditor()->Get3DEngine()) - { - m_area = GetIEditor()->Get3DEngine()->CreateVisArea(visGUID); - } - - m_AZCachedWorldTransform = AZ::Transform::CreateIdentity(); - m_cryCachedWorldTransform = Matrix34::CreateIdentity(); - - m_componentModeDelegate.ConnectWithSingleComponentMode< - EditorPortalComponent, EditorPortalComponentMode>( - AZ::EntityComponentIdPair(entityId, GetId()), this); - - EditorPortalRequestBus::Handler::BusConnect(entityId); - AZ::FixedVerticesRequestBus::Handler::BusConnect(entityId); - AZ::TransformNotificationBus::Handler::BusConnect(entityId); - AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(entityId); - AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusConnect(entityId); - AzFramework::BoundsRequestBus::Handler::BusConnect(entityId); - - //Call OnTransformChanged manually to cache current transform since it won't be called - //automatically for us when the level starts up. - AZ::Transform worldTM; - AZ::TransformBus::EventResult(worldTM, entityId, &AZ::TransformBus::Events::GetWorldTM); - - //Use an identity transform for localTM because the - //OnTransformChanged impl for this class doesn't need it - OnTransformChanged(AZ::Transform::CreateIdentity(), worldTM); - } - - void EditorPortalComponent::Deactivate() - { - m_componentModeDelegate.Disconnect(); - - AzFramework::BoundsRequestBus::Handler::BusDisconnect(); - AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusDisconnect(GetEntityId()); - AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(GetEntityId()); - AZ::TransformNotificationBus::Handler::BusDisconnect(GetEntityId()); - AZ::FixedVerticesRequestBus::Handler::BusDisconnect(); - EditorPortalRequestBus::Handler::BusDisconnect(); - - Base::Deactivate(); - } - - void EditorPortalComponent::SetHeight(const float height) - { - m_config.m_height = height; - UpdatePortalObject(); - } - - float EditorPortalComponent::GetHeight() - { - return m_config.m_height; - } - - void EditorPortalComponent::SetDisplayFilled(const bool filled) - { - m_config.m_displayFilled = filled; - UpdatePortalObject(); - } - - bool EditorPortalComponent::GetDisplayFilled() - { - return m_config.m_displayFilled; - } - - void EditorPortalComponent::SetAffectedBySun(const bool affectedBySun) - { - m_config.m_affectedBySun = affectedBySun; - UpdatePortalObject(); - } - - bool EditorPortalComponent::GetAffectedBySun() - { - return m_config.m_affectedBySun; - } - - void EditorPortalComponent::SetViewDistRatio(const float viewDistRatio) - { - m_config.m_viewDistRatio = viewDistRatio; - UpdatePortalObject(); - } - - float EditorPortalComponent::GetViewDistRatio() - { - return m_config.m_viewDistRatio; - } - - void EditorPortalComponent::SetSkyOnly(const bool skyOnly) - { - m_config.m_skyOnly = skyOnly; - UpdatePortalObject(); - } - - bool EditorPortalComponent::GetSkyOnly() - { - return m_config.m_skyOnly; - } - - void EditorPortalComponent::SetOceanIsVisible(const bool oceanVisible) - { - m_config.m_oceanIsVisible = oceanVisible; - UpdatePortalObject(); - } - - bool EditorPortalComponent::GetOceanIsVisible() - { - return m_config.m_oceanIsVisible; - } - - void EditorPortalComponent::SetUseDeepness(const bool useDeepness) - { - m_config.m_useDeepness = useDeepness; - UpdatePortalObject(); - } - - bool EditorPortalComponent::GetUseDeepness() - { - return m_config.m_useDeepness; - } - - void EditorPortalComponent::SetDoubleSide(const bool doubleSided) - { - m_config.m_doubleSide = doubleSided; - UpdatePortalObject(); - } - - bool EditorPortalComponent::GetDoubleSide() - { - return m_config.m_doubleSide; - } - - void EditorPortalComponent::SetLightBlending(const bool lightBending) - { - m_config.m_lightBlending = lightBending; - UpdatePortalObject(); - } - - bool EditorPortalComponent::GetLightBlending() - { - return m_config.m_lightBlending; - } - - void EditorPortalComponent::SetLightBlendValue(const float lightBendAmount) - { - m_config.m_lightBlendValue = lightBendAmount; - UpdatePortalObject(); - } - - float EditorPortalComponent::GetLightBlendValue() - { - return m_config.m_lightBlendValue; - } - - bool EditorPortalComponent::GetVertex(const size_t index, AZ::Vector3& vertex) const - { - if (index < m_config.m_vertices.size()) - { - vertex = m_config.m_vertices[index]; - return true; - } - - return false; - } - - bool EditorPortalComponent::UpdateVertex(const size_t index, const AZ::Vector3& vertex) - { - if (index < m_config.m_vertices.size()) - { - m_config.m_vertices[index] = vertex; - return true; - } - - return false; - } - - /// Update the object runtime after changes to the Configuration. - /// Called by the default RequestBus SetXXX implementations, - /// and used to initially set up the object the first time the - /// Configuration are set. - void EditorPortalComponent::UpdatePortalObject() - { - if (m_area) - { - SVisAreaInfo info; - info.vAmbientColor = Vec3(ZERO); - info.bAffectedByOutLights = m_config.m_affectedBySun; - info.bSkyOnly = m_config.m_skyOnly; - info.fViewDistRatio = m_config.m_viewDistRatio; - info.bDoubleSide = m_config.m_doubleSide; - info.bUseDeepness = m_config.m_useDeepness; - info.bUseInIndoors = true; //Does not apply to Portals (Portals are only in VisAreas) - info.bOceanIsVisible = m_config.m_oceanIsVisible; - info.fPortalBlending = -1.0f; - - if (m_config.m_lightBlending) - { - info.fPortalBlending = m_config.m_lightBlendValue; - } - - AZStd::string name = AZStd::string("Portal_") + GetEntity()->GetName(); - - // Calculate scaled height - // Height exists separate from plane points but we still want to scale it with the transform - info.fHeight = m_config.m_height; - - /* - We have to derive at least 3 points and pass them to the vis area system - For now that means getting the 4 points of the bottom face of the box. - - If we want to send *all* points of a shape the vis system we need to make sure - that Height is 0; otherwise it'll extend the AABB of the area upwards. - */ - - //Convert to Cry vectors and apply the transform to the given points - AZStd::fixed_vector verts(4); - for (AZ::u32 i = 0; i < verts.size(); ++i) - { - verts[i] = AZVec3ToLYVec3(m_config.m_vertices[i]); - verts[i] = m_cryCachedWorldTransform.TransformPoint(verts[i]); - } - - if (GetIEditor()->Get3DEngine()) - { - GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &verts[0], verts.size(), name.c_str(), info, true); - } - - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); - } - } - - void EditorPortalComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) - { - //Cache the transform so that we don't have to retrieve it every time UpdatePortalObject is called - m_AZCachedWorldTransform = world; - m_cryCachedWorldTransform = AZTransformToLYTransform(m_AZCachedWorldTransform); - - UpdatePortalObject(); - } - - struct PortalQuadVertices - { - AZ::Vector3 floorLeftFront; - AZ::Vector3 floorRightFront; - AZ::Vector3 floorLeftBack; - AZ::Vector3 floorRightBack; - - AZ::Vector3 quadUpperLeftFront; - AZ::Vector3 quadUpperRightFront; - AZ::Vector3 quadUpperLeftBack; - AZ::Vector3 quadUpperRightBack; - - AZ::Vector3 portalUpperLeftFront; - AZ::Vector3 portalUpperRightFront; - AZ::Vector3 portalUpperLeftBack; - AZ::Vector3 portalUpperRightBack; - }; - - PortalQuadVertices EditorPortalComponent::CalculatePortalQuadVertices(VertTranslation vertTranslation) - { - PortalQuadVertices pqv; - - //Untransformed quad corners - const AZ::Vector3 lowerLeftFront = m_config.m_vertices[0]; - const AZ::Vector3 lowerRightFront = m_config.m_vertices[1]; - const AZ::Vector3 lowerLeftBack = m_config.m_vertices[3]; - const AZ::Vector3 lowerRightBack = m_config.m_vertices[2]; - - //Need to calculate the height of the quad after transformation - const AZ::u32 quadPointCount = 4; - AZ::Vector3 transformedQuadPoints[quadPointCount]; - - transformedQuadPoints[0] = m_AZCachedWorldTransform.TransformPoint(lowerLeftFront); - transformedQuadPoints[1] = m_AZCachedWorldTransform.TransformPoint(lowerRightFront); - transformedQuadPoints[2] = m_AZCachedWorldTransform.TransformPoint(lowerLeftBack); - transformedQuadPoints[3] = m_AZCachedWorldTransform.TransformPoint(lowerRightBack); - - const AZ::Vector3 translation = m_AZCachedWorldTransform.GetTranslation(); - - float minHeight = FLT_MAX; - float maxHeight = FLT_MIN; - - for (auto& transformedQuadPoint : transformedQuadPoints) - { - // remove translation from quad points so we can use them with the DisplayContext's usage of the transform - if (vertTranslation == VertTranslation::Remove) - { - transformedQuadPoint -= translation; - } - - const float height = transformedQuadPoint.GetZ(); - if (height < minHeight) - { - minHeight = height; - } - if (height > maxHeight) - { - maxHeight = height; - } - } - - pqv.floorLeftFront = AZ::Vector3(transformedQuadPoints[0].GetX(), transformedQuadPoints[0].GetY(), minHeight); - pqv.floorRightFront = AZ::Vector3(transformedQuadPoints[1].GetX(), transformedQuadPoints[1].GetY(), minHeight); - pqv.floorLeftBack = AZ::Vector3(transformedQuadPoints[2].GetX(), transformedQuadPoints[2].GetY(), minHeight); - pqv.floorRightBack = AZ::Vector3(transformedQuadPoints[3].GetX(), transformedQuadPoints[3].GetY(), minHeight); - - pqv.quadUpperLeftFront = AZ::Vector3(transformedQuadPoints[0].GetX(), transformedQuadPoints[0].GetY(), maxHeight); - pqv.quadUpperRightFront = AZ::Vector3(transformedQuadPoints[1].GetX(), transformedQuadPoints[1].GetY(), maxHeight); - pqv.quadUpperLeftBack = AZ::Vector3(transformedQuadPoints[2].GetX(), transformedQuadPoints[2].GetY(), maxHeight); - pqv.quadUpperRightBack = AZ::Vector3(transformedQuadPoints[3].GetX(), transformedQuadPoints[3].GetY(), maxHeight); - - pqv.portalUpperLeftFront = AZ::Vector3(transformedQuadPoints[0].GetX(), transformedQuadPoints[0].GetY(), maxHeight + m_config.m_height); - pqv.portalUpperRightFront = AZ::Vector3(transformedQuadPoints[1].GetX(), transformedQuadPoints[1].GetY(), maxHeight + m_config.m_height); - pqv.portalUpperLeftBack = AZ::Vector3(transformedQuadPoints[2].GetX(), transformedQuadPoints[2].GetY(), maxHeight + m_config.m_height); - pqv.portalUpperRightBack = AZ::Vector3(transformedQuadPoints[3].GetX(), transformedQuadPoints[3].GetY(), maxHeight + m_config.m_height); - - return pqv; - } - - void EditorPortalComponent::DisplayEntityViewport( - [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) - { - /* - IMPORTANT NOTE: This method may seem very complicated but it is an accurate visualization of - how portals actually work. The legacy visualization used with the legacy portal entity is - very misleading! - - Portals always exist as a quad but if the quad becomes non-planar, from rotation or in the legacy - system from a point being pulled up or down, the volume changes in a non-obvious way. Instead of portal - existing as the shape defined by 4 points and extruded upwards, the portal actually remains planar. - Any height difference that you add by making the shape non-planar is just applied to the height of the volume. - - If this is confusing, please actually look at the visualization created by this method. Make sure - that you rotate the portal in many weird contorted ways and examine how the visualization reacts. - The portal volume is always going to be a box rotated on only X and Y axes that stretches up along the Z axis. - - Important note on the complexity of this method: - We cannot directly visualize the OBB of the portal with an AABB that we then transform. The OBB that's mentioned - here is best imagined as the top plane being all points of the quad pulled up to the height of the highest quad's vert - and the bottom plane being all points of the quad pulled down to the height of the lowest quad's vert. Trying to - create an AABB from these points won't produce the correct visualization under complex rotations as the Min and Max - of the AABB will either only encompass part of the bounding volume or be too large. - */ - - const PortalQuadVertices pqv = CalculatePortalQuadVertices(VertTranslation::Remove); - - //Draw the outline of the OBB of the Portal's quad - AZ::Color color(0.000f, 1.0f, 0.000f, 1.0f); - debugDisplay.SetColor(AZ::Vector4(color.GetR(), color.GetG(), color.GetB(), 1.f)); - - //Remove all rotation from the transform - const AZ::Quaternion rotation = AZ::Quaternion::CreateIdentity(); - - AZ::Transform worldTMOnlyZRot = m_AZCachedWorldTransform; - worldTMOnlyZRot.SetRotation(rotation); - - debugDisplay.PushMatrix(worldTMOnlyZRot); - - //Draw the outline of the OBB of the portal quad - - //Bottom - debugDisplay.DrawLine(pqv.floorLeftFront, pqv.floorRightFront); - debugDisplay.DrawLine(pqv.floorRightFront, pqv.floorRightBack); - debugDisplay.DrawLine(pqv.floorRightBack, pqv.floorLeftBack); - debugDisplay.DrawLine(pqv.floorLeftBack, pqv.floorLeftFront); - //Top - debugDisplay.DrawLine(pqv.quadUpperLeftFront, pqv.quadUpperRightFront); - debugDisplay.DrawLine(pqv.quadUpperRightFront, pqv.quadUpperRightBack); - debugDisplay.DrawLine(pqv.quadUpperRightBack, pqv.quadUpperLeftBack); - debugDisplay.DrawLine(pqv.quadUpperLeftBack, pqv.quadUpperLeftFront); - //Left - debugDisplay.DrawLine(pqv.floorLeftFront, pqv.quadUpperLeftFront); - debugDisplay.DrawLine(pqv.quadUpperLeftFront, pqv.quadUpperLeftBack); - debugDisplay.DrawLine(pqv.quadUpperLeftBack, pqv.floorLeftBack); - debugDisplay.DrawLine(pqv.floorLeftBack, pqv.floorLeftFront); - //Right - debugDisplay.DrawLine(pqv.floorRightFront, pqv.quadUpperRightFront); - debugDisplay.DrawLine(pqv.quadUpperRightFront, pqv.quadUpperRightBack); - debugDisplay.DrawLine(pqv.quadUpperRightBack, pqv.floorRightBack); - debugDisplay.DrawLine(pqv.floorRightBack, pqv.floorRightFront); - //Front - debugDisplay.DrawLine(pqv.floorLeftFront, pqv.floorRightFront); - debugDisplay.DrawLine(pqv.floorRightFront, pqv.quadUpperRightFront); - debugDisplay.DrawLine(pqv.quadUpperRightFront, pqv.quadUpperLeftFront); - debugDisplay.DrawLine(pqv.quadUpperLeftFront, pqv.floorLeftFront); - //Back - debugDisplay.DrawLine(pqv.floorLeftBack, pqv.floorRightBack); - debugDisplay.DrawLine(pqv.floorRightBack, pqv.quadUpperRightBack); - debugDisplay.DrawLine(pqv.quadUpperRightBack, pqv.quadUpperLeftBack); - debugDisplay.DrawLine(pqv.quadUpperLeftBack, pqv.floorLeftBack); - - //Now draw the entire portal volume (Previous OBB + extra height) - if (m_config.m_displayFilled) - { - //Draw whole portal with less alpha - debugDisplay.SetColor(AZ::Vector4(color.GetR(), color.GetG(), color.GetB(), 0.1f)); - - //Draw both winding orders for quads so they appear solid from all angles - //Not drawing boxes because the corners of the quad may not be hit if the bounds are rotated oddly - - //Bottom - debugDisplay.DrawQuad(pqv.floorLeftFront, pqv.floorRightFront, pqv.floorRightBack, pqv.floorLeftBack); - debugDisplay.DrawQuad(pqv.floorLeftFront, pqv.floorLeftBack, pqv.floorRightBack, pqv.floorRightFront); - //Top - debugDisplay.DrawQuad(pqv.portalUpperLeftFront, pqv.portalUpperRightFront, pqv.portalUpperRightBack, pqv.portalUpperLeftBack); - debugDisplay.DrawQuad(pqv.portalUpperLeftFront, pqv.portalUpperLeftBack, pqv.portalUpperRightBack, pqv.portalUpperRightFront); - //Left - debugDisplay.DrawQuad(pqv.floorLeftFront, pqv.portalUpperLeftFront, pqv.portalUpperLeftBack, pqv.floorLeftBack); - debugDisplay.DrawQuad(pqv.floorLeftFront, pqv.floorLeftBack, pqv.portalUpperLeftBack, pqv.portalUpperLeftFront); - //Right - debugDisplay.DrawQuad(pqv.floorRightFront, pqv.portalUpperRightFront, pqv.portalUpperRightBack, pqv.floorRightBack); - debugDisplay.DrawQuad(pqv.floorRightFront, pqv.floorRightBack, pqv.portalUpperRightBack, pqv.portalUpperRightFront); - //Front - debugDisplay.DrawQuad(pqv.floorLeftFront, pqv.floorRightFront, pqv.portalUpperRightFront, pqv.portalUpperLeftFront); - debugDisplay.DrawQuad(pqv.floorLeftFront, pqv.portalUpperLeftFront, pqv.portalUpperRightFront, pqv.floorRightFront); - //Back - debugDisplay.DrawQuad(pqv.floorLeftBack, pqv.floorRightBack, pqv.portalUpperRightBack, pqv.portalUpperLeftBack); - debugDisplay.DrawQuad(pqv.floorLeftBack, pqv.portalUpperLeftBack, pqv.portalUpperRightBack, pqv.floorRightBack); - } - else - { - //Bottom - debugDisplay.DrawLine(pqv.floorLeftFront, pqv.floorRightFront); - debugDisplay.DrawLine(pqv.floorRightFront, pqv.floorRightBack); - debugDisplay.DrawLine(pqv.floorRightBack, pqv.floorLeftBack); - debugDisplay.DrawLine(pqv.floorLeftBack, pqv.floorLeftFront); - //Top - debugDisplay.DrawLine(pqv.portalUpperLeftFront, pqv.portalUpperRightFront); - debugDisplay.DrawLine(pqv.portalUpperRightFront, pqv.portalUpperRightBack); - debugDisplay.DrawLine(pqv.portalUpperRightBack, pqv.portalUpperLeftBack); - debugDisplay.DrawLine(pqv.portalUpperLeftBack, pqv.portalUpperLeftFront); - //Left - debugDisplay.DrawLine(pqv.floorLeftFront, pqv.portalUpperLeftFront); - debugDisplay.DrawLine(pqv.portalUpperLeftFront, pqv.portalUpperLeftBack); - debugDisplay.DrawLine(pqv.portalUpperLeftBack, pqv.floorLeftBack); - debugDisplay.DrawLine(pqv.floorLeftBack, pqv.floorLeftFront); - //Right - debugDisplay.DrawLine(pqv.floorRightFront, pqv.portalUpperRightFront); - debugDisplay.DrawLine(pqv.portalUpperRightFront, pqv.portalUpperRightBack); - debugDisplay.DrawLine(pqv.portalUpperRightBack, pqv.floorRightBack); - debugDisplay.DrawLine(pqv.floorRightBack, pqv.floorRightFront); - //Front - debugDisplay.DrawLine(pqv.floorLeftFront, pqv.floorRightFront); - debugDisplay.DrawLine(pqv.floorRightFront, pqv.portalUpperRightFront); - debugDisplay.DrawLine(pqv.portalUpperRightFront, pqv.portalUpperLeftFront); - debugDisplay.DrawLine(pqv.portalUpperLeftFront, pqv.floorLeftFront); - //Back - debugDisplay.DrawLine(pqv.floorLeftBack, pqv.floorRightBack); - debugDisplay.DrawLine(pqv.floorRightBack, pqv.portalUpperRightBack); - debugDisplay.DrawLine(pqv.portalUpperRightBack, pqv.portalUpperLeftBack); - debugDisplay.DrawLine(pqv.portalUpperLeftBack, pqv.floorLeftBack); - } - - if (m_componentModeDelegate.AddedToComponentMode()) - { - AzToolsFramework::VertexContainerDisplay::DisplayVertexContainerIndices( - debugDisplay, AzToolsFramework::FixedVerticesArray(m_config.m_vertices), - GetWorldTM(), AZ::Vector3::CreateOne(), IsSelected()); - } - - debugDisplay.PopMatrix(); - } - - void EditorPortalComponent::BuildGameEntity(AZ::Entity* gameEntity) - { - gameEntity->CreateComponent(m_config); - } - - AZ::Aabb EditorPortalComponent::GetEditorSelectionBoundsViewport(const AzFramework::ViewportInfo& /*viewportInfo*/) - { - const PortalQuadVertices pqv = CalculatePortalQuadVertices(VertTranslation::Keep); - - AZ::Aabb bbox = AZ::Aabb::CreateNull(); - bbox.AddPoint(pqv.floorLeftFront); - bbox.AddPoint(pqv.floorRightFront); - bbox.AddPoint(pqv.floorLeftBack); - bbox.AddPoint(pqv.floorRightBack); - bbox.AddPoint(pqv.portalUpperLeftFront); - return bbox; - } - - bool EditorPortalComponent::EditorSelectionIntersectRayViewport( - const AzFramework::ViewportInfo& /*viewportInfo*/, const AZ::Vector3& src, - const AZ::Vector3& dir, float& distance) - { - float t; - float intermediateT = FLT_MAX; - - const PortalQuadVertices pqv = CalculatePortalQuadVertices(VertTranslation::Keep); - - //Count each quad for intersection hits, two hits implies we are intersecting the prism from outside of it (or from too far) - AZ::u8 hits = 0; - - //Bottom - if (AZ::Intersect::IntersectRayQuad(src, dir, pqv.floorLeftFront, pqv.floorRightFront, pqv.floorRightBack, pqv.floorLeftBack, t)) - { - ++hits; - intermediateT = AZStd::GetMin(t, intermediateT); - } - //Top - if (AZ::Intersect::IntersectRayQuad(src, dir, pqv.portalUpperLeftFront, pqv.portalUpperRightFront, pqv.portalUpperRightBack, pqv.portalUpperLeftBack, t)) - { - ++hits; - intermediateT = AZStd::GetMin(t, intermediateT); - } - - //Left - if (AZ::Intersect::IntersectRayQuad(src, dir, pqv.floorLeftFront, pqv.portalUpperLeftFront, pqv.portalUpperLeftBack, pqv.floorLeftBack, t)) - { - ++hits; - intermediateT = AZStd::GetMin(t, intermediateT); - } - //Right - if (AZ::Intersect::IntersectRayQuad(src, dir, pqv.floorRightFront, pqv.portalUpperRightFront, pqv.portalUpperRightBack, pqv.floorRightBack, t)) - { - ++hits; - intermediateT = AZStd::GetMin(t, intermediateT); - } - //Front - if (AZ::Intersect::IntersectRayQuad(src, dir, pqv.floorLeftFront, pqv.floorRightFront, pqv.portalUpperRightFront, pqv.portalUpperLeftFront, t)) - { - ++hits; - intermediateT = AZStd::GetMin(t, intermediateT); - } - //Back - if (AZ::Intersect::IntersectRayQuad(src, dir, pqv.floorLeftBack, pqv.floorRightBack, pqv.portalUpperRightBack, pqv.portalUpperLeftBack, t)) - { - ++hits; - intermediateT = AZStd::GetMin(t, intermediateT); - } - - if (hits > 0) - { - distance = intermediateT; - } - return hits >= 2; - } - - AZ::Aabb EditorPortalComponent::GetWorldBounds() - { - return GetLocalBounds().GetTransformedAabb(m_AZCachedWorldTransform); - } - - AZ::Aabb EditorPortalComponent::GetLocalBounds() - { - AZ::Aabb bbox = AZ::Aabb::CreateNull(); - for (const auto& vertex : m_config.m_vertices) - { - bbox.AddPoint(vertex); - } - return bbox; - } -} //namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorPortalComponent.h b/Gems/Visibility/Code/Source/EditorPortalComponent.h deleted file mode 100644 index a8e00b9698..0000000000 --- a/Gems/Visibility/Code/Source/EditorPortalComponent.h +++ /dev/null @@ -1,148 +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 -#include -#include -#include - -#include "PortalComponent.h" -#include "EditorPortalComponentBus.h" - -namespace Visibility -{ - class EditorPortalComponent; - struct PortalQuadVertices; - - class EditorPortalConfiguration - : public PortalConfiguration - { - public: - AZ_TYPE_INFO_LEGACY(EditorPortalConfiguration, "{C9F99449-7A77-50C4-9ED3-D69B923BFDBD}", PortalConfiguration); - AZ_CLASS_ALLOCATOR(EditorPortalConfiguration, AZ::SystemAllocator,0); - - static void Reflect(AZ::ReflectContext* context); - - void OnChange() override; - void OnVerticesChange() override; - - void SetEntityId(AZ::EntityId entityId); - - private: - AZ::EntityId m_entityId; - }; - - class EditorPortalComponent - : public AzToolsFramework::Components::EditorComponentBase - , private EditorPortalRequestBus::Handler - , private AZ::FixedVerticesRequestBus::Handler - , private AzFramework::EntityDebugDisplayEventBus::Handler - , private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler - , public AZ::TransformNotificationBus::Handler - , public AzFramework::BoundsRequestBus::Handler - { - friend class EditorPortalConfiguration; - - using Base = AzToolsFramework::Components::EditorComponentBase; - - public: - AZ_COMPONENT(EditorPortalComponent, "{64525CDD-7DD4-5CEF-B545-559127DC834E}", AzToolsFramework::Components::EditorComponentBase); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); - static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - - static void Reflect(AZ::ReflectContext* context); - - EditorPortalComponent() = default; - EditorPortalComponent(const EditorPortalComponent&) = delete; - EditorPortalComponent& operator=(const EditorPortalComponent&) = delete; - ~EditorPortalComponent() override; - - // EditorComponentBase overrides ... - void Activate() override; - void Deactivate() override; - void BuildGameEntity(AZ::Entity* gameEntity) override; - - // TransformNotificationBus overrides ... - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - - // EditorComponentSelectionRequestsBus overrides ... - AZ::Aabb GetEditorSelectionBoundsViewport( - const AzFramework::ViewportInfo& viewportInfo) override; - bool EditorSelectionIntersectRayViewport( - const AzFramework::ViewportInfo& viewportInfo, const AZ::Vector3& src, - const AZ::Vector3& dir, float& distance) override; - bool SupportsEditorRayIntersect() override { return true; } - - // PortalRequestBus overrides ... - void SetHeight(float height) override; - float GetHeight() override; - void SetDisplayFilled(bool filled) override; - bool GetDisplayFilled() override; - void SetAffectedBySun(bool affectedBySun) override; - bool GetAffectedBySun() override; - void SetViewDistRatio(float viewDistRatio) override; - float GetViewDistRatio() override; - void SetSkyOnly(bool skyOnly) override; - bool GetSkyOnly() override; - void SetOceanIsVisible(bool oceanVisible) override; - bool GetOceanIsVisible() override; - void SetUseDeepness(bool useDeepness) override; - bool GetUseDeepness() override; - void SetDoubleSide(bool doubleSided) override; - bool GetDoubleSide() override; - void SetLightBlending(bool lightBending) override; - bool GetLightBlending() override; - void SetLightBlendValue(float lightBendAmount) override; - float GetLightBlendValue() override; - bool GetVertex(size_t index, AZ::Vector3& vertex) const override; - bool UpdateVertex(size_t index, const AZ::Vector3& vertex) override; - size_t Size() const override { return m_config.m_vertices.size(); } - void UpdatePortalObject() override; - - // EntityDebugDisplayBus overrides ... - void DisplayEntityViewport( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; - - // BoundsRequestBus overrides ... - AZ::Aabb GetWorldBounds() override; - AZ::Aabb GetLocalBounds() override; - - private: - enum class VertTranslation - { - Keep, - Remove - }; - - PortalQuadVertices CalculatePortalQuadVertices(VertTranslation vertTranslation); - - // Reflected members - EditorPortalConfiguration m_config; - - using ComponentModeDelegate = AzToolsFramework::ComponentModeFramework::ComponentModeDelegate; - ComponentModeDelegate m_componentModeDelegate; ///< Responsible for detecting ComponentMode activation - ///< and creating a concrete ComponentMode. - - AZ::Transform m_AZCachedWorldTransform; - Matrix44 m_cryCachedWorldTransform; - IVisArea* m_area = nullptr; - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorPortalComponentMode.cpp b/Gems/Visibility/Code/Source/EditorPortalComponentMode.cpp deleted file mode 100644 index 5d9b089c65..0000000000 --- a/Gems/Visibility/Code/Source/EditorPortalComponentMode.cpp +++ /dev/null @@ -1,85 +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 "Visibility_precompiled.h" -#include "EditorPortalComponentMode.h" - -#include - -namespace Visibility -{ - AZ_CLASS_ALLOCATOR_IMPL(EditorPortalComponentMode, AZ::SystemAllocator, 0) - - EditorPortalComponentMode::EditorPortalComponentMode( - const AZ::EntityComponentIdPair& entityComponentIdPair, AZ::Uuid componentType) - : EditorBaseComponentMode(entityComponentIdPair, componentType) - { - CreateManipulators(); - - AZ::TransformNotificationBus::Handler::BusConnect(entityComponentIdPair.GetEntityId()); - EditorPortalNotificationBus::Handler::BusConnect(entityComponentIdPair.GetEntityId()); - } - - EditorPortalComponentMode::~EditorPortalComponentMode() - { - EditorPortalNotificationBus::Handler::BusDisconnect(); - AZ::TransformNotificationBus::Handler::BusDisconnect(); - - m_vertexSelection.Destroy(); - } - - void EditorPortalComponentMode::CreateManipulators() - { - using namespace AzToolsFramework; - - m_vertexSelection.Create( - AZ::EntityComponentIdPair(GetEntityId(), GetComponentId()), g_mainManipulatorManagerId, - AZStd::make_unique(), - TranslationManipulators::Dimensions::Three, - ConfigureTranslationManipulatorAppearance3d); - - m_vertexSelection.SetVertexPositionsUpdatedCallback([this]() - { - EditorPortalRequestBus::Event( - GetEntityId(), &EditorPortalRequests::UpdatePortalObject); - }); - } - - void EditorPortalComponentMode::OnTransformChanged( - const AZ::Transform& /*local*/, const AZ::Transform& world) - { - m_vertexSelection.RefreshSpace(world); - } - - void EditorPortalComponentMode::OnVerticesChangedInspector() - { - m_vertexSelection.RefreshLocal(); - } - - void EditorPortalComponentMode::Refresh() - { - // destroy and recreate manipulators when container is modified (vertices are added or removed) - m_vertexSelection.Destroy(); - CreateManipulators(); - } - - AZStd::vector EditorPortalComponentMode::PopulateActionsImpl() - { - return m_vertexSelection.ActionOverrides(); - } - - bool EditorPortalComponentMode::HandleMouseInteraction( - const AzToolsFramework::ViewportInteraction::MouseInteractionEvent& mouseInteraction) - { - return m_vertexSelection.HandleMouse(mouseInteraction); - } -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorPortalComponentMode.h b/Gems/Visibility/Code/Source/EditorPortalComponentMode.h deleted file mode 100644 index 633c3a1ba8..0000000000 --- a/Gems/Visibility/Code/Source/EditorPortalComponentMode.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. -* -*/ - -#pragma once - -#include -#include -#include - -#include "EditorPortalComponentBus.h" - -namespace Visibility -{ - class EditorPortalComponentMode - : public AzToolsFramework::ComponentModeFramework::EditorBaseComponentMode - , private AZ::TransformNotificationBus::Handler - , private EditorPortalNotificationBus::Handler - { - public: - AZ_CLASS_ALLOCATOR_DECL - - EditorPortalComponentMode( - const AZ::EntityComponentIdPair& entityComponentIdPair, AZ::Uuid componentType); - ~EditorPortalComponentMode(); - - private: - // EditorBaseComponentMode - void Refresh() override; - AZStd::vector PopulateActionsImpl() override; - bool HandleMouseInteraction( - const AzToolsFramework::ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; - - // Manipulator handling - void CreateManipulators(); - - // TransformNotificationBus - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - - // EditorPortalNotificationBus - void OnVerticesChangedInspector() override; - - AzToolsFramework::EditorVertexSelectionFixed m_vertexSelection; ///< Handles all manipulator interactions with vertices. - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp b/Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp deleted file mode 100644 index fcf2241cd3..0000000000 --- a/Gems/Visibility/Code/Source/EditorVisAreaComponent.cpp +++ /dev/null @@ -1,632 +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 "Visibility_precompiled.h" -#include "EditorVisAreaComponent.h" -#include "EditorVisAreaComponentMode.h" - -#include -#include -#include -#include -#include - -// Include files needed for writing DisplayEntity functions that access the DisplayContext directly. -#include - -#include "MathConversion.h" - -namespace Visibility -{ - /*static*/ AZ::Color EditorVisAreaComponent::s_visAreaColor = AZ::Color(1.0f, 0.5f, 0.0f, 1.0f); - - void EditorVisAreaComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("EditorVisAreaService", 0x4507d2ae)); - provided.push_back(AZ_CRC("VisAreaService", 0x0c063fb9)); - provided.push_back(AZ_CRC("VariableVertexContainerService", 0x70c58740)); - provided.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); - } - - void EditorVisAreaComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires) - { - requires.push_back(AZ_CRC("TransformService", 0x8ee22c50)); - } - - void EditorVisAreaComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("VariableVertexContainerService", 0x70c58740)); - incompatible.push_back(AZ_CRC("FixedVertexContainerService", 0x83f1bbf2)); - } - - void EditorVisAreaConfiguration::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1); - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class("VisArea Configuration", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true); - - editContext->Class("VisArea Configuration", "") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->DataElement(AZ::Edit::UIHandlers::Default, &VisAreaConfiguration::m_height, "Height", "How tall the VisArea is.") - ->Attribute(AZ::Edit::Attributes::Max, 100.0f) - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &VisAreaConfiguration::ChangeHeight) - ->DataElement(AZ::Edit::UIHandlers::Default, &VisAreaConfiguration::m_displayFilled, "DisplayFilled", "Display the VisArea as a filled volume.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &VisAreaConfiguration::ChangeDisplayFilled) - ->DataElement(AZ::Edit::UIHandlers::Default, &VisAreaConfiguration::m_affectedBySun, "AffectedBySun", "Allows sunlight to affect objects inside the VisArea.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &VisAreaConfiguration::ChangeAffectedBySun) - ->DataElement(AZ::Edit::UIHandlers::Default, &VisAreaConfiguration::m_viewDistRatio, "ViewDistRatio", "Specifies how far the VisArea is rendered.") - ->Attribute(AZ::Edit::Attributes::Max, 100.0f) - ->Attribute(AZ::Edit::Attributes::Min, 0.0f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &VisAreaConfiguration::ChangeViewDistRatio) - ->DataElement(AZ::Edit::UIHandlers::Default, &VisAreaConfiguration::m_oceanIsVisible, "OceanIsVisible", "Ocean will be visible when looking outside the VisArea.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &VisAreaConfiguration::ChangeOceanIsVisible) - // note: This will not work as expected. See Activate where we set the callbacks on the vertex container directly - ->DataElement(AZ::Edit::UIHandlers::Default, &VisAreaConfiguration::m_vertexContainer, "Vertices", "Points that make up the floor of the VisArea.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &VisAreaConfiguration::ChangeVertexContainer) - ; - } - } - } - - void EditorVisAreaComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(2) - ->Field("m_config", &EditorVisAreaComponent::m_config) - ->Field("ComponentMode", &EditorVisAreaComponent::m_componentModeDelegate) - ; - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class("VisArea", "An area where only objects inside the area will be visible.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Rendering") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/VisArea.png") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/VisArea.svg") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->Attribute(AZ::Edit::Attributes::HelpPageURL, "http://docs.aws.amazon.com/console/lumberyard/userguide/vis-area-component") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorVisAreaComponent::m_config, "m_config", "No Description") - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorVisAreaComponent::m_componentModeDelegate, "Component Mode", "VisArea Component Mode") - ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly) - ; - } - } - - if (auto behaviorContext = azrtti_cast(context)) - { - behaviorContext->EBus("EditorVisAreaComponentRequestBus") - ->Event("SetHeight", &EditorVisAreaComponentRequestBus::Events::SetHeight) - ->Event("GetHeight", &EditorVisAreaComponentRequestBus::Events::GetHeight) - ->VirtualProperty("Height", "GetHeight", "SetHeight") - - ->Event("SetDisplayFilled", &EditorVisAreaComponentRequestBus::Events::SetDisplayFilled) - ->Event("GetDisplayFilled", &EditorVisAreaComponentRequestBus::Events::GetDisplayFilled) - ->VirtualProperty("DisplayFilled", "GetDisplayFilled", "SetDisplayFilled") - - ->Event("SetAffectedBySun", &EditorVisAreaComponentRequestBus::Events::SetAffectedBySun) - ->Event("GetAffectedBySun", &EditorVisAreaComponentRequestBus::Events::GetAffectedBySun) - ->VirtualProperty("AffectedBySun", "GetAffectedBySun", "SetAffectedBySun") - - ->Event("SetViewDistRatio", &EditorVisAreaComponentRequestBus::Events::SetViewDistRatio) - ->Event("GetViewDistRatio", &EditorVisAreaComponentRequestBus::Events::GetViewDistRatio) - ->VirtualProperty("ViewDistRatio", "GetViewDistRatio", "SetViewDistRatio") - - ->Event("SetOceanIsVisible", &EditorVisAreaComponentRequestBus::Events::SetOceanIsVisible) - ->Event("GetOceanIsVisible", &EditorVisAreaComponentRequestBus::Events::GetOceanIsVisible) - ->VirtualProperty("OceanIsVisible", "GetOceanIsVisible", "SetOceanIsVisible") - ; - - behaviorContext->Class()->RequestBus("EditorVisAreaComponentRequestBus"); - } - - EditorVisAreaConfiguration::Reflect(context); - } - - void EditorVisAreaConfiguration::ChangeHeight() - { - EditorVisAreaComponentRequestBus::Event( - m_entityId, &EditorVisAreaComponentRequests::UpdateVisAreaObject); - } - - void EditorVisAreaConfiguration::ChangeDisplayFilled() - { - EditorVisAreaComponentRequestBus::Event( - m_entityId, &EditorVisAreaComponentRequests::UpdateVisAreaObject); - } - - void EditorVisAreaConfiguration::ChangeAffectedBySun() - { - EditorVisAreaComponentRequestBus::Event( - m_entityId, &EditorVisAreaComponentRequests::UpdateVisAreaObject); - } - - void EditorVisAreaConfiguration::ChangeViewDistRatio() - { - EditorVisAreaComponentRequestBus::Event( - m_entityId, &EditorVisAreaComponentRequests::UpdateVisAreaObject); - } - - void EditorVisAreaConfiguration::ChangeOceanIsVisible() - { - EditorVisAreaComponentRequestBus::Event( - m_entityId, &EditorVisAreaComponentRequests::UpdateVisAreaObject); - } - - void EditorVisAreaConfiguration::ChangeVertexContainer() - { - EditorVisAreaComponentRequestBus::Event( - m_entityId, &EditorVisAreaComponentRequests::UpdateVisAreaObject); - } - - void EditorVisAreaConfiguration::SetEntityId(const AZ::EntityId entityId) - { - m_entityId = entityId; - } - - EditorVisAreaComponent::~EditorVisAreaComponent() - { - if (m_area && GetIEditor()->Get3DEngine()) - { - // Reset the listener vis area in the unlucky case that we are deleting the - // vis area where the listener is currently in - GetIEditor()->Get3DEngine()->DeleteVisArea(m_area); - m_area = nullptr; - } - } - - void EditorVisAreaComponent::Activate() - { - Base::Activate(); - - const AZ::EntityId entityId = GetEntityId(); - - // NOTE: We create the vis-area here at activated, but destroy it in the destructor. - // We have to do this, otherwise the vis-area is not saved into the level. - // Unfortunately, at this time we cannot create the vis-areas at game runtime. - // This means that dynamic slices cannot effectively contain vis areas until we fix the core rendering system to allow that. - - const auto visGUID = AZ::u64(entityId); - if(!m_area && GetIEditor() && GetIEditor()->Get3DEngine()) - { - m_area = GetIEditor()->Get3DEngine()->CreateVisArea(visGUID); - } - - m_componentModeDelegate.ConnectWithSingleComponentMode< - EditorVisAreaComponent, EditorVisAreaComponentMode>( - AZ::EntityComponentIdPair(entityId, GetId()), this); - - // give default values to the vertices if needed - if (m_config.m_vertexContainer.Size() == 0) - { - m_config.m_vertexContainer.AddVertex(AZ::Vector3(-1.0f, -1.0f, 0.0f)); - m_config.m_vertexContainer.AddVertex(AZ::Vector3(+1.0f, -1.0f, 0.0f)); - m_config.m_vertexContainer.AddVertex(AZ::Vector3(+1.0f, +1.0f, 0.0f)); - m_config.m_vertexContainer.AddVertex(AZ::Vector3(-1.0f, +1.0f, 0.0f)); - } - - const auto vertexAdded = [this](size_t vertIndex) - { - EditorVisAreaComponentNotificationBus::Event( - GetEntityId(), &EditorVisAreaComponentNotifications::OnVertexAdded, vertIndex); - - UpdateVisAreaObject(); - }; - - const auto vertexRemoved = [this](size_t vertIndex) - { - EditorVisAreaComponentNotificationBus::Event( - GetEntityId(), &EditorVisAreaComponentNotifications::OnVertexRemoved, vertIndex); - - UpdateVisAreaObject(); - }; - - const auto vertexChanged = [this](size_t vertIndex) - { - EditorVisAreaComponentNotificationBus::Event( - GetEntityId(), &EditorVisAreaComponentNotifications::OnVertexUpdated, vertIndex); - - UpdateVisAreaObject(); - }; - - const auto verticesSet = [this]() - { - EditorVisAreaComponentNotificationBus::Event( - GetEntityId(), &EditorVisAreaComponentNotifications::OnVerticesSet, - m_config.m_vertexContainer.GetVertices()); - - UpdateVisAreaObject(); - }; - - const auto verticesCleared = [this]() - { - EditorVisAreaComponentNotificationBus::Event( - GetEntityId(), &EditorVisAreaComponentNotifications::OnVerticesCleared); - - UpdateVisAreaObject(); - }; - - m_config.m_vertexContainer.SetCallbacks( - vertexAdded, vertexRemoved, vertexChanged, - verticesSet, verticesCleared); - - m_config.SetEntityId(entityId); - - AZ::TransformBus::EventResult( - m_currentWorldTransform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); - - // make the initial vis area with the data we just parsed - UpdateVisAreaObject(); - - EditorVisAreaComponentRequestBus::Handler::BusConnect(entityId); - AZ::VariableVerticesRequestBus::Handler::BusConnect(entityId); - AZ::FixedVerticesRequestBus::Handler::BusConnect(entityId); - AZ::TransformNotificationBus::Handler::BusConnect(entityId); - AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(entityId); - AzToolsFramework::EditorEntityInfoNotificationBus::Handler::BusConnect(); - AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusConnect(entityId); - AzFramework::BoundsRequestBus::Handler::BusConnect(entityId); - } - - void EditorVisAreaComponent::Deactivate() - { - m_componentModeDelegate.Disconnect(); - - AzFramework::BoundsRequestBus::Handler::BusDisconnect(); - AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusDisconnect(); - AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); - AzToolsFramework::EditorEntityInfoNotificationBus::Handler::BusDisconnect(); - AZ::TransformNotificationBus::Handler::BusDisconnect(); - AZ::FixedVerticesRequestBus::Handler::BusDisconnect(); - AZ::VariableVerticesRequestBus::Handler::BusDisconnect(); - EditorVisAreaComponentRequestBus::Handler::BusDisconnect(); - - Base::Deactivate(); - } - - void EditorVisAreaComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) - { - m_currentWorldTransform = world; - UpdateVisAreaObject(); - } - - /// Apply the component's settings to the underlying vis area - void EditorVisAreaComponent::UpdateVisAreaObject() - { - if (m_area) - { - std::vector points; - - const AZStd::vector& vertices = m_config.m_vertexContainer.GetVertices(); - const size_t vertexCount = vertices.size(); - - if (vertexCount > 3) - { - const Matrix34& wtm = AZTransformToLYTransform(GetWorldTM()); - points.resize(vertexCount); - for (size_t i = 0; i < vertexCount; i++) - { - points[i] = wtm.TransformPoint(AZVec3ToLYVec3(vertices[i])); - } - - SVisAreaInfo info; - info.fHeight = GetHeight(); - info.bAffectedByOutLights = m_config.m_affectedBySun; - info.fViewDistRatio = m_config.m_viewDistRatio; - info.bOceanIsVisible = m_config.m_oceanIsVisible; - - //Unconfigurable; these values are used by other area types - //We set them just so that debugging later it's clear that these - //aren't being used because this is a VisArea. - info.fPortalBlending = -1; - info.bDoubleSide = true; - info.bUseDeepness = false; - info.bUseInIndoors = false; - - const AZStd::string name = AZStd::string("vis-area_") + GetEntity()->GetName(); - - if (GetIEditor()->Get3DEngine()) - { - GetIEditor()->Get3DEngine()->UpdateVisArea(m_area, &points[0], points.size(), name.c_str(), info, true); - } - - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); - } - } - } - - void EditorVisAreaComponent::SetHeight(const float value) - { - m_config.m_height = value; - UpdateVisAreaObject(); - } - - float EditorVisAreaComponent::GetHeight() - { - return m_config.m_height; - } - - void EditorVisAreaComponent::SetDisplayFilled(const bool value) - { - m_config.m_displayFilled = value; - UpdateVisAreaObject(); - } - - bool EditorVisAreaComponent::GetDisplayFilled() - { - return m_config.m_displayFilled; - } - - void EditorVisAreaComponent::SetAffectedBySun(const bool value) - { - m_config.m_affectedBySun = value; - UpdateVisAreaObject(); - } - - bool EditorVisAreaComponent::GetAffectedBySun() - { - return m_config.m_affectedBySun; - } - - void EditorVisAreaComponent::SetViewDistRatio(const float value) - { - m_config.m_viewDistRatio = value; - UpdateVisAreaObject(); - } - - float EditorVisAreaComponent::GetViewDistRatio() - { - return m_config.m_viewDistRatio; - } - - void EditorVisAreaComponent::SetOceanIsVisible(const bool value) - { - m_config.m_oceanIsVisible = value; - UpdateVisAreaObject(); - } - - bool EditorVisAreaComponent::GetOceanIsVisible() - { - return m_config.m_oceanIsVisible; - } - - bool EditorVisAreaComponent::GetVertex(size_t index, AZ::Vector3& vertex) const - { - return m_config.m_vertexContainer.GetVertex(index, vertex); - } - - void EditorVisAreaComponent::AddVertex(const AZ::Vector3& vertex) - { - m_config.m_vertexContainer.AddVertex(vertex); - UpdateVisAreaObject(); - } - - bool EditorVisAreaComponent::UpdateVertex(size_t index, const AZ::Vector3& vertex) - { - if (m_config.m_vertexContainer.UpdateVertex(index, vertex)) - { - UpdateVisAreaObject(); - return true; - } - - return false; - } - - bool EditorVisAreaComponent::InsertVertex(size_t index, const AZ::Vector3& vertex) - { - if (m_config.m_vertexContainer.InsertVertex(index, vertex)) - { - UpdateVisAreaObject(); - return true; - } - - return false; - } - - bool EditorVisAreaComponent::RemoveVertex(size_t index) - { - if (m_config.m_vertexContainer.RemoveVertex(index)) - { - UpdateVisAreaObject(); - return true; - } - - return false; - } - - void EditorVisAreaComponent::SetVertices(const AZStd::vector& vertices) - { - m_config.m_vertexContainer.SetVertices(vertices); - UpdateVisAreaObject(); - } - - void EditorVisAreaComponent::ClearVertices() - { - m_config.m_vertexContainer.Clear(); - UpdateVisAreaObject(); - } - - size_t EditorVisAreaComponent::Size() const - { - return m_config.m_vertexContainer.Size(); - } - - bool EditorVisAreaComponent::Empty() const - { - return m_config.m_vertexContainer.Empty(); - } - - void EditorVisAreaComponent::DisplayEntityViewport( - [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) - { - /* - The VisArea and Portal share a common strangeness with how they are displayed. - The Legacy visualization is actually incorrect! It's important to know that - the vis volumes essentially act as a points on an XY plane with a known Z - position and a height. The volumes that actually affect rendition are planar - quads with a height. The height is calculated by the largest height value on - a local point + the given height value on the component. - - Also note that this visualization does not display the floors or ceilings of the vis area - volumes. There is currently no way with the display context to easily draw a filled polygon. - We could try to draw some triangles but it would take up a great deal of rendering - time and could potentially slow down the editor more than we want if there are a lot - of volumes. - */ - - const AZStd::vector& vertices = m_config.m_vertexContainer.GetVertices(); - const size_t vertexCount = vertices.size(); - - //We do not want to push a transform with scale or rotation as the - //vis area is always snapped to the XY plane with a height. - //Scale will be applied during flattening - AZ::Transform translation = AZ::Transform::CreateIdentity(); - translation.SetTranslation(m_currentWorldTransform.GetTranslation()); - - debugDisplay.PushMatrix(translation); - debugDisplay.SetColor(s_visAreaColor.GetAsVector4()); - - AZStd::vector transformedPoints; - transformedPoints.resize(vertexCount); - - //Min and max Z value (in local space) - float minZ = FLT_MAX; - float maxZ = FLT_MIN; - - //Apply rotation and scale before removing translation. - //We want translation to apply with the matrix to make things easier - //but we need to calculate a difference in Z after rotation and scaling. - //During the next loop we'll flatten all these points down to a common XY plane - for (size_t i = 0; i < vertexCount; ++i) - { - AZ::Vector3 transformedPoint = m_currentWorldTransform.TransformPoint(vertices[i]); - - //Back into local space - transformedPoints[i] = transformedPoint - m_currentWorldTransform.GetTranslation(); - - const float transformedZ = transformedPoints[i].GetZ(); - - minZ = AZ::GetMin(transformedZ, minZ); - maxZ = AZ::GetMax(transformedZ, maxZ); - } - - //The height of the vis area + the max local height - const float actualHeight = m_config.m_height + maxZ; - - //Draw walls for every line segment - size_t transformedPointCount = transformedPoints.size(); - for (size_t i = 0; i < transformedPointCount; ++i) - { - AZ::Vector3 lowerLeft = AZ::Vector3(); - AZ::Vector3 lowerRight = AZ::Vector3(); - AZ::Vector3 upperRight = AZ::Vector3(); - AZ::Vector3 upperLeft = AZ::Vector3(); - - lowerLeft = transformedPoints[i]; - lowerRight = transformedPoints[(i + 1) % transformedPointCount]; - //The mod with transformedPointCount ensures that for the last vert it will connect back with vert 0 - //If vert count is 10, the last vert will be i = 9 and we want that to create a surface with vert 0 - - //Make all lower points planar - lowerLeft.SetZ(minZ); - lowerRight.SetZ(minZ); - - upperRight = AZ::Vector3(lowerRight.GetX(), lowerRight.GetY(), actualHeight); - upperLeft = AZ::Vector3(lowerLeft.GetX(), lowerLeft.GetY(), actualHeight); - - if (m_config.m_displayFilled) - { - debugDisplay.SetAlpha(0.3f); - //Draw filled quad with two winding orders to make it double sided - debugDisplay.DrawQuad(lowerLeft, lowerRight, upperRight, upperLeft); - debugDisplay.DrawQuad(lowerLeft, upperLeft, upperRight, lowerRight); - } - - debugDisplay.SetAlpha(1.0f); - debugDisplay.DrawLine(lowerLeft, lowerRight); - debugDisplay.DrawLine(lowerRight, upperRight); - debugDisplay.DrawLine(upperRight, upperLeft); - debugDisplay.DrawLine(upperLeft, lowerLeft); - } - - if (m_componentModeDelegate.AddedToComponentMode()) - { - AzToolsFramework::VertexContainerDisplay::DisplayVertexContainerIndices( - debugDisplay, AzToolsFramework::VariableVerticesVertexContainer(m_config.m_vertexContainer), - GetWorldTM(), AZ::Vector3::CreateOne(), IsSelected()); - } - - debugDisplay.PopMatrix(); - } - - void EditorVisAreaComponent::BuildGameEntity(AZ::Entity* gameEntity) - { - gameEntity->CreateComponent(m_config); - } - - AZ::Aabb EditorVisAreaComponent::GetEditorSelectionBoundsViewport( - const AzFramework::ViewportInfo& /*viewportInfo*/) - { - return GetWorldBounds(); - } - - bool EditorVisAreaComponent::EditorSelectionIntersectRayViewport( - const AzFramework::ViewportInfo& viewportInfo, const AZ::Vector3& src, - const AZ::Vector3& dir, float& distance) - { - AZ::Aabb bbox = GetEditorSelectionBoundsViewport(viewportInfo); - float end; - float t; - - const bool intersection = AZ::Intersect::IntersectRayAABB2( - src, dir.GetReciprocal(), - bbox, t, end) > 0; - - if (intersection) - { - distance = t; - } - - return intersection; - } - - AZ::Aabb EditorVisAreaComponent::GetWorldBounds() - { - return GetLocalBounds().GetTransformedAabb(GetWorldTM()); - } - - AZ::Aabb EditorVisAreaComponent::GetLocalBounds() - { - AZ::Aabb bbox = AZ::Aabb::CreateNull(); - for (const auto& vertex : m_config.m_vertexContainer.GetVertices()) - { - bbox.AddPoint(vertex); - } - bbox.AddPoint(bbox.GetMax() + AZ::Vector3::CreateAxisZ(m_config.m_height)); - return bbox; - } -} //namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorVisAreaComponent.h b/Gems/Visibility/Code/Source/EditorVisAreaComponent.h deleted file mode 100644 index 45c87e13cc..0000000000 --- a/Gems/Visibility/Code/Source/EditorVisAreaComponent.h +++ /dev/null @@ -1,144 +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 -#include -#include -#include -#include -#include -#include - -#include "EditorVisAreaComponentBus.h" -#include "VisAreaComponent.h" - -namespace Visibility -{ - class EditorVisAreaComponent; - - class EditorVisAreaConfiguration - : public VisAreaConfiguration - { - public: - AZ_TYPE_INFO_LEGACY(EditorVisAreaConfiguration, "{C329E65C-1F34-5C80-9A7A-4B568105256B}", VisAreaConfiguration); - AZ_CLASS_ALLOCATOR(EditorVisAreaConfiguration, AZ::SystemAllocator,0); - - static void Reflect(AZ::ReflectContext* context); - - void ChangeHeight() override; - void ChangeDisplayFilled() override; - void ChangeAffectedBySun() override; - void ChangeViewDistRatio() override; - void ChangeOceanIsVisible() override; - void ChangeVertexContainer() override; - - void SetEntityId(AZ::EntityId entityId); - - private: - AZ::EntityId m_entityId; - }; - - class EditorVisAreaComponent - : public AzToolsFramework::Components::EditorComponentBase - , private EditorVisAreaComponentRequestBus::Handler - , private AZ::FixedVerticesRequestBus::Handler - , private AZ::VariableVerticesRequestBus::Handler - , private AzFramework::EntityDebugDisplayEventBus::Handler - , private AzToolsFramework::EditorEntityInfoNotificationBus::Handler - , private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler - , private AZ::TransformNotificationBus::Handler - , public AzFramework::BoundsRequestBus::Handler - { - friend class EditorVisAreaConfiguration; //So that the config can set m_vertices when the vertex container changes - - using Base = AzToolsFramework::Components::EditorComponentBase; - - public: - AZ_COMPONENT(EditorVisAreaComponent, "{F4EC32D8-D4DD-54F7-97A8-D195497D5F2C}", AzToolsFramework::Components::EditorComponentBase); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - - static void Reflect(AZ::ReflectContext* context); - - EditorVisAreaComponent() = default; - EditorVisAreaComponent(const EditorVisAreaComponent&) = delete; - EditorVisAreaComponent& operator=(const EditorVisAreaComponent&) = delete; - virtual ~EditorVisAreaComponent(); - - // AZ::Component overrides ... - void Activate() override; - void Deactivate() override; - void BuildGameEntity(AZ::Entity* gameEntity) override; - - // TransformNotificationBus overrides ... - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - - // EditorComponentSelectionRequestsBus overrides ... - AZ::Aabb GetEditorSelectionBoundsViewport( - const AzFramework::ViewportInfo& viewportInfo) override; - bool EditorSelectionIntersectRayViewport( - const AzFramework::ViewportInfo& viewportInfo, const AZ::Vector3& src, - const AZ::Vector3& dir, float& distance) override; - bool SupportsEditorRayIntersect() override { return true; } - - // VisAreaComponentRequestBus overrides ... - void SetHeight(float height) override; - float GetHeight() override; - void SetDisplayFilled(bool filled) override; - bool GetDisplayFilled() override; - void SetAffectedBySun(bool affectedBySun) override; - bool GetAffectedBySun() override; - void SetViewDistRatio(float viewDistRatio) override; - float GetViewDistRatio() override; - void SetOceanIsVisible(bool oceanVisible) override; - bool GetOceanIsVisible() override; - bool GetVertex(size_t index, AZ::Vector3& vertex) const override; - void AddVertex(const AZ::Vector3& vertex) override; - bool UpdateVertex(size_t index, const AZ::Vector3& vertex) override; - bool InsertVertex(size_t index, const AZ::Vector3& vertex) override; - bool RemoveVertex(size_t index) override; - void SetVertices(const AZStd::vector& vertices) override; - void ClearVertices() override; - size_t Size() const override; - bool Empty() const override; - void UpdateVisAreaObject() override; - - // AzFramework::EntityDebugDisplayEventBus overrides ... - void DisplayEntityViewport( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; - - // BoundsRequestBus overrides ... - AZ::Aabb GetWorldBounds() override; - AZ::Aabb GetLocalBounds() override; - - private: - // Reflected members - EditorVisAreaConfiguration m_config; - - using ComponentModeDelegate = AzToolsFramework::ComponentModeFramework::ComponentModeDelegate; - ComponentModeDelegate m_componentModeDelegate; ///< Responsible for detecting ComponentMode activation - ///< and creating a concrete ComponentMode. - - // Unreflected members - AZ::Transform m_currentWorldTransform; - IVisArea* m_area = nullptr; - - static AZ::Color s_visAreaColor; ///< The orange color that all vis-areas draw with. - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorVisAreaComponentMode.cpp b/Gems/Visibility/Code/Source/EditorVisAreaComponentMode.cpp deleted file mode 100644 index d479e51345..0000000000 --- a/Gems/Visibility/Code/Source/EditorVisAreaComponentMode.cpp +++ /dev/null @@ -1,120 +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 "Visibility_precompiled.h" -#include "EditorVisAreaComponentMode.h" - -#include -#include - -namespace Visibility -{ - AZ_CLASS_ALLOCATOR_IMPL(EditorVisAreaComponentMode, AZ::SystemAllocator, 0) - - EditorVisAreaComponentMode::EditorVisAreaComponentMode( - const AZ::EntityComponentIdPair& entityComponentIdPair, AZ::Uuid componentType) - : EditorBaseComponentMode(entityComponentIdPair, componentType) - { - CreateManipulators(); - - AZ::TransformNotificationBus::Handler::BusConnect(entityComponentIdPair.GetEntityId()); - EditorVisAreaComponentNotificationBus::Handler::BusConnect(entityComponentIdPair.GetEntityId()); - } - - EditorVisAreaComponentMode::~EditorVisAreaComponentMode() - { - EditorVisAreaComponentNotificationBus::Handler::BusDisconnect(); - AZ::TransformNotificationBus::Handler::BusDisconnect(); - - m_vertexSelection.Destroy(); - } - - void EditorVisAreaComponentMode::CreateManipulators() - { - using namespace AzToolsFramework; - - m_vertexSelection.Create( - GetEntityComponentIdPair(), g_mainManipulatorManagerId, - AZStd::make_unique>(GetEntityComponentIdPair(), g_mainManipulatorManagerId), - TranslationManipulators::Dimensions::Three, - ConfigureTranslationManipulatorAppearance3d); - - m_vertexSelection.SetVertexPositionsUpdatedCallback([this]() - { - EditorVisAreaComponentRequestBus::Event( - GetEntityId(), &EditorVisAreaComponentRequests::UpdateVisAreaObject); - }); - } - - void EditorVisAreaComponentMode::OnTransformChanged( - const AZ::Transform& /*local*/, const AZ::Transform& world) - { - m_vertexSelection.RefreshSpace(world); - } - - void EditorVisAreaComponentMode::OnVertexAdded(size_t index) - { - Refresh(); - - AZ::Vector3 vertex; - bool found = false; - AZ::FixedVerticesRequestBus::EventResult( - found, GetEntityId(), &AZ::FixedVerticesRequestBus::Handler::GetVertex, - index, vertex); - - if (found) - { - m_vertexSelection.CreateTranslationManipulator( - GetEntityComponentIdPair(), AzToolsFramework::g_mainManipulatorManagerId, - vertex, index); - } - } - - void EditorVisAreaComponentMode::OnVertexRemoved(size_t /*index*/) - { - Refresh(); - } - - void EditorVisAreaComponentMode::OnVerticesSet(const AZStd::vector& /*vertices*/) - { - Refresh(); - } - - void EditorVisAreaComponentMode::OnVerticesCleared() - { - Refresh(); - } - - void EditorVisAreaComponentMode::Refresh() - { - // destroy and recreate manipulators when container is modified (vertices are added or removed) - m_vertexSelection.Destroy(); - CreateManipulators(); - } - - AZStd::vector EditorVisAreaComponentMode::PopulateActionsImpl() - { - return m_vertexSelection.ActionOverrides(); - } - - bool EditorVisAreaComponentMode::HandleMouseInteraction( - const AzToolsFramework::ViewportInteraction::MouseInteractionEvent& mouseInteraction) - { - return m_vertexSelection.HandleMouse(mouseInteraction); - } - - AZStd::string EditorVisAreaComponentMode::GetComponentModeName() const - { - return "Vis Area Edit Mode"; - } - -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/EditorVisAreaComponentMode.h b/Gems/Visibility/Code/Source/EditorVisAreaComponentMode.h deleted file mode 100644 index e33aed32f0..0000000000 --- a/Gems/Visibility/Code/Source/EditorVisAreaComponentMode.h +++ /dev/null @@ -1,58 +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 "EditorVisAreaComponentBus.h" - -namespace Visibility -{ - /// The ComponentMode for editing the Vis Area Component. - class EditorVisAreaComponentMode - : public AzToolsFramework::ComponentModeFramework::EditorBaseComponentMode - , private AZ::TransformNotificationBus::Handler - , private EditorVisAreaComponentNotificationBus::Handler - { - public: - AZ_CLASS_ALLOCATOR_DECL - - EditorVisAreaComponentMode( - const AZ::EntityComponentIdPair& entityComponentIdPair, AZ::Uuid componentType); - ~EditorVisAreaComponentMode(); - - private: - // EditorBaseComponentMode - void Refresh() override; - AZStd::vector PopulateActionsImpl() override; - bool HandleMouseInteraction( - const AzToolsFramework::ViewportInteraction::MouseInteractionEvent& mouseInteraction) override; - AZStd::string GetComponentModeName() const override; - - // Manipulator handling - void CreateManipulators(); - - // TransformNotificationBus - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - - // EditorVisAreaComponentNotificationBus - void OnVertexAdded(size_t index) override; - void OnVertexRemoved(size_t index) override; - void OnVerticesSet(const AZStd::vector& vertices) override; - void OnVerticesCleared() override; - - AzToolsFramework::EditorVertexSelectionVariable m_vertexSelection; ///< Handles all manipulator interactions with vertices (inserting and translating). - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/OccluderAreaComponent.cpp b/Gems/Visibility/Code/Source/OccluderAreaComponent.cpp deleted file mode 100644 index 947bc3a38b..0000000000 --- a/Gems/Visibility/Code/Source/OccluderAreaComponent.cpp +++ /dev/null @@ -1,115 +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 "Visibility_precompiled.h" -#include "OccluderAreaComponent.h" - -#include -#include -#include - -namespace Visibility -{ - void OccluderAreaComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides) - { - provides.push_back(AZ_CRC("OccluderAreaService")); - } - void OccluderAreaComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires) - { - requires.push_back(AZ_CRC("TransformService")); - } - - void OccluderAreaConfiguration::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("DisplayFilled", &OccluderAreaConfiguration::m_displayFilled) - ->Field("CullDistRatio", &OccluderAreaConfiguration::m_cullDistRatio) - ->Field("UseInIndoors", &OccluderAreaConfiguration::m_useInIndoors) - ->Field("DoubleSide", &OccluderAreaConfiguration::m_doubleSide) - ->Field("vertices", &OccluderAreaConfiguration::m_vertices) - ; - } - - if (auto behaviorContext = azrtti_cast(context)) - { - behaviorContext->EBus("OccluderAreaRequestBus") - ->Event("GetDisplayFilled", &OccluderAreaRequestBus::Events::GetDisplayFilled) - ->VirtualProperty("DisplayFilled", "GetDisplayFilled", nullptr) - - ->Event("GetCullDistRatio", &OccluderAreaRequestBus::Events::GetCullDistRatio) - ->VirtualProperty("CullDistRatio", "GetCullDistRatio", nullptr) - - ->Event("GetUseInIndoors", &OccluderAreaRequestBus::Events::GetUseInIndoors) - ->VirtualProperty("UseInIndoors", "GetUseInIndoors", nullptr) - - ->Event("GetDoubleSide", &OccluderAreaRequestBus::Events::GetDoubleSide) - ->VirtualProperty("DoubleSide", "GetDoubleSide", nullptr) - ; - - behaviorContext->Class()->RequestBus("OccluderAreaRequestBus"); - } - } - - void OccluderAreaComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("m_config", &OccluderAreaComponent::m_config) - ; - } - - OccluderAreaConfiguration::Reflect(context); - } - - OccluderAreaComponent::OccluderAreaComponent(const OccluderAreaConfiguration& params) - : m_config(params) - { - } - - void OccluderAreaComponent::Activate() - { - OccluderAreaRequestBus::Handler::BusConnect(GetEntityId()); - AZ::TransformNotificationBus::Handler::BusConnect(GetEntityId()); - } - - void OccluderAreaComponent::Deactivate() - { - AZ::TransformNotificationBus::Handler::BusDisconnect(GetEntityId()); - OccluderAreaRequestBus::Handler::BusDisconnect(GetEntityId()); - } - - bool OccluderAreaComponent::GetDisplayFilled() - { - return m_config.m_displayFilled; - } - - float OccluderAreaComponent::GetCullDistRatio() - { - return m_config.m_cullDistRatio; - } - - bool OccluderAreaComponent::GetUseInIndoors() - { - return m_config.m_useInIndoors; - } - - bool OccluderAreaComponent::GetDoubleSide() - { - return m_config.m_doubleSide; - } - -} //namespace Visibility diff --git a/Gems/Visibility/Code/Source/OccluderAreaComponent.h b/Gems/Visibility/Code/Source/OccluderAreaComponent.h deleted file mode 100644 index 80d98af4df..0000000000 --- a/Gems/Visibility/Code/Source/OccluderAreaComponent.h +++ /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. - * - */ - -#pragma once - -#include -#include -#include - -#include "OccluderAreaComponentBus.h" - -namespace Visibility -{ - class OccluderAreaConfiguration - { - public: - AZ_TYPE_INFO(OccluderAreaConfiguration, "{F024EC7E-717F-576C-8C22-09CAFEFEAF29}"); - AZ_CLASS_ALLOCATOR(OccluderAreaConfiguration, AZ::SystemAllocator, 0); - - virtual ~OccluderAreaConfiguration() = default; - - static void Reflect(AZ::ReflectContext* context); - - bool m_displayFilled = true; - float m_cullDistRatio = 100.0f; - bool m_useInIndoors = false; - bool m_doubleSide = true; - - AZStd::array m_vertices = - AZStd::array { { - AZ::Vector3(-1.0f, -1.0f, 0.0f), - AZ::Vector3( 1.0f, -1.0f, 0.0f), - AZ::Vector3( 1.0f, 1.0f, 0.0f), - AZ::Vector3(-1.0f, 1.0f, 0.0f) - } }; - - virtual void OnChange() {} - virtual void OnVerticesChange() {} - }; - - class OccluderAreaComponent - : public AZ::Component - , private OccluderAreaRequestBus::Handler - , public AZ::TransformNotificationBus::Handler - { - public: - AZ_COMPONENT(OccluderAreaComponent, "{B3C90C5F-0F9B-5D4F-ABAE-6D16CB45CB5A}", AZ::Component); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires); - static void Reflect(AZ::ReflectContext* context); - - OccluderAreaComponent() = default; - explicit OccluderAreaComponent(const OccluderAreaConfiguration& params); - - // AZ::Component - void Activate() override; - void Deactivate() override; - - // OccluderAreaRequestBus - bool GetDisplayFilled() override; - float GetCullDistRatio() override; - bool GetUseInIndoors() override; - bool GetDoubleSide() override; - - protected: - // Reflected Data - OccluderAreaConfiguration m_config; - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/PortalComponent.cpp b/Gems/Visibility/Code/Source/PortalComponent.cpp deleted file mode 100644 index 9f1f618607..0000000000 --- a/Gems/Visibility/Code/Source/PortalComponent.cpp +++ /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. -* -*/ - -#include "Visibility_precompiled.h" -#include "PortalComponent.h" - -#include -#include - -namespace Visibility -{ - void PortalComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides) - { - provides.push_back(AZ::Crc32("PortalService")); - } - - void PortalComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires) - { - requires.push_back(AZ::Crc32("TransformService")); - } - - void PortalConfiguration::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("Height", &PortalConfiguration::m_height) - ->Field("DisplayFilled", &PortalConfiguration::m_displayFilled) - ->Field("AffectedBySun", &PortalConfiguration::m_affectedBySun) - ->Field("ViewDistRatio", &PortalConfiguration::m_viewDistRatio) - ->Field("SkyOnly", &PortalConfiguration::m_skyOnly) - ->Field("OceanIsVisible", &PortalConfiguration::m_oceanIsVisible) - ->Field("UseDeepness", &PortalConfiguration::m_useDeepness) - ->Field("DoubleSide", &PortalConfiguration::m_doubleSide) - ->Field("LightBlending", &PortalConfiguration::m_lightBlending) - ->Field("LightBlendValue", &PortalConfiguration::m_lightBlendValue) - ->Field("vertices", &PortalConfiguration::m_vertices) - ; - } - - if (auto* behaviorContext = azrtti_cast(context)) - { - behaviorContext->EBus("PortalRequestBus") - ->Event("GetHeight", &PortalRequestBus::Events::GetHeight) - ->VirtualProperty("Height", "GetHeight", nullptr) - - ->Event("GetDisplayFilled", &PortalRequestBus::Events::GetDisplayFilled) - ->VirtualProperty("DisplayFilled", "GetDisplayFilled", nullptr) - - ->Event("GetAffectedBySun", &PortalRequestBus::Events::GetAffectedBySun) - ->VirtualProperty("AffectedBySun", "GetAffectedBySun", nullptr) - - ->Event("GetViewDistRatio", &PortalRequestBus::Events::GetViewDistRatio) - ->VirtualProperty("ViewDistRatio", "GetViewDistRatio", nullptr) - - ->Event("GetSkyOnly", &PortalRequestBus::Events::GetSkyOnly) - ->VirtualProperty("SkyOnly", "GetSkyOnly", nullptr) - - ->Event("GetOceanIsVisible", &PortalRequestBus::Events::GetOceanIsVisible) - ->VirtualProperty("OceanIsVisible", "GetOceanIsVisible", nullptr) - - ->Event("GetUseDeepness", &PortalRequestBus::Events::GetUseDeepness) - ->VirtualProperty("UseDeepness", "GetUseDeepness", nullptr) - - ->Event("GetDoubleSide", &PortalRequestBus::Events::GetDoubleSide) - ->VirtualProperty("DoubleSide", "GetDoubleSide", nullptr) - - ->Event("GetLightBlending", &PortalRequestBus::Events::GetLightBlending) - ->VirtualProperty("LightBlending", "GetLightBlending", nullptr) - - ->Event("GetLightBlendValue", &PortalRequestBus::Events::GetLightBlendValue) - ->VirtualProperty("LightBlendValue", "GetLightBlendValue", nullptr) - ; - - behaviorContext->Class()->RequestBus("PortalRequestBus"); - } - } - - bool PortalConfiguration::VersionConverter( - [[maybe_unused]] AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) - { - // conversion from version 1: - // - Remove IgnoreSkyColor - // - Remove IgnoreGI - if (classElement.GetVersion() <= 1) - { - classElement.RemoveElementByName(AZ_CRC("IgnoreSkyColor")); - classElement.RemoveElementByName(AZ_CRC("IgnoreGI")); - } - - return true; - } - - void PortalComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("m_config", &PortalComponent::m_config) - ; - } - - PortalConfiguration::Reflect(context); - } - - PortalComponent::PortalComponent(const PortalConfiguration& params) - : m_config(params) - { - } - - void PortalComponent::Activate() - { - PortalRequestBus::Handler::BusConnect(GetEntityId()); - } - - void PortalComponent::Deactivate() - { - PortalRequestBus::Handler::BusDisconnect(GetEntityId()); - } - - float PortalComponent::GetHeight() - { - return m_config.m_height; - } - - bool PortalComponent::GetDisplayFilled() - { - return m_config.m_displayFilled; - } - - bool PortalComponent::GetAffectedBySun() - { - return m_config.m_affectedBySun; - } - - float PortalComponent::GetViewDistRatio() - { - return m_config.m_viewDistRatio; - } - - bool PortalComponent::GetSkyOnly() - { - return m_config.m_skyOnly; - } - - bool PortalComponent::GetOceanIsVisible() - { - return m_config.m_oceanIsVisible; - } - - bool PortalComponent::GetUseDeepness() - { - return m_config.m_useDeepness; - } - - bool PortalComponent::GetDoubleSide() - { - return m_config.m_doubleSide; - } - - bool PortalComponent::GetLightBlending() - { - return m_config.m_lightBlending; - } - - float PortalComponent::GetLightBlendValue() - { - return m_config.m_lightBlendValue; - } - -} //namespace Visibility diff --git a/Gems/Visibility/Code/Source/PortalComponent.h b/Gems/Visibility/Code/Source/PortalComponent.h deleted file mode 100644 index fd6ce4ab77..0000000000 --- a/Gems/Visibility/Code/Source/PortalComponent.h +++ /dev/null @@ -1,92 +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 "PortalComponentBus.h" - -namespace Visibility -{ - class PortalConfiguration - { - public: - AZ_TYPE_INFO(PortalConfiguration, "{B9BDF017-DF8B-5DBE-8A92-5F62B7AECC1C}"); - AZ_CLASS_ALLOCATOR(PortalConfiguration, AZ::SystemAllocator,0); - - virtual ~PortalConfiguration() = default; - - static void Reflect(AZ::ReflectContext* context); - static bool VersionConverter( - AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement); - - float m_height = 1.0f; - bool m_displayFilled = false; - bool m_affectedBySun = false; - float m_viewDistRatio = 100.0f; - bool m_skyOnly = false; - bool m_oceanIsVisible = false; - bool m_useDeepness = true; - bool m_doubleSide = true; - bool m_lightBlending = true; - float m_lightBlendValue = 0.5f; - - AZStd::array m_vertices = - AZStd::array { { - AZ::Vector3(-1.0f, -1.0f, 0.0f), - AZ::Vector3( 1.0f, -1.0f, 0.0f), - AZ::Vector3( 1.0f, 1.0f, 0.0f), - AZ::Vector3(-1.0f, 1.0f, 0.0f) - } }; - - virtual void OnChange() {} - virtual void OnVerticesChange() {} - }; - - class PortalComponent - : public AZ::Component - , private PortalRequestBus::Handler - { - public: - AZ_COMPONENT(PortalComponent, "{89F1DD88-4445-5A9D-9223-6D4D8D44E6AC}", AZ::Component); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires); - static void Reflect(AZ::ReflectContext* context); - - PortalComponent() = default; - explicit PortalComponent(const PortalConfiguration& params); - - // AZ::Component - void Activate() override; - void Deactivate() override; - - // PortalRequestBus - float GetHeight() override; - bool GetDisplayFilled() override; - bool GetAffectedBySun() override; - float GetViewDistRatio() override; - bool GetSkyOnly() override; - bool GetOceanIsVisible() override; - bool GetUseDeepness() override; - bool GetDoubleSide() override; - bool GetLightBlending() override; - float GetLightBlendValue() override; - - protected: - // Reflected Data - PortalConfiguration m_config; - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/VisAreaComponent.cpp b/Gems/Visibility/Code/Source/VisAreaComponent.cpp deleted file mode 100644 index 7db60f1688..0000000000 --- a/Gems/Visibility/Code/Source/VisAreaComponent.cpp +++ /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. -* -*/ - -#include "Visibility_precompiled.h" -#include "VisAreaComponent.h" - -#include -#include - -namespace Visibility -{ - void VisAreaComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides) - { - provides.push_back(AZ::Crc32("VisAreaService")); - } - - void VisAreaComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires) - { - requires.push_back(AZ::Crc32("TransformService")); - } - - void VisAreaConfiguration::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(2, &VersionConverter) - ->Field("m_Height", &VisAreaConfiguration::m_height) - ->Field("m_DisplayFilled", &VisAreaConfiguration::m_displayFilled) - ->Field("m_AffectedBySun", &VisAreaConfiguration::m_affectedBySun) - ->Field("m_ViewDistRatio", &VisAreaConfiguration::m_viewDistRatio) - ->Field("m_OceanIsVisible", &VisAreaConfiguration::m_oceanIsVisible) - ->Field("m_vertexContainer", &VisAreaConfiguration::m_vertexContainer) - ; - } - - if (auto behaviorContext = azrtti_cast(context)) - { - behaviorContext->EBus("VisAreaComponentRequestBus") - ->Event("GetHeight", &VisAreaComponentRequestBus::Events::GetHeight) - ->VirtualProperty("Height", "GetHeight", nullptr) - - ->Event("GetDisplayFilled", &VisAreaComponentRequestBus::Events::GetDisplayFilled) - ->VirtualProperty("DisplayFilled", "GetDisplayFilled", nullptr) - - ->Event("GetAffectedBySun", &VisAreaComponentRequestBus::Events::GetAffectedBySun) - ->VirtualProperty("AffectedBySun", "GetAffectedBySun", nullptr) - - ->Event("GetViewDistRatio", &VisAreaComponentRequestBus::Events::GetViewDistRatio) - ->VirtualProperty("ViewDistRatio", "GetViewDistRatio", nullptr) - - ->Event("GetOceanIsVisible", &VisAreaComponentRequestBus::Events::GetOceanIsVisible) - ->VirtualProperty("OceanIsVisible", "GetOceanIsVisible", nullptr) - ; - - behaviorContext->Class()->RequestBus("VisAreaComponentRequestBus"); - } - } - - bool VisAreaConfiguration::VersionConverter([[maybe_unused]] AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) - { - // conversion from version 1: - // - Remove IgnoreSkyColor - // - Remove IgnoreGI - // - Remove SkyOnly - if (classElement.GetVersion() <= 1) - { - classElement.RemoveElementByName(AZ_CRC("IgnoreSkyColor")); - classElement.RemoveElementByName(AZ_CRC("IgnoreGI")); - classElement.RemoveElementByName(AZ_CRC("SkyOnly")); - } - - return true; - } - - void VisAreaComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("m_config", &VisAreaComponent::m_config) - ; - } - - VisAreaConfiguration::Reflect(context); - } - - VisAreaComponent::VisAreaComponent(const VisAreaConfiguration& params) - : m_config(params) - { - } - - void VisAreaComponent::Activate() - { - VisAreaComponentRequestBus::Handler::BusConnect(GetEntityId()); - } - - void VisAreaComponent::Deactivate() - { - VisAreaComponentRequestBus::Handler::BusDisconnect(GetEntityId()); - } - - float VisAreaComponent::GetHeight() - { - return m_config.m_height; - } - - bool VisAreaComponent::GetDisplayFilled() - { - return m_config.m_displayFilled; - } - - bool VisAreaComponent::GetAffectedBySun() - { - return m_config.m_affectedBySun; - } - - float VisAreaComponent::GetViewDistRatio() - { - return m_config.m_viewDistRatio; - } - - bool VisAreaComponent::GetOceanIsVisible() - { - return m_config.m_oceanIsVisible; - } -} //namespace Visibility diff --git a/Gems/Visibility/Code/Source/VisAreaComponent.h b/Gems/Visibility/Code/Source/VisAreaComponent.h deleted file mode 100644 index f2efe7167d..0000000000 --- a/Gems/Visibility/Code/Source/VisAreaComponent.h +++ /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. -* -*/ - -#pragma once - -#include -#include -#include -#include - -#include "VisAreaComponentBus.h" - -namespace Visibility -{ - class VisAreaConfiguration - { - public: - AZ_TYPE_INFO(VisAreaConfiguration, "{160D9FC2-936F-59BB-827C-DEF89671E4DC}"); - AZ_CLASS_ALLOCATOR(VisAreaConfiguration, AZ::SystemAllocator,0); - - virtual ~VisAreaConfiguration() = default; - - static void Reflect(AZ::ReflectContext* context); - static bool VersionConverter( - AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement); - - float m_height = 5.0f; - bool m_displayFilled = false; - bool m_affectedBySun = false; - float m_viewDistRatio = 100.0f; - bool m_oceanIsVisible = false; - AZ::VertexContainer m_vertexContainer; - - virtual void ChangeHeight() {} - virtual void ChangeDisplayFilled() {} - virtual void ChangeAffectedBySun() {} - virtual void ChangeViewDistRatio() {} - virtual void ChangeOceanIsVisible() {} - virtual void ChangeVertexContainer() {} - }; - - class VisAreaComponent - : public AZ::Component - , private VisAreaComponentRequestBus::Handler - { - public: - AZ_COMPONENT(VisAreaComponent, "{ACAB60F8-100E-5EAF-BE2B-D60F79312404}", AZ::Component); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provides); - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& requires); - static void Reflect(AZ::ReflectContext* context); - - VisAreaComponent() = default; - explicit VisAreaComponent(const VisAreaConfiguration& params); - - // AZ::Component - void Activate() override; - void Deactivate() override; - - // VisAreaComponentRequestBus - float GetHeight() override; - bool GetDisplayFilled() override; - bool GetAffectedBySun() override; - float GetViewDistRatio() override; - bool GetOceanIsVisible() override; - - private: - VisAreaConfiguration m_config; ///< Reflected configuration. - }; -} // namespace Visibility diff --git a/Gems/Visibility/Code/Source/VisibilityGem.cpp b/Gems/Visibility/Code/Source/VisibilityGem.cpp deleted file mode 100644 index 37d31a56f6..0000000000 --- a/Gems/Visibility/Code/Source/VisibilityGem.cpp +++ /dev/null @@ -1,39 +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 "Visibility_precompiled.h" - -#include "VisibilityGem.h" - -#include "OccluderAreaComponent.h" -#include "PortalComponent.h" -#include "VisAreaComponent.h" - -#ifdef VISIBILITY_EDITOR -#include "EditorOccluderAreaComponent.h" -#include "EditorPortalComponent.h" -#include "EditorVisAreaComponent.h" -#endif //VISIBILITY_EDITOR - -VisibilityGem::VisibilityGem() -{ - m_descriptors.push_back(Visibility::OccluderAreaComponent::CreateDescriptor()); - m_descriptors.push_back(Visibility::PortalComponent::CreateDescriptor()); - m_descriptors.push_back(Visibility::VisAreaComponent::CreateDescriptor()); - -#ifdef VISIBILITY_EDITOR - m_descriptors.push_back(Visibility::EditorOccluderAreaComponent::CreateDescriptor()); - m_descriptors.push_back(Visibility::EditorPortalComponent::CreateDescriptor()); - m_descriptors.push_back(Visibility::EditorVisAreaComponent::CreateDescriptor()); -#endif //VISIBILITY_EDITOR -} - -AZ_DECLARE_MODULE_CLASS(Gem_Visibility, VisibilityGem) diff --git a/Gems/Visibility/Code/Source/VisibilityGem.h b/Gems/Visibility/Code/Source/VisibilityGem.h deleted file mode 100644 index 1abc1b8901..0000000000 --- a/Gems/Visibility/Code/Source/VisibilityGem.h +++ /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. -* -*/ - -#pragma once - -#include - -#include - - -class VisibilityGem - : public AZ::Module -{ -public: - AZ_RTTI(VisibilityGem, "{5138F2B6-EDFB-490E-AB3E-B82E43263A20}"); - - VisibilityGem(); -}; diff --git a/Gems/Visibility/Code/Source/Visibility_precompiled.cpp b/Gems/Visibility/Code/Source/Visibility_precompiled.cpp deleted file mode 100644 index 6d32d0ea69..0000000000 --- a/Gems/Visibility/Code/Source/Visibility_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 "Visibility_precompiled.h" diff --git a/Gems/Visibility/Code/Source/Visibility_precompiled.h b/Gems/Visibility/Code/Source/Visibility_precompiled.h deleted file mode 100644 index 2a1bc2e083..0000000000 --- a/Gems/Visibility/Code/Source/Visibility_precompiled.h +++ /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 - -#include -#include -#include -#include -#include diff --git a/Gems/Visibility/Code/Tests/VisibilityTest.cpp b/Gems/Visibility/Code/Tests/VisibilityTest.cpp deleted file mode 100644 index 406cef86a4..0000000000 --- a/Gems/Visibility/Code/Tests/VisibilityTest.cpp +++ /dev/null @@ -1,184 +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 "Visibility_precompiled.h" - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include - -class VisibilityTest - : public ::testing::Test -{ -protected: - - void SetUp() override - { - AZ::ComponentApplication::Descriptor appDesc; - appDesc.m_memoryBlocksByteSize = 10 * 1024 * 1024; - appDesc.m_recordingMode = AZ::Debug::AllocationRecords::RECORD_FULL; - - AZ::ComponentApplication::StartupParameters appStartup; - appStartup.m_createStaticModulesCallback = - [](AZStd::vector& modules) - { - modules.emplace_back(new VisibilityGem); - }; - - m_systemEntity = m_application.Create(appDesc, appStartup); - m_systemEntity->Init(); - m_systemEntity->Activate(); - - m_application.RegisterComponentDescriptor(AzFramework::TransformComponent::CreateDescriptor()); - m_application.RegisterComponentDescriptor(Visibility::OccluderAreaComponent::CreateDescriptor()); - m_application.RegisterComponentDescriptor(Visibility::PortalComponent::CreateDescriptor()); - m_application.RegisterComponentDescriptor(Visibility::VisAreaComponent::CreateDescriptor()); - } - - void TearDown() override - { - m_application.Destroy(); - } - - AZ::ComponentApplication m_application; - AZ::Entity* m_systemEntity; -}; - -#include -#include -#include - -TEST_F(VisibilityTest, Occluder_TestIntersect) -{ - AZ::Entity* testEntity = aznew AZ::Entity(); - ASSERT_TRUE(testEntity != nullptr); - - testEntity->CreateComponent(); - testEntity->CreateComponent(); - - Visibility::EditorOccluderAreaComponent* oaComp = testEntity->FindComponent(); - ASSERT_TRUE(oaComp != nullptr); - testEntity->Init(); - testEntity->Activate(); - - // Test CCW tri intersection test - const AZ::Vector3 src(0, 0, 10); - const AZ::Vector3 dir(0, 0, -1); - float distance; - - // Visibility Components do not make use of the ViewportInfo to determine - // camera position etc. - AzFramework::ViewportInfo viewportInfo{}; - - bool didHit = oaComp->EditorSelectionIntersectRayViewport(viewportInfo, src, dir, distance); - ASSERT_TRUE(didHit); - ASSERT_NEAR(distance, 10, 0.1f); // Occluder is a flat plane - - // Test CW tri intersection test - const AZ::Vector3 srcNeg(0, 0, -10); - const AZ::Vector3 dirNeg(0, 0, 1); - - didHit = oaComp->EditorSelectionIntersectRayViewport(viewportInfo, srcNeg, dirNeg, distance); - ASSERT_TRUE(didHit); - ASSERT_NEAR(distance, 10, 0.1f); // Occluder is a flat plane - - // Test intersect failure - const AZ::Vector3 badDir(100, 100, -1); - didHit = oaComp->EditorSelectionIntersectRayViewport(viewportInfo, src, badDir, distance); - ASSERT_FALSE(didHit); -} - -TEST_F(VisibilityTest, Portal_TestIntersect) -{ - AZ::Entity* testEntity = aznew AZ::Entity(); - ASSERT_TRUE(testEntity != nullptr); - - testEntity->CreateComponent(); - testEntity->CreateComponent(); - - Visibility::EditorPortalComponent* pComp = testEntity->FindComponent(); - ASSERT_TRUE(pComp != nullptr); - testEntity->Init(); - testEntity->Activate(); - - const AZ::Vector3 src(0, 0, 10); - const AZ::Vector3 dir(0, 0, -1); - float distance; - - // Visibility Components do not make use of the ViewportInfo to determine - // camera position etc. - AzFramework::ViewportInfo viewportInfo{}; - - // Test intersect - bool didHit = pComp->EditorSelectionIntersectRayViewport(viewportInfo, src, dir, distance); - ASSERT_TRUE(didHit); - ASSERT_NEAR(distance, 9, 0.1f); // Portal has a default height of 1 - - // Test casting a ray from inside the geom - const AZ::Vector3 internalSrc(0, 0, 0.5f); - didHit = pComp->EditorSelectionIntersectRayViewport(viewportInfo, internalSrc, dir, distance); - ASSERT_FALSE(didHit); - - // Test intersect failure - const AZ::Vector3 badDir(100, 100, -1); - didHit = pComp->EditorSelectionIntersectRayViewport(viewportInfo, src, badDir, distance); - ASSERT_FALSE(didHit); -} - -TEST_F(VisibilityTest, VisArea_TestIntersect) -{ - AZ::Entity* testEntity = aznew AZ::Entity(); - ASSERT_TRUE(testEntity != nullptr); - - testEntity->CreateComponent(); - testEntity->CreateComponent(); - testEntity->Init(); - testEntity->Activate(); - - Visibility::EditorVisAreaComponent* vaComp = testEntity->FindComponent(); - ASSERT_TRUE(vaComp != nullptr); - - const AZ::Vector3 src(0, 0, 10); - const AZ::Vector3 dir(0, 0, -1); - float distance; - - // Visibility Components do not make use of the ViewportInfo to determine - // camera position etc. - AzFramework::ViewportInfo viewportInfo{}; - - bool didHit = vaComp->EditorSelectionIntersectRayViewport(viewportInfo, src, dir, distance); - ASSERT_TRUE(didHit); - ASSERT_NEAR(distance, 5, 0.1f); // VisArea has a default height of 5 - - const AZ::Vector3 badDir(100, 100, -1); - didHit = vaComp->EditorSelectionIntersectRayViewport(viewportInfo, src, badDir, distance); - ASSERT_FALSE(didHit); -} - -AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Gems/Visibility/Code/visibility_editor_files.cmake b/Gems/Visibility/Code/visibility_editor_files.cmake deleted file mode 100644 index 9d17b92e27..0000000000 --- a/Gems/Visibility/Code/visibility_editor_files.cmake +++ /dev/null @@ -1,22 +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 - Include/EditorOccluderAreaComponentBus.h - Include/EditorPortalComponentBus.h - Include/EditorVisAreaComponentBus.h - Source/EditorOccluderAreaComponentMode.h - Source/EditorOccluderAreaComponentMode.cpp - Source/EditorPortalComponentMode.h - Source/EditorPortalComponentMode.cpp - Source/EditorVisAreaComponentMode.h - Source/EditorVisAreaComponentMode.cpp -) diff --git a/Gems/Visibility/Code/visibility_editor_shared_files.cmake b/Gems/Visibility/Code/visibility_editor_shared_files.cmake deleted file mode 100644 index 1714fc1402..0000000000 --- a/Gems/Visibility/Code/visibility_editor_shared_files.cmake +++ /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. -# - -set(FILES - Source/VisibilityGem.h - Source/VisibilityGem.cpp - Source/EditorOccluderAreaComponent.h - Source/EditorOccluderAreaComponent.cpp - Source/EditorPortalComponent.h - Source/EditorPortalComponent.cpp - Source/EditorVisAreaComponent.h - Source/EditorVisAreaComponent.cpp -) diff --git a/Gems/Visibility/Code/visibility_editor_tests_files.cmake b/Gems/Visibility/Code/visibility_editor_tests_files.cmake deleted file mode 100644 index 52867e64af..0000000000 --- a/Gems/Visibility/Code/visibility_editor_tests_files.cmake +++ /dev/null @@ -1,22 +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 - Tests/VisibilityTest.cpp - Source/VisibilityGem.h - Source/VisibilityGem.cpp - Source/EditorOccluderAreaComponent.h - Source/EditorOccluderAreaComponent.cpp - Source/EditorPortalComponent.h - Source/EditorPortalComponent.cpp - Source/EditorVisAreaComponent.h - Source/EditorVisAreaComponent.cpp -) diff --git a/Gems/Visibility/Code/visibility_files.cmake b/Gems/Visibility/Code/visibility_files.cmake deleted file mode 100644 index e58ac4fbba..0000000000 --- a/Gems/Visibility/Code/visibility_files.cmake +++ /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. -# - -set(FILES - Source/Visibility_precompiled.cpp - Source/Visibility_precompiled.h - Include/OccluderAreaComponentBus.h - Include/PortalComponentBus.h - Include/VisAreaComponentBus.h - Source/OccluderAreaComponent.h - Source/OccluderAreaComponent.cpp - Source/PortalComponent.h - Source/PortalComponent.cpp - Source/VisAreaComponent.h - Source/VisAreaComponent.cpp -) diff --git a/Gems/Visibility/Code/visibility_shared_files.cmake b/Gems/Visibility/Code/visibility_shared_files.cmake deleted file mode 100644 index a37350ade6..0000000000 --- a/Gems/Visibility/Code/visibility_shared_files.cmake +++ /dev/null @@ -1,15 +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/VisibilityGem.h - Source/VisibilityGem.cpp -) diff --git a/Gems/Visibility/gem.json b/Gems/Visibility/gem.json deleted file mode 100644 index 3e8eca471b..0000000000 --- a/Gems/Visibility/gem.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "gem_name": "Visibility", - "GemFormatVersion": 3, - "Uuid": "3b4ab3f54c2749328934c5b864355a61", - "Name": "Visibility", - "DisplayName": "Visibility", - "Version": "0.1.0", - "LinkType": "Dynamic", - "Summary": "Provides components for defining visible regions of a scene", - "Tags": ["Untagged"], - "IconPath": "preview.png", - "EditorModule": true -} diff --git a/Gems/Visibility/preview.png b/Gems/Visibility/preview.png deleted file mode 100644 index f60ab5eebd..0000000000 --- a/Gems/Visibility/preview.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8f1a3e838ba075704ee974a1289487d4007e7b7385eb855b8b2a09534b6cecd1 -size 1949 From 0f9f4be382a1f6c6c48c7e8fbdaf83606dba8d54 Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Fri, 30 Apr 2021 13:18:06 -0500 Subject: [PATCH 042/185] [LYN-3357] Cherry-pick fix to UI textures to make them process as the correct type. --- .../Config/UserInterface_Compressed.preset | 5 +- .../Config/UserInterface_Lossless.preset | 13 ++- .../Textures/Basic/Button_Sliced_Normal.tif | 3 - .../Basic/button_sliced_normal.sprite | 3 - .../LyShineExamples/CircleFrame.tif.assetinfo | 69 ++++++++++++ .../CircleGradient.png.assetinfo | 69 ++++++++++++ .../Circle_Shadow.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/ColorTest.tif.assetinfo | 69 ++++++++++++ .../ColorTestPow2.tif.assetinfo | 69 ++++++++++++ .../ParticleGlow.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/button.tif.assetinfo | 69 ++++++++++++ .../buttonPressed.tif.assetinfo | 69 ++++++++++++ .../buttonSlider.tif.assetinfo | 69 ++++++++++++ .../checkbox_spritesheet.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/checkered3.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/empty_icon.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/fixed_image.tif.assetinfo | 69 ++++++++++++ .../flipbook_walking.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/mask.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/outline.tif.assetinfo | 69 ++++++++++++ .../outlineRounded.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/panelBkgd.tif.assetinfo | 69 ++++++++++++ .../pattern02_big.tif.assetinfo | 69 ++++++++++++ .../pattern02vertical.tif.assetinfo | 69 ++++++++++++ .../pattern02vertical_big.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/pattern03.tif.assetinfo | 69 ++++++++++++ .../pattern03_big.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_1.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_10.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_2.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_3.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_4.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_5.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_6.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_7.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_8.tif.assetinfo | 69 ++++++++++++ .../scroll_box_icon_9.tif.assetinfo | 69 ++++++++++++ .../scroll_box_map.tif.assetinfo | 69 ++++++++++++ .../LyShineExamples/selected.tif.assetinfo | 69 ++++++++++++ .../shadowInside2.tif.assetinfo | 69 ++++++++++++ .../shadowInsideSquare.tif.assetinfo | 69 ++++++++++++ .../Basic/Button_Sliced_Normal.tif.assetinfo | 69 ++++++++++++ .../Button_Sliced_Normal.tif.exportsettings | 1 - .../Basic/Button_Sliced_Pressed.tif.assetinfo | 69 ++++++++++++ .../Button_Sliced_Pressed.tif.exportsettings | 1 - .../Button_Sliced_Selected.tif.assetinfo | 69 ++++++++++++ .../Button_Sliced_Selected.tif.exportsettings | 1 - .../Button_Stretched_Normal.tif.assetinfo | 69 ++++++++++++ ...Button_Stretched_Normal.tif.exportsettings | 1 - .../Button_Stretched_Pressed.tif.assetinfo | 69 ++++++++++++ ...utton_Stretched_Pressed.tif.exportsettings | 1 - .../Button_Stretched_Selected.tif.assetinfo | 69 ++++++++++++ ...tton_Stretched_Selected.tif.exportsettings | 1 - .../Basic/CheckBox_Check.tif.assetinfo | 69 ++++++++++++ .../CheckBox_Check_Background.tif.assetinfo | 69 ++++++++++++ .../Basic/CheckBox_Cross.tif.assetinfo | 69 ++++++++++++ .../Textures/Basic/CheckBox_Off.tif.assetinfo | 69 ++++++++++++ .../Textures/Basic/CheckBox_On.tif.assetinfo | 69 ++++++++++++ ...Checkbox_Background_Disabled.tif.assetinfo | 69 ++++++++++++ .../Checkbox_Background_Hover.tif.assetinfo | 69 ++++++++++++ .../Checkbox_Background_Normal.tif.assetinfo | 69 ++++++++++++ .../Textures/Basic/Checkered.tif.assetinfo | 69 ++++++++++++ .../Basic/Checkered.tif.exportsettings | 1 - .../Slider_Background_Disabled.tif.assetinfo | 69 ++++++++++++ .../Slider_Background_Hover.tif.assetinfo | 69 ++++++++++++ .../Slider_Background_Normal.tif.assetinfo | 69 ++++++++++++ .../Basic/Slider_Fill_Sliced.tif.assetinfo | 69 ++++++++++++ .../Basic/Slider_Fill_Stretch.tif.assetinfo | 69 ++++++++++++ .../Basic/Slider_Manipulator.tif.assetinfo | 69 ++++++++++++ .../Basic/Slider_Track_Sliced.tif.assetinfo | 69 ++++++++++++ .../Basic/Slider_Track_Stretch.tif.assetinfo | 69 ++++++++++++ .../Text_Input_Sliced_Normal.tif.assetinfo | 69 ++++++++++++ ...ext_Input_Sliced_Normal.tif.exportsettings | 1 - .../Text_Input_Sliced_Pressed.tif.assetinfo | 69 ++++++++++++ ...xt_Input_Sliced_Pressed.tif.exportsettings | 1 - .../Text_Input_Sliced_Selected.tif.assetinfo | 69 ++++++++++++ ...t_Input_Sliced_Selected.tif.exportsettings | 1 - .../Prefab/Dropdown_Arrow.tif.assetinfo | 69 ++++++++++++ .../Prefab/Dropdown_ArrowL.tif.assetinfo | 69 ++++++++++++ .../Prefab/Dropdown_ArrowR.tif.assetinfo | 69 ++++++++++++ .../Prefab/Dropdown_ArrowU.tif.assetinfo | 69 ++++++++++++ .../Prefab/Dropdown_Button.tif.assetinfo | 69 ++++++++++++ .../Prefab/Dropdown_Menu.tif.assetinfo | 69 ++++++++++++ ...ioButton_Background_Disabled.tif.assetinfo | 69 ++++++++++++ ...RadioButton_Background_Hover.tif.assetinfo | 69 ++++++++++++ ...adioButton_Background_Normal.tif.assetinfo | 69 ++++++++++++ .../Prefab/RadioButton_Dot.tif.assetinfo | 69 ++++++++++++ .../Prefab/button_disabled.tif.assetinfo | 69 ++++++++++++ .../Prefab/button_normal.tif.assetinfo | 69 ++++++++++++ .../checkbox_box_disabled.tif.assetinfo | 69 ++++++++++++ .../Prefab/checkbox_box_hover.tif.assetinfo | 69 ++++++++++++ .../Prefab/checkbox_box_normal.tif.assetinfo | 101 ++++++++++++++++++ .../Prefab/checkbox_check.tif.assetinfo | 69 ++++++++++++ .../Prefab/scrollbar_handle.tif.assetinfo | 69 ++++++++++++ .../scrollbar_horiz_track.tif.assetinfo | 69 ++++++++++++ .../Prefab/scrollbar_vert_track.tif.assetinfo | 69 ++++++++++++ .../Prefab/slider_fill_disabled.tif.assetinfo | 69 ++++++++++++ .../Prefab/slider_fill_normal.tif.assetinfo | 69 ++++++++++++ .../slider_handle_disabled.tif.assetinfo | 69 ++++++++++++ .../Prefab/slider_handle_normal.tif.assetinfo | 69 ++++++++++++ .../slider_track_disabled.tif.assetinfo | 69 ++++++++++++ .../Prefab/slider_track_normal.tif.assetinfo | 69 ++++++++++++ .../Prefab/textinput_disabled.tif.assetinfo | 69 ++++++++++++ .../Prefab/textinput_hover.tif.assetinfo | 69 ++++++++++++ .../Prefab/textinput_normal.tif.assetinfo | 69 ++++++++++++ .../Prefab/tooltip_sliced.tif.assetinfo | 69 ++++++++++++ 106 files changed, 6392 insertions(+), 22 deletions(-) delete mode 100644 Gems/LyShine/Assets/Textures/Basic/Button_Sliced_Normal.tif delete mode 100644 Gems/LyShine/Assets/Textures/Basic/button_sliced_normal.sprite create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleFrame.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleGradient.png.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/Circle_Shadow.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTest.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTestPow2.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ParticleGlow.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/button.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonPressed.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonSlider.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkbox_spritesheet.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkered3.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/empty_icon.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/fixed_image.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/flipbook_walking.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/mask.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outline.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outlineRounded.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/panelBkgd.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02_big.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical_big.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03_big.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_1.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_10.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_2.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_3.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_4.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_5.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_6.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_7.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_8.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_9.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_map.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/selected.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInside2.tif.assetinfo create mode 100644 Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInsideSquare.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check_Background.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/CheckBox_Cross.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/CheckBox_Off.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/CheckBox_On.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Hover.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Hover.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Sliced.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Stretch.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Slider_Manipulator.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Sliced.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Stretch.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.assetinfo delete mode 100644 Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.exportsettings create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Arrow.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowL.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowR.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowU.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Button.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Menu.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Hover.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Dot.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/button_disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/button_normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_hover.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_check.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_handle.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_horiz_track.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_vert_track.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_disabled.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_hover.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif.assetinfo create mode 100644 Gems/UiBasics/Assets/UI/Textures/Prefab/tooltip_sliced.tif.assetinfo diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset index dcbaea96aa..01595a3425 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Compressed.preset @@ -7,7 +7,10 @@ "UUID": "{2828FBFE-BDF9-45A7-9370-F93822719CCF}", "Name": "UserInterface_Compressed", "SuppressEngineReduce": true, - "PixelFormat": "R8G8B8X8" + "PixelFormat": "R8G8B8A8", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ "_ui" ] }, "PlatformsPresets": { "es3": { diff --git a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset b/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset index 5ccaa3ac16..78c63790ab 100644 --- a/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset +++ b/Gems/Atom/Asset/ImageProcessingAtom/Config/UserInterface_Lossless.preset @@ -7,32 +7,35 @@ "UUID": "{83003128-F63E-422B-AEC2-68F0A947225F}", "Name": "UserInterface_Lossless", "SuppressEngineReduce": true, - "PixelFormat": "R8G8B8X8" + "PixelFormat": "R8G8B8A8", + "SourceColor": "Linear", + "DestColor": "Linear", + "FileMasks": [ "_ui" ] }, "PlatformsPresets": { "es3": { "UUID": "{83003128-F63E-422B-AEC2-68F0A947225F}", "Name": "UserInterface_Lossless", "SuppressEngineReduce": true, - "PixelFormat": "R8G8B8X8" + "PixelFormat": "R8G8B8A8" }, "ios": { "UUID": "{83003128-F63E-422B-AEC2-68F0A947225F}", "Name": "UserInterface_Lossless", "SuppressEngineReduce": true, - "PixelFormat": "R8G8B8X8" + "PixelFormat": "R8G8B8A8" }, "osx_gl": { "UUID": "{83003128-F63E-422B-AEC2-68F0A947225F}", "Name": "UserInterface_Lossless", "SuppressEngineReduce": true, - "PixelFormat": "R8G8B8X8" + "PixelFormat": "R8G8B8A8" }, "provo": { "UUID": "{83003128-F63E-422B-AEC2-68F0A947225F}", "Name": "UserInterface_Lossless", "SuppressEngineReduce": true, - "PixelFormat": "R8G8B8X8" + "PixelFormat": "R8G8B8A8" } } } diff --git a/Gems/LyShine/Assets/Textures/Basic/Button_Sliced_Normal.tif b/Gems/LyShine/Assets/Textures/Basic/Button_Sliced_Normal.tif deleted file mode 100644 index c51e06aa9a..0000000000 --- a/Gems/LyShine/Assets/Textures/Basic/Button_Sliced_Normal.tif +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1e6a98954dd2b2da87309cf522959efc601444080cf99b850ad64f2b7c5e8668 -size 38228 diff --git a/Gems/LyShine/Assets/Textures/Basic/button_sliced_normal.sprite b/Gems/LyShine/Assets/Textures/Basic/button_sliced_normal.sprite deleted file mode 100644 index 3f6cfe0345..0000000000 --- a/Gems/LyShine/Assets/Textures/Basic/button_sliced_normal.sprite +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f91c1587e5d611d253528c82c93b83e460f7ea71412d2489ff368eca4d8798db -size 122 diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleFrame.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleFrame.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleFrame.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleGradient.png.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleGradient.png.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/CircleGradient.png.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/Circle_Shadow.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/Circle_Shadow.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/Circle_Shadow.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTest.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTest.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTest.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTestPow2.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTestPow2.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ColorTestPow2.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ParticleGlow.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ParticleGlow.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/ParticleGlow.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/button.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/button.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/button.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonPressed.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonPressed.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonPressed.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonSlider.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonSlider.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/buttonSlider.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkbox_spritesheet.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkbox_spritesheet.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkbox_spritesheet.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkered3.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkered3.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/checkered3.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/empty_icon.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/empty_icon.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/empty_icon.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/fixed_image.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/fixed_image.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/fixed_image.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/flipbook_walking.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/flipbook_walking.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/flipbook_walking.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/mask.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/mask.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/mask.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outline.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outline.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outline.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outlineRounded.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outlineRounded.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/outlineRounded.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/panelBkgd.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/panelBkgd.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/panelBkgd.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02_big.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02_big.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02_big.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical_big.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical_big.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern02vertical_big.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03_big.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03_big.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/pattern03_big.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_1.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_1.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_1.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_10.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_10.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_10.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_2.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_2.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_2.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_3.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_3.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_3.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_4.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_4.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_4.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_5.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_5.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_5.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_6.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_6.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_6.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_7.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_7.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_7.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_8.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_8.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_8.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_9.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_9.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_icon_9.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_map.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_map.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/scroll_box_map.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/selected.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/selected.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/selected.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInside2.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInside2.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInside2.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInsideSquare.tif.assetinfo b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInsideSquare.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/LyShineExamples/Assets/UI/Textures/LyShineExamples/shadowInsideSquare.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Normal.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Pressed.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Sliced_Selected.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Normal.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Pressed.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Button_Stretched_Selected.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check_Background.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check_Background.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Check_Background.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Cross.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Cross.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Cross.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Off.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Off.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_Off.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/CheckBox_On.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_On.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/CheckBox_On.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Disabled.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Disabled.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Hover.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Hover.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Hover.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Checkbox_Background_Normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Checkered.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Disabled.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Disabled.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Hover.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Hover.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Hover.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Background_Normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Sliced.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Sliced.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Sliced.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Stretch.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Stretch.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Fill_Stretch.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Manipulator.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Manipulator.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Manipulator.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Sliced.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Sliced.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Sliced.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Stretch.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Stretch.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Slider_Track_Stretch.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Normal.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Pressed.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.assetinfo b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.exportsettings b/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.exportsettings deleted file mode 100644 index 1415bea891..0000000000 --- a/Gems/UiBasics/Assets/Textures/Basic/Text_Input_Sliced_Selected.tif.exportsettings +++ /dev/null @@ -1 +0,0 @@ -/autooptimizefile=0 /dns=1 /preset=ReferenceImage_Linear /reduce=0 /ser=0 diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Arrow.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Arrow.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Arrow.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowL.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowL.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowL.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowR.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowR.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowR.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowU.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowU.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_ArrowU.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Button.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Button.tif.assetinfo new file mode 100644 index 0000000000..95b548a2eb --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Button.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Menu.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Menu.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/Dropdown_Menu.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Disabled.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Hover.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Hover.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Hover.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Background_Normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Dot.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Dot.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/RadioButton_Dot.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/button_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/button_disabled.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/button_disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/button_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/button_normal.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/button_normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_disabled.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_hover.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_hover.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_hover.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_normal.tif.assetinfo new file mode 100644 index 0000000000..2eb5be8e93 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_box_normal.tif.assetinfo @@ -0,0 +1,101 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_check.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_check.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/checkbox_check.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_handle.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_handle.tif.assetinfo new file mode 100644 index 0000000000..95b548a2eb --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_handle.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_horiz_track.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_horiz_track.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_horiz_track.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_vert_track.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_vert_track.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/scrollbar_vert_track.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_disabled.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_fill_normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_disabled.tif.assetinfo new file mode 100644 index 0000000000..95b548a2eb --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_handle_normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_disabled.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_normal.tif.assetinfo new file mode 100644 index 0000000000..61b2832ff3 --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/slider_track_normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_disabled.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_disabled.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_disabled.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_hover.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_hover.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_hover.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif.assetinfo new file mode 100644 index 0000000000..c6f6ca1e9c --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/textinput_normal.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Gems/UiBasics/Assets/UI/Textures/Prefab/tooltip_sliced.tif.assetinfo b/Gems/UiBasics/Assets/UI/Textures/Prefab/tooltip_sliced.tif.assetinfo new file mode 100644 index 0000000000..dd1d22706e --- /dev/null +++ b/Gems/UiBasics/Assets/UI/Textures/Prefab/tooltip_sliced.tif.assetinfo @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 83e06912432d2207a91cec158b3b8903f819fe52 Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Mon, 3 May 2021 14:58:15 -0500 Subject: [PATCH 043/185] Added some comments to clarify the role of the default instance --- .../Source/AtomDebugDisplayViewportInterface.cpp | 12 +++++------- .../Code/Source/AtomDebugDisplayViewportInterface.h | 8 +++++--- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp index 871d75f194..8a063cd7a7 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp @@ -282,12 +282,14 @@ namespace AZ::AtomBridge m_auxGeomPtr = nullptr; return; } + // default instance draws to all viewports in the default scene if (m_defaultInstance || !view) { m_auxGeomPtr = auxGeomFP->GetDrawQueue(); } else { + // cache the aux geom draw interface for the current view (aka camera) m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(view); } } @@ -297,7 +299,7 @@ namespace AZ::AtomBridge AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); UpdateAuxGeom(scene, viewportContextPtr ? viewportContextPtr->GetDefaultView().get() : nullptr); AzFramework::DebugDisplayRequestBus::Handler::BusConnect(m_viewportId); - if (!m_defaultInstance) + if (!m_defaultInstance) // only the per viewport instances need to listen for viewport changes { AZ::RPI::ViewportContextIdNotificationBus::Handler::BusConnect(viewportContextPtr->GetId()); } @@ -307,13 +309,9 @@ namespace AZ::AtomBridge void AtomDebugDisplayViewportInterface::OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view) { ResetRenderState(); - if (m_defaultInstance) - { - RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); - UpdateAuxGeom(scene, nullptr); - } - else + if (!m_defaultInstance) { + // handle viewport update (view change, scene change, etc auto viewportContextManager = AZ::Interface::Get(); AZ::RPI::ViewportContextPtr viewportContextPtr = viewportContextManager->GetViewportContextById(m_viewportId); UpdateAuxGeom(viewportContextPtr->GetRenderScene().get(), viewportContextPtr->GetDefaultView().get()); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h index 4520b60041..c872e2b81e 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.h @@ -263,10 +263,12 @@ namespace AZ::AtomBridge RenderState m_rendState; AZ::RPI::AuxGeomDrawPtr m_auxGeomPtr; - bool m_defaultInstance = false; // only true for drawing to a particular viewport. What would 2D drawing mean in a scene with several windows? + + // m_defaultInstance is true for the instance that multicasts the debug draws to all viewports + // (with an AuxGeom render pass) in the default scene. + bool m_defaultInstance = false; AzFramework::ViewportId m_viewportId = AzFramework::InvalidViewportId; // Address this instance answers on. - AZ::RPI::ViewportContext::SceneChangedEvent::Handler - m_sceneChangeHandler; + AZ::RPI::ViewportContext::SceneChangedEvent::Handler m_sceneChangeHandler; }; // this is duplicated from Cry_Math.h, GetBasisVectors. From 1a712857d9534dfad45c16044747802ff88311ac Mon Sep 17 00:00:00 2001 From: rgba16f <82187279+rgba16f@users.noreply.github.com> Date: Mon, 3 May 2021 15:22:04 -0500 Subject: [PATCH 044/185] Delete a mistakenly commited .orig file --- ...AtomDebugDisplayViewportInterface.cpp.orig | 1544 ----------------- 1 file changed, 1544 deletions(-) delete mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig deleted file mode 100644 index a4093ec937..0000000000 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomDebugDisplayViewportInterface.cpp.orig +++ /dev/null @@ -1,1544 +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 - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace // unnamed namespace to hold copies of Cry AuxGeom state enum's, this is to avoid creating a dependency on IRenderAuxGeom.h -{ - // Notes: - // Don't change the xxxShift values, they need to match the values from legacy cry rendering - // This also applies to the individual flags in EAuxGeomPublicRenderflags_*! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - enum EAuxGeomPublicRenderflagBitMasks - { - e_Mode2D3DShift = 31, - e_Mode2D3DMask = 0x1 << e_Mode2D3DShift, - - e_AlphaBlendingShift = 29, - e_AlphaBlendingMask = 0x3 << e_AlphaBlendingShift, - - e_DrawInFrontShift = 28, - e_DrawInFrontMask = 0x1 << e_DrawInFrontShift, - - e_FillModeShift = 26, - e_FillModeMask = 0x3 << e_FillModeShift, - - e_CullModeShift = 24, - e_CullModeMask = 0x3 << e_CullModeShift, - - e_DepthWriteShift = 23, - e_DepthWriteMask = 0x1 << e_DepthWriteShift, - - e_DepthTestShift = 22, - e_DepthTestMask = 0x1 << e_DepthTestShift, - - e_PublicParamsMask = e_Mode2D3DMask | e_AlphaBlendingMask | e_DrawInFrontMask | e_FillModeMask | - e_CullModeMask | e_DepthWriteMask | e_DepthTestMask - }; - - // Notes: - // e_Mode2D renders in normalized [0.. 1] screen space. - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_Mode2D3D - { - e_Mode3D = 0x0 << e_Mode2D3DShift, - e_Mode2D = 0x1 << e_Mode2D3DShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_AlphaBlendMode - { - e_AlphaNone = 0x0 << e_AlphaBlendingShift, - e_AlphaAdditive = 0x1 << e_AlphaBlendingShift, - e_AlphaBlended = 0x2 << e_AlphaBlendingShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_DrawInFrontMode - { - e_DrawInFrontOff = 0x0 << e_DrawInFrontShift, - e_DrawInFrontOn = 0x1 << e_DrawInFrontShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_FillMode - { - e_FillModeSolid = 0x0 << e_FillModeShift, - e_FillModeWireframe = 0x1 << e_FillModeShift, - e_FillModePoint = 0x2 << e_FillModeShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_CullMode - { - e_CullModeNone = 0x0 << e_CullModeShift, - e_CullModeFront = 0x1 << e_CullModeShift, - e_CullModeBack = 0x2 << e_CullModeShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_DepthWrite - { - e_DepthWriteOn = 0x0 << e_DepthWriteShift, - e_DepthWriteOff = 0x1 << e_DepthWriteShift, - }; - - // Notes: - // Don't change the xxxShift values blindly as they affect the rendering output - // that is two primitives have to be rendered after 3d primitives, alpha blended - // geometry have to be rendered after opaque ones, etc. - // This also applies to the individual flags in EAuxGeomPublicRenderflagBitMasks! - // Remarks: - // Bits 0 - 22 are currently reserved for prim type and per draw call render parameters (point size, etc.) - // Check RenderAuxGeom.h in ../RenderDll/Common - // See also: - // EAuxGeomPublicRenderflagBitMasks - enum EAuxGeomPublicRenderflags_DepthTest - { - e_DepthTestOn = 0x0 << e_DepthTestShift, - e_DepthTestOff = 0x1 << e_DepthTestShift, - }; -}; - -namespace AZ::AtomBridge -{ - - //////////////////////////////////////////////////////////////////////// - SingleColorDynamicSizeLineHelper::SingleColorDynamicSizeLineHelper( - int estimatedNumLineSegments - ) - { - m_points.reserve(estimatedNumLineSegments * 2); - } - - void SingleColorDynamicSizeLineHelper::AddLineSegment( - const AZ::Vector3& lineStart, - const AZ::Vector3& lineEnd - ) - { - m_points.push_back(lineStart); - m_points.push_back(lineEnd); - } - - void SingleColorDynamicSizeLineHelper::Draw( - AZ::RPI::AuxGeomDrawPtr auxGeomDrawPtr, - const RenderState& rendState - ) const - { - if (auxGeomDrawPtr && !m_points.empty()) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = m_points.data(); - drawArgs.m_vertCount = aznumeric_cast(m_points.size()); - drawArgs.m_colors = &rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = rendState.m_lineWidth; - drawArgs.m_opacityType = rendState.m_opacityType; - drawArgs.m_depthTest = rendState.m_depthTest; - drawArgs.m_depthWrite = rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = rendState.m_viewProjOverrideIndex; - auxGeomDrawPtr->DrawLines( drawArgs ); - } - } - - void SingleColorDynamicSizeLineHelper::Draw2d( - AZ::RPI::AuxGeomDrawPtr auxGeomDrawPtr, - const RenderState& rendState - ) const - { - if (auxGeomDrawPtr && !m_points.empty()) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = m_points.data(); - drawArgs.m_vertCount = aznumeric_cast(m_points.size()); - drawArgs.m_colors = &rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = rendState.m_lineWidth; - drawArgs.m_opacityType = rendState.m_opacityType; - drawArgs.m_depthTest = rendState.m_depthTest; - drawArgs.m_depthWrite = rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = auxGeomDrawPtr->GetOrAdd2DViewProjOverride(); - auxGeomDrawPtr->DrawLines( drawArgs ); - } - } - - void SingleColorDynamicSizeLineHelper::Reset() - { - m_points.clear(); - } - //////////////////////////////////////////////////////////////////////// - - // Partial implementation of the DebugDisplayRequestBus on Atom. - // Commented out function prototypes are waiting to be implemented. - // work tracked in [ATOM-3459] - AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(AZ::RPI::ViewportContextPtr viewportContextPtr) - { - ResetRenderState(); - m_viewportId = viewportContextPtr->GetId(); - m_defaultInstance = false; - auto setupScene = [this](RPI::ScenePtr scene) - { - auto viewportContextManager = AZ::Interface::Get(); - AZ::RPI::ViewportContextPtr viewportContextPtr = viewportContextManager->GetViewportContextById(m_viewportId); - InitInternal(scene.get(), viewportContextPtr); - }; - setupScene(viewportContextPtr->GetRenderScene()); - m_sceneChangeHandler = AZ::RPI::ViewportContext::SceneChangedEvent::Handler(setupScene); - viewportContextPtr->ConnectSceneChangedHandler(m_sceneChangeHandler); - } - - AtomDebugDisplayViewportInterface::AtomDebugDisplayViewportInterface(uint32_t defaultInstanceAddress) - { - ResetRenderState(); - m_viewportId = defaultInstanceAddress; - m_defaultInstance = true; - RPI::Scene* scene = RPI::RPISystemInterface::Get()->GetDefaultScene().get(); - InitInternal(scene, nullptr); - } - - void AtomDebugDisplayViewportInterface::InitInternal(RPI::Scene* scene, AZ::RPI::ViewportContextPtr viewportContextPtr) - { - AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); - if (!scene) - { - m_auxGeomPtr = nullptr; - return; - } - auto auxGeomFP = scene->GetFeatureProcessor(); - if (!auxGeomFP) - { - m_auxGeomPtr = nullptr; - return; - } - if (m_defaultInstance) - { - m_auxGeomPtr = auxGeomFP->GetDrawQueue(); - } - else - { - m_auxGeomPtr = auxGeomFP->GetOrCreateDrawQueueForView(viewportContextPtr->GetDefaultView().get()); - } - AzFramework::DebugDisplayRequestBus::Handler::BusConnect(m_viewportId); - } - - AtomDebugDisplayViewportInterface::~AtomDebugDisplayViewportInterface() - { - AzFramework::DebugDisplayRequestBus::Handler::BusDisconnect(m_viewportId); - m_viewportId = AzFramework::InvalidViewportId; - m_auxGeomPtr = nullptr; - } - - void AtomDebugDisplayViewportInterface::ResetRenderState() - { - m_rendState = RenderState(); - for (int index = 0; index < RenderState::TransformStackSize; ++index) - { - m_rendState.m_transformStack[index] = AZ::Matrix3x4::Identity(); - } - } - - void AtomDebugDisplayViewportInterface::SetColor(float r, float g, float b, float a) - { - m_rendState.m_color = AZ::Color(r, g, b, a); - } - - void AtomDebugDisplayViewportInterface::SetColor(const AZ::Color& color) - { - m_rendState.m_color = color; - } - - void AtomDebugDisplayViewportInterface::SetColor(const AZ::Vector4& color) - { - m_rendState.m_color = AZ::Color(color); - } - - void AtomDebugDisplayViewportInterface::SetAlpha(float a) - { - m_rendState.m_color.SetA(a); - if (a < 1.0f) - { - m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Opaque; - } - else - { - m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Translucent; - } - } - - void AtomDebugDisplayViewportInterface::DrawQuad( - const AZ::Vector3& p1, - const AZ::Vector3& p2, - const AZ::Vector3& p3, - const AZ::Vector3& p4) - { - if (m_auxGeomPtr) - { - AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; - AZ::Vector3 triangles[6]; - triangles[0] = wsPoints[0]; - triangles[1] = wsPoints[1]; - triangles[2] = wsPoints[2]; - triangles[3] = wsPoints[2]; - triangles[4] = wsPoints[3]; - triangles[5] = wsPoints[0]; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = triangles; - drawArgs.m_vertCount = 6; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawQuad(float width, float height) - { - if (!m_auxGeomPtr || width <= 0.0f || height <= 0.0f) - { - return; - } - - m_auxGeomPtr->DrawQuad( - width, - height, - GetCurrentTransform(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex); - } - - void AtomDebugDisplayViewportInterface::DrawWireQuad( - const AZ::Vector3& p1, - const AZ::Vector3& p2, - const AZ::Vector3& p3, - const AZ::Vector3& p4) - { - if (m_auxGeomPtr) - { - AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = wsPoints; - drawArgs.m_vertCount = 4; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawPolylines(drawArgs, AZ::RPI::AuxGeomDraw::PolylineEnd::Closed); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireQuad(float width, float height) - { - if (!m_auxGeomPtr || width <= 0.0f || height <= 0.0f) - { - return; - } - - m_auxGeomPtr->DrawQuad( - width, - height, - GetCurrentTransform(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Line, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex); - } - - void AtomDebugDisplayViewportInterface::DrawQuadGradient( - const AZ::Vector3& p1, - const AZ::Vector3& p2, - const AZ::Vector3& p3, - const AZ::Vector3& p4, - const AZ::Vector4& firstColor, - const AZ::Vector4& secondColor) - { - if (m_auxGeomPtr) - { - AZ::Vector3 wsPoints[4] = { ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3), ToWorldSpacePosition(p4) }; - AZ::Vector3 triangles[6]; - AZ::Color colors[6]; - triangles[0] = wsPoints[0]; colors[0] = firstColor; - triangles[1] = wsPoints[1]; colors[1] = firstColor; - triangles[2] = wsPoints[2]; colors[2] = secondColor; - triangles[3] = wsPoints[2]; colors[3] = secondColor; - triangles[4] = wsPoints[3]; colors[4] = secondColor; - triangles[5] = wsPoints[0]; colors[5] = firstColor; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = triangles; - drawArgs.m_vertCount = 6; - drawArgs.m_colors = colors; - drawArgs.m_colorCount = 6; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawTri(const AZ::Vector3& p1, const AZ::Vector3& p2, const AZ::Vector3& p3) - { - if (m_auxGeomPtr) - { - AZ::Vector3 verts[3] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2), ToWorldSpacePosition(p3)}; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = verts; - drawArgs.m_vertCount = 3; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawTriangles(const AZStd::vector& vertices, const AZ::Color& color) - { - if (m_auxGeomPtr) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = vertices.data(); - drawArgs.m_vertCount = aznumeric_cast(vertices.size()); - drawArgs.m_colors = &color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawTrianglesIndexed( - const AZStd::vector& vertices, - const AZStd::vector& indices, - const AZ::Color& color) - { - if (m_auxGeomPtr) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicIndexedDrawArguments drawArgs; - drawArgs.m_verts = vertices.data(); - drawArgs.m_vertCount = aznumeric_cast(vertices.size()); - drawArgs.m_indices = indices.data(); - drawArgs.m_indexCount = aznumeric_cast(indices.size()); - drawArgs.m_colors = &color; - drawArgs.m_colorCount = 1; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawTriangles(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireBox(const AZ::Vector3& min, const AZ::Vector3& max) - { - if (m_auxGeomPtr) - { - m_auxGeomPtr->DrawAabb( - AZ::Aabb::CreateFromMinMax(min, max), - GetCurrentTransform(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Line, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawSolidBox(const AZ::Vector3& min, const AZ::Vector3& max) - { - if (m_auxGeomPtr) - { - m_auxGeomPtr->DrawAabb( - AZ::Aabb::CreateFromMinMax(min, max), - GetCurrentTransform(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Solid, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex); - } - } - - void AtomDebugDisplayViewportInterface::DrawSolidOBB( - const AZ::Vector3& center, - const AZ::Vector3& axisX, - const AZ::Vector3& axisY, - const AZ::Vector3& axisZ, - const AZ::Vector3& halfExtents) - { - if (m_auxGeomPtr) - { - AZ::Quaternion rotation = AZ::Quaternion::CreateFromMatrix3x3(AZ::Matrix3x3::CreateFromColumns(axisX, axisY, axisZ)); - AZ::Obb obb = AZ::Obb::CreateFromPositionRotationAndHalfLengths(center, rotation, halfExtents); - m_auxGeomPtr->DrawObb( - obb, - AZ::Vector3::CreateZero(), - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Solid, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex); - } - } - - void AtomDebugDisplayViewportInterface::DrawPoint(const AZ::Vector3& p, int nSize) - { - if (m_auxGeomPtr) - { - AZ::Vector3 wsPoint = ToWorldSpacePosition(p); - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = &wsPoint; - drawArgs.m_vertCount = 1; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = aznumeric_cast(nSize); - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawPoints(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawLine(const AZ::Vector3& p1, const AZ::Vector3& p2) - { - if (m_auxGeomPtr) - { - AZ::Vector3 verts[2] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2)}; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = verts; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawLine(const AZ::Vector3& p1, const AZ::Vector3& p2, const AZ::Vector4& col1, const AZ::Vector4& col2) - { - if (m_auxGeomPtr) - { - AZ::Vector3 verts[2] = {ToWorldSpacePosition(p1), ToWorldSpacePosition(p2)}; - AZ::Color colors[2] = {col1, col2}; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = verts; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = colors; - drawArgs.m_colorCount = 2; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawLines(const AZStd::vector& lines, const AZ::Color& color) - { - if (m_auxGeomPtr) - { - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = lines.data(); - drawArgs.m_vertCount = aznumeric_cast(lines.size()); - drawArgs.m_colors = &color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawPolyLine(const AZ::Vector3* pnts, int numPoints, bool cycled) - { - if (m_auxGeomPtr) - { - AZStd::vector wsPoints(static_cast(numPoints)); - for (int index = 0; index < numPoints; ++index) - { - wsPoints[index] = ToWorldSpacePosition(pnts[index]); - } - AZ::RPI::AuxGeomDraw::PolylineEnd polylineEnd = cycled ? AZ::RPI::AuxGeomDraw::PolylineEnd::Closed : AZ::RPI::AuxGeomDraw::PolylineEnd::Open; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = wsPoints.data(); - drawArgs.m_vertCount = aznumeric_cast(numPoints); - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - m_auxGeomPtr->DrawPolylines(drawArgs, polylineEnd); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireQuad2d(const AZ::Vector2& p1, const AZ::Vector2& p2, float z) - { - if (m_auxGeomPtr) - { - AZ::Vector3 points[4]; - points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); - points[1] = AZ::Vector3(p2.GetX(), p1.GetY(), z); - points[2] = AZ::Vector3(p2.GetX(), p2.GetY(), z); - points[3] = AZ::Vector3(p1.GetX(), p2.GetY(), z); - - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = points; - drawArgs.m_vertCount = 4; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); - m_auxGeomPtr->DrawPolylines(drawArgs, AZ::RPI::AuxGeomDraw::PolylineEnd::Closed); - } - } - - void AtomDebugDisplayViewportInterface::DrawLine2d(const AZ::Vector2& p1, const AZ::Vector2& p2, float z) - { - if (m_auxGeomPtr) - { - AZ::Vector3 points[2]; - points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); - points[1] = AZ::Vector3(p2.GetX(), p2.GetY(), z); - - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = points; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawLine2dGradient(const AZ::Vector2& p1, const AZ::Vector2& p2, float z, const AZ::Vector4& firstColor, const AZ::Vector4& secondColor) - { - if (m_auxGeomPtr) - { - AZ::Vector3 points[2]; - points[0] = AZ::Vector3(p1.GetX(), p1.GetY(), z); - points[1] = AZ::Vector3(p2.GetX(), p2.GetY(), z); - AZ::Color colors[2] = {firstColor, secondColor}; - - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = points; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = colors; - drawArgs.m_colorCount = 2; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); - m_auxGeomPtr->DrawLines(drawArgs); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireCircle2d(const AZ::Vector2& center, float radius, float z) - { - if (m_auxGeomPtr) - { - // Draw axis aligned arc - constexpr float angularStepDegrees = 10.0f; - constexpr float startAngleDegrees = 0.0f; - constexpr float sweepAngleDegrees = 360.0f; - const float stepAngle = DegToRad(angularStepDegrees); - const float startAngle = DegToRad(startAngleDegrees); - const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; - SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - AZ::Vector3 pos = AZ::Vector3(center.GetX(), center.GetY(), z); - CreateAxisAlignedArc( - lines, - stepAngle, - startAngle, - stopAngle, - pos, - radiusV3, - CircleAxis::CircleAxisZ - ); - lines.Draw2d(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawArc( - const AZ::Vector3& pos, - float radius, - float startAngleDegrees, - float sweepAngleDegrees, - float angularStepDegrees, - int referenceAxis) - { - if (m_auxGeomPtr) - { - // Draw axis aligned arc - const float stepAngle = DegToRad(angularStepDegrees); - const float startAngle = DegToRad(startAngleDegrees); - const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; - SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - CreateAxisAlignedArc( - lines, - stepAngle, - startAngle, - stopAngle, - pos, - radiusV3, - static_cast(referenceAxis) - ); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawArc( - const AZ::Vector3& pos, - float radius, - float startAngleDegrees, - float sweepAngleDegrees, - float angularStepDegrees, - const AZ::Vector3& fixedAxis) - { - if (m_auxGeomPtr) - { - // Draw arbitraty axis arc - const float stepAngle = DegToRad(angularStepDegrees); - const float startAngle = DegToRad(startAngleDegrees); - const float stopAngle = DegToRad(sweepAngleDegrees) + startAngle; - SingleColorDynamicSizeLineHelper lines(1+static_cast(sweepAngleDegrees/angularStepDegrees)); - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - CreateArbitraryAxisArc( - lines, - stepAngle, - startAngle, - stopAngle, - pos, - radiusV3, - fixedAxis - ); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawCircle(const AZ::Vector3& pos, float radius, int nUnchangedAxis) - { - if (m_auxGeomPtr) - { - // Draw circle with default radius. - const float step = DegToRad(10.0f); - const float maxAngle = DegToRad(360.0f) + step; - SingleColorStaticSizeLineHelper<40> lines; // hard code 40 lines until DegToRad is constexpr. - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - CreateAxisAlignedArc( - lines, - step, - 0.0f, - maxAngle, - pos, - radiusV3, - static_cast(nUnchangedAxis)); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawHalfDottedCircle(const AZ::Vector3& pos, float radius, const AZ::Vector3& viewPos, int nUnchangedAxis) - { - if (m_auxGeomPtr) - { - // Draw circle with single radius. - const float step = DegToRad(10.0f); - const float maxAngle = DegToRad(360.0f) + step; - SingleColorStaticSizeLineHelper<40> lines; // hard code 40 lines until DegToRad is constexpr. - - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); - const AZ::Vector3 worldView = ToWorldSpacePosition(viewPos); - const AZ::Vector3 worldDir = worldView - worldPos; - - CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, radiusV3, static_cast(nUnchangedAxis%CircleAxisMax), - [&worldPos, &worldDir](const AZ::Vector3& lineStart, const AZ::Vector3& lineEnd, int segmentIndex) - { - AZ_UNUSED(lineEnd); - const float dot = (lineStart - worldPos).Dot(worldDir); - const bool facing = dot > 0.0f; - // if so skip every other line to produce a dotted effect - if (facing || segmentIndex % 2 == 0) - { - return true; - } - return false; - }); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawCone(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius, float height, bool drawShaded) - { - if (m_auxGeomPtr) - { - const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); - const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); - m_auxGeomPtr->DrawCone( - worldPos, - worldDir, - radius, - height, - m_rendState.m_color, - drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireCylinder(const AZ::Vector3& center, const AZ::Vector3& axis, float radius, float height) - { - if (m_auxGeomPtr) - { - const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); - const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); - m_auxGeomPtr->DrawCylinder( - worldCenter, - worldAxis, - radius, - height, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Line, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawSolidCylinder( - const AZ::Vector3& center, - const AZ::Vector3& axis, - float radius, - float height, - bool drawShaded) - { - if (m_auxGeomPtr) - { - const AZ::Vector3 worldCenter = ToWorldSpacePosition(center); - const AZ::Vector3 worldAxis = ToWorldSpaceVector(axis); - m_auxGeomPtr->DrawCylinder( - worldCenter, - worldAxis, - radius, - height, - m_rendState.m_color, - drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireCapsule( - const AZ::Vector3& center, - const AZ::Vector3& axis, - float radius, - float heightStraightSection) - { - if (m_auxGeomPtr && radius > FLT_EPSILON && axis.GetLengthSq() > FLT_EPSILON) - { - AZ::Vector3 axisNormalized = axis.GetNormalizedEstimate(); - SingleColorStaticSizeLineHelper<(16+1) * 5> lines; // 360/22.5 = 16, 5 possible calls to CreateArbitraryAxisArc - AZ::Vector3 radiusV3 = AZ::Vector3(radius); - float stepAngle = DegToRad(22.5f); - float Deg0 = DegToRad(0.0f); - - - // Draw cylinder part (or just a circle around the middle) - if (heightStraightSection > FLT_EPSILON) - { - DrawWireCylinder(center, axis, radius, heightStraightSection); - } - else - { - float Deg360 = DegToRad(360.0f); - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg0, - Deg360, - center, - radiusV3, - axisNormalized - ); - } - - float Deg90 = DegToRad(90.0f); - float Deg180 = DegToRad(180.0f); - - AZ::Vector3 ortho1Normalized, ortho2Normalized; - CalcBasisVectors(axisNormalized, ortho1Normalized, ortho2Normalized); - AZ::Vector3 centerToTopCircleCenter = axisNormalized * heightStraightSection * 0.5f; - AZ::Vector3 topCenter = center + centerToTopCircleCenter; - AZ::Vector3 bottomCenter = center - centerToTopCircleCenter; - - // Draw top cap as two criss-crossing 180deg arcs - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg90, - Deg90 + Deg180, - topCenter, - radiusV3, - ortho1Normalized - ); - - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg180, - Deg180 + Deg180, - topCenter, - radiusV3, - ortho2Normalized - ); - - // Draw bottom cap - CreateArbitraryAxisArc( - lines, - stepAngle, - -Deg90, - -Deg90 + Deg180, - bottomCenter, - radiusV3, - ortho1Normalized - ); - - CreateArbitraryAxisArc( - lines, - stepAngle, - Deg0, - Deg0 + Deg180, - bottomCenter, - radiusV3, - ortho2Normalized - ); - - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireSphere(const AZ::Vector3& pos, float radius) - { - if (m_auxGeomPtr) - { - - m_auxGeomPtr->DrawSphere( - ToWorldSpacePosition(pos), - radius, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Line, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireSphere(const AZ::Vector3& pos, const AZ::Vector3 radius) - { - if (m_auxGeomPtr) - { - // This matches Cry behavior, the DrawWireSphere above may need modifying to use the same approach. - // Draw 3 axis aligned circles - const float step = DegToRad(10.0f); - const float maxAngle = DegToRad(360.0f) + step; - SingleColorStaticSizeLineHelper<40*3> lines; // hard code to 40 lines * 3 circles until DegToRad is constexpr. - - // Z Axis - AZ::Vector3 axisRadius(radius.GetX(), radius.GetY(), 0.0f); - CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisZ); - - // X Axis - axisRadius = AZ::Vector3(0.0f, radius.GetY(), radius.GetZ()); - CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisX); - - // Y Axis - axisRadius = AZ::Vector3(radius.GetX(), 0.0f, radius.GetZ()); - CreateAxisAlignedArc(lines, step, 0.0f, maxAngle, pos, axisRadius, CircleAxisY); - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawWireDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) - { - if (m_auxGeomPtr) - { - - // Draw 3 axis aligned circles - const float stepAngle = DegToRad(11.25f); - const float startAngle = DegToRad(0.0f); - const float stopAngle = DegToRad(360.0f) + startAngle; - SingleColorDynamicSizeLineHelper lines(2+static_cast(360.0f/11.25f)); // num disk segments + 1 for azis line + 1 for spare - const AZ::Vector3 radiusV3 = AZ::Vector3(radius); - CreateArbitraryAxisArc( - lines, - stepAngle, - startAngle, - stopAngle, - pos, - radiusV3, - dir - ); - - lines.AddLineSegment(ToWorldSpacePosition(pos), ToWorldSpacePosition(pos + dir * (radius * 0.2f))); // 0.2f comes from Code\Sandbox\Editor\Objects\DisplayContextShared.inl DisplayContext::DrawWireDisk - lines.Draw(m_auxGeomPtr, m_rendState); - } - } - - void AtomDebugDisplayViewportInterface::DrawBall(const AZ::Vector3& pos, float radius, bool drawShaded) - { - if (m_auxGeomPtr) - { - // get the max scaled radius in case the transform on the stack is scaled non-uniformly - const float transformedRadiusX = ToWorldSpaceVector(AZ::Vector3(radius, 0.0f, 0.0f)).GetLengthEstimate(); - const float transformedRadiusY = ToWorldSpaceVector(AZ::Vector3(0.0f, radius, 0.0f)).GetLengthEstimate(); - const float transformedRadiusZ = ToWorldSpaceVector(AZ::Vector3(0.0f, 0.0f, radius)).GetLengthEstimate(); - const float maxTransformedRadius = - AZ::GetMax(transformedRadiusX, AZ::GetMax(transformedRadiusY, transformedRadiusZ)); - - AZ::RPI::AuxGeomDraw::DrawStyle drawStyle = drawShaded ? AZ::RPI::AuxGeomDraw::DrawStyle::Shaded : AZ::RPI::AuxGeomDraw::DrawStyle::Solid; - m_auxGeomPtr->DrawSphere( - ToWorldSpacePosition(pos), - maxTransformedRadius, - m_rendState.m_color, - drawStyle, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawDisk(const AZ::Vector3& pos, const AZ::Vector3& dir, float radius) - { - if (m_auxGeomPtr) - { - const AZ::Vector3 worldPos = ToWorldSpacePosition(pos); - const AZ::Vector3 worldDir = ToWorldSpaceVector(dir); - m_auxGeomPtr->DrawDisk( - worldPos, - worldDir, - radius, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - - void AtomDebugDisplayViewportInterface::DrawArrow(const AZ::Vector3& src, const AZ::Vector3& trg, float headScale, bool dualEndedArrow) - { - if (m_auxGeomPtr) - { - float f2dScale = 1.0f; - float arrowLen = 0.4f * headScale; - float arrowRadius = 0.1f * headScale; - // if (flags & DISPLAY_2D) - // { - // f2dScale = 1.2f * ToWorldSpaceVector(Vec3(1, 0, 0)).GetLength(); - // } - AZ::Vector3 dir = trg - src; - dir = ToWorldSpaceVector(dir.GetNormalized()); - AZ::Vector3 verts[2] = {ToWorldSpacePosition(src), ToWorldSpacePosition(trg)}; - AZ::RPI::AuxGeomDraw::AuxGeomDynamicDrawArguments drawArgs; - drawArgs.m_verts = verts; - drawArgs.m_vertCount = 2; - drawArgs.m_colors = &m_rendState.m_color; - drawArgs.m_colorCount = 1; - drawArgs.m_size = m_rendState.m_lineWidth; - drawArgs.m_opacityType = m_rendState.m_opacityType; - drawArgs.m_depthTest = m_rendState.m_depthTest; - drawArgs.m_depthWrite = m_rendState.m_depthWrite; - drawArgs.m_viewProjectionOverrideIndex = m_rendState.m_viewProjOverrideIndex; - if (!dualEndedArrow) - { - verts[1] -= dir * arrowLen; - m_auxGeomPtr->DrawLines(drawArgs); - m_auxGeomPtr->DrawCone( - verts[1], - dir, - arrowRadius * f2dScale, - arrowLen * f2dScale, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - else - { - verts[0] += dir * arrowLen; - verts[1] -= dir * arrowLen; - m_auxGeomPtr->DrawLines(drawArgs); - m_auxGeomPtr->DrawCone( - verts[0], - -dir, - arrowRadius * f2dScale, - arrowLen * f2dScale, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - m_auxGeomPtr->DrawCone( - verts[1], - dir, - arrowRadius * f2dScale, - arrowLen * f2dScale, - m_rendState.m_color, - AZ::RPI::AuxGeomDraw::DrawStyle::Shaded, - m_rendState.m_depthTest, - m_rendState.m_depthWrite, - m_rendState.m_faceCullMode, - m_rendState.m_viewProjOverrideIndex - ); - } - } - } - - void AtomDebugDisplayViewportInterface::DrawTextLabel( - const AZ::Vector3& pos, - float size, - const char* text, - const bool center, - int srcOffsetX [[maybe_unused]], - int srcOffsetY [[maybe_unused]]) - { - // abort draw if draw is invalid or font query interface is missing. - if (!text || size == 0.0f || !AZ::Interface::Get()) - { - return; - } - - AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); - // abort draw if font draw interface is missing - if (!fontDrawInterface) - { - return; - } - // if 2d draw need to project pos to screen first - AzFramework::TextDrawParameters params; - AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works - params.m_position = pos; - params.m_color = m_rendState.m_color; - params.m_scale = AZ::Vector2(size); - params.m_hAlign = center ? AzFramework::TextHorizontalAlignment::Center : AzFramework::TextHorizontalAlignment::Left; //! Horizontal text alignment - params.m_monospace = false; //! disable character proportional spacing - params.m_depthTest = false; //! Test character against the depth buffer - params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution - params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger - params.m_multiline = true; //! text respects ascii newline characters - - fontDrawInterface->DrawScreenAlignedText3d(params, text); - } - - void AtomDebugDisplayViewportInterface::Draw2dTextLabel( - float x, - float y, - float size, - const char* text, - bool center) - { -<<<<<<< HEAD - // abort draw if draw is invalid or font query interface is missing. - if (!text || size == 0.0f || !AZ::Interface::Get()) - { - return; - } - - AzFramework::FontDrawInterface* fontDrawInterface = AZ::Interface::Get()->GetDefaultFontDrawInterface(); - // abort draw if font draw interface is missing - if (!fontDrawInterface) -======= - auto fontQueryInterface = AZ::Interface::Get(); - if (!fontQueryInterface) - { - return; - } - AzFramework::FontDrawInterface* fontDrawInterface = fontQueryInterface->GetDefaultFontDrawInterface(); - if (!fontDrawInterface || !text || size == 0.0f) ->>>>>>> upstream/main - { - return; - } - // if 2d draw need to project pos to screen first - AzFramework::TextDrawParameters params; - AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - params.m_drawViewportId = viewportContext->GetId(); // get the viewport ID so default viewport works - params.m_position = AZ::Vector3(x, y, 1.0f); - params.m_color = m_rendState.m_color; - params.m_scale = AZ::Vector2(size); - params.m_hAlign = center ? AzFramework::TextHorizontalAlignment::Center : AzFramework::TextHorizontalAlignment::Left; //! Horizontal text alignment - params.m_monospace = false; //! disable character proportional spacing - params.m_depthTest = false; //! Test character against the depth buffer - params.m_virtual800x600ScreenSize = true; //! Text placement and size are scaled relative to a virtual 800x600 resolution - params.m_scaleWithWindow = false; //! Font gets bigger as the window gets bigger - params.m_multiline = true; //! text respects ascii newline characters - - fontDrawInterface->DrawScreenAlignedText2d(params, text); - } - - void AtomDebugDisplayViewportInterface::DrawTextOn2DBox( - const AZ::Vector3& pos [[maybe_unused]], - const char* text [[maybe_unused]], - float textScale [[maybe_unused]], - const AZ::Vector4& TextColor [[maybe_unused]], - const AZ::Vector4& TextBackColor [[maybe_unused]]) - { - AZ_Assert(false, "Unexpected use of legacy api, please file a feature request with the rendering team to get this implemented!"); - } - // unhandledled on Atom - virtual void DrawTextureLabel(ITexture* texture, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; - // void AtomDebugDisplayViewportInterface::DrawTextureLabel(int textureId, const AZ::Vector3& pos, float sizeX, float sizeY, int texIconFlags) override; - - void AtomDebugDisplayViewportInterface::SetLineWidth(float width) - { - AZ_Assert(width >= 0.0f && width <= 255.0f, "Width (%f) exceeds allowable range [0 - 255]", width); - m_rendState.m_lineWidth = static_cast(width); - } - - bool AtomDebugDisplayViewportInterface::IsVisible(const AZ::Aabb& bounds) - { - AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - const AZ::Matrix4x4& worldToClip = viewportContext->GetDefaultView()->GetWorldToClipMatrix(); - AZ::Frustum frustum = AZ::Frustum::CreateFromMatrixColumnMajor(worldToClip, Frustum::ReverseDepth::True); - return frustum.IntersectAabb(bounds) != AZ::IntersectResult::Exterior; - } - // int AtomDebugDisplayViewportInterface::SetFillMode(int nFillMode) override; - float AtomDebugDisplayViewportInterface::GetLineWidth() - { - return m_rendState.m_lineWidth; - } - - float AtomDebugDisplayViewportInterface::GetAspectRatio() - { - AZ::RPI::ViewportContextPtr viewportContext = GetViewportContext(); - auto windowSize = viewportContext->GetViewportSize(); - return aznumeric_cast(windowSize.m_width)/aznumeric_cast(windowSize.m_height); - } - - void AtomDebugDisplayViewportInterface::DepthTestOff() - { - m_rendState.m_depthTest = AZ::RPI::AuxGeomDraw::DepthTest::Off; - } - - void AtomDebugDisplayViewportInterface::DepthTestOn() - { - m_rendState.m_depthTest = AZ::RPI::AuxGeomDraw::DepthTest::On; - } - - void AtomDebugDisplayViewportInterface::DepthWriteOff() - { - m_rendState.m_depthWrite = AZ::RPI::AuxGeomDraw::DepthWrite::Off; - } - - void AtomDebugDisplayViewportInterface::DepthWriteOn() - { - m_rendState.m_depthWrite = AZ::RPI::AuxGeomDraw::DepthWrite::On; - } - - void AtomDebugDisplayViewportInterface::CullOff() - { - m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::None; - } - - void AtomDebugDisplayViewportInterface::CullOn() - { - m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::Back; - } - - bool AtomDebugDisplayViewportInterface::SetDrawInFrontMode(bool on) - { - AZ_UNUSED(on); - return false; - } - - AZ::u32 AtomDebugDisplayViewportInterface::GetState() - { - return ConvertRenderStateToCry(); - } - - AZ::u32 AtomDebugDisplayViewportInterface::SetState(AZ::u32 state) - { - uint32_t currentState = ConvertRenderStateToCry(); - uint32_t changedState = (state & e_PublicParamsMask) ^ currentState; - - if (changedState & e_Mode2D3DMask) - { - // this is the only way to turn on 2d Mode under Atom - if (state & e_Mode2D) - { - AZ_Assert((currentState & e_DrawInFrontOn) == 0 && (changedState & e_DrawInFrontOn) == 0, "Atom doesnt support Draw In Front and 2d at the same time"); - m_rendState.m_viewProjOverrideIndex = m_auxGeomPtr->GetOrAdd2DViewProjOverride(); - m_rendState.m_2dMode = true; - } - else // switch back to mode 3d - { - m_rendState.m_viewProjOverrideIndex = -1; - m_rendState.m_2dMode = false; - } - } - - if (changedState & e_AlphaBlendingMask) - { - switch (state&e_AlphaBlendingMask) - { - case e_AlphaNone: - m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Opaque; - break; - case e_AlphaAdditive: - [[fallthrough]]; // Additive not currently supported in Atom AuxGeom implementation - case e_AlphaBlended: - m_rendState.m_opacityType = AZ::RPI::AuxGeomDraw::OpacityType::Translucent; - break; - } - } - - if (changedState & e_DrawInFrontMask) - { - AZ_Assert( // either state is turning DrawInFront off or Mode 2D has to be off - (state & e_DrawInFrontOn) == 0 || - ((currentState & e_Mode2D) == 0 && (changedState & e_Mode2D) == 0), - "Atom doesnt support Draw In Front and 2d at the same time"); - SetDrawInFrontMode(changedState & e_DrawInFrontOn); - } - - if (changedState & e_CullModeMask) - { - switch (state & e_CullModeMask) - { - case e_CullModeNone: - CullOff(); - break; - case e_CullModeFront: - // Currently no other way to set front face culling in DebugDisplayRequestBus - m_rendState.m_faceCullMode = AZ::RPI::AuxGeomDraw::FaceCullMode::Front; - break; - case e_CullModeBack: - CullOn(); - break; - } - } - - if (changedState & e_DepthWriteMask) - { - if (state & e_DepthWriteOff) - { - DepthWriteOff(); - } - else - { - DepthWriteOn(); - } - } - - if (changedState & e_DepthTestMask) - { - if (state & e_DepthTestOff) - { - DepthTestOff(); - } - else - { - DepthTestOn(); - } - } - - return currentState; - } - - void AtomDebugDisplayViewportInterface::PushMatrix(const AZ::Transform& tm) - { - AZ_Assert(m_rendState.m_currentTransform < RenderState::TransformStackSize, "Exceeded AtomDebugDisplayViewportInterface matrix stack size"); - if (m_rendState.m_currentTransform < RenderState::TransformStackSize) - { - m_rendState.m_currentTransform++; - m_rendState.m_transformStack[m_rendState.m_currentTransform] = m_rendState.m_transformStack[m_rendState.m_currentTransform - 1] * AZ::Matrix3x4::CreateFromTransform(tm); - } - } - - void AtomDebugDisplayViewportInterface::PopMatrix() - { - AZ_Assert(m_rendState.m_currentTransform > 0, "Underflowed AtomDebugDisplayViewportInterface matrix stack"); - if (m_rendState.m_currentTransform > 0) - { - m_rendState.m_currentTransform--; - } - } - - const AZ::Matrix3x4& AtomDebugDisplayViewportInterface::GetCurrentTransform() const - { - return m_rendState.m_transformStack[m_rendState.m_currentTransform]; - } - - AZ::RPI::ViewportContextPtr AtomDebugDisplayViewportInterface::GetViewportContext() const - { - auto viewContextManager = AZ::Interface::Get(); - if (m_defaultInstance) - { - return viewContextManager->GetViewportContextByName(viewContextManager->GetDefaultViewportContextName()); - } - else - { - return viewContextManager->GetViewportContextById(m_viewportId); - } - } - - uint32_t AtomDebugDisplayViewportInterface::ConvertRenderStateToCry() const - { - uint32_t result = 0; - - result |= m_rendState.m_2dMode ? e_Mode2D : e_Mode3D; - result |= m_rendState.m_opacityType == AZ::RPI::AuxGeomDraw::OpacityType::Opaque ? e_AlphaNone : e_AlphaBlended; - result |= m_rendState.m_drawInFront ? e_DrawInFrontOn : e_DrawInFrontOff; - result |= m_rendState.m_depthTest == AZ::RPI::AuxGeomDraw::DepthTest::On ? e_DepthTestOn : e_DepthTestOff; - result |= m_rendState.m_depthWrite == AZ::RPI::AuxGeomDraw::DepthWrite::On ? e_DepthWriteOn : e_DepthWriteOff; - switch (m_rendState.m_faceCullMode) - { - case AZ::RPI::AuxGeomDraw::FaceCullMode::None: - result |= e_CullModeNone; - break; - case AZ::RPI::AuxGeomDraw::FaceCullMode::Front: - result |= e_CullModeFront; - break; - case AZ::RPI::AuxGeomDraw::FaceCullMode::Back: - result |= e_CullModeBack; - break; - default: - AZ_Assert(false, "Trying to convert an unknown culling mode to cry!"); - break; - } - - return result; - } -} From 64d980bc0361748bb6f09a2b58819584b4604a38 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 3 May 2021 15:40:32 -0500 Subject: [PATCH 045/185] Deleted AzFramework::AtomActiveInterface --- Code/CryEngine/CrySystem/System.cpp | 26 ------- Code/CryEngine/CrySystem/SystemInit.cpp | 16 ----- .../AzFramework/API/AtomActiveInterface.h | 26 ------- .../AzFramework/azframework_files.cmake | 1 - .../Utilities/HandleDpiAwareness_Windows.cpp | 1 - .../Editor/Core/LevelEditorMenuHandler.cpp | 1 - Code/Sandbox/Editor/CryEditDoc.cpp | 38 +---------- Code/Sandbox/Editor/EditorViewportWidget.cpp | 1 - Code/Sandbox/Editor/IconManager.cpp | 67 ++----------------- Code/Sandbox/Editor/LayoutWnd.cpp | 1 - Code/Sandbox/Editor/MainWindow.cpp | 14 +--- Code/Sandbox/Editor/RenderViewport.cpp | 27 ++------ Code/Sandbox/Editor/ToolbarManager.cpp | 1 - Code/Sandbox/Editor/ViewManager.cpp | 5 +- Code/Sandbox/Editor/ViewPane.cpp | 1 - .../SandboxIntegration.cpp | 3 +- .../Plugins/EditorCommon/QViewport.cpp | 13 ++-- .../Code/Source/AtomBridgeSystemComponent.cpp | 2 - .../Code/Source/AtomBridgeSystemComponent.h | 2 - .../Code/Source/BuilderComponent.cpp | 2 - .../AtomBridge/Code/Source/BuilderComponent.h | 2 - .../Pipeline/RCExt/Actor/ActorBuilder.cpp | 1 - .../Integration/Components/ActorComponent.h | 7 +- .../Components/EditorActorComponent.cpp | 2 +- .../Editor/EditorImageBuilderComponent.cpp | 10 +-- .../ImGuiEditorWindowSystemComponent.cpp | 15 ----- Gems/ImGui/Code/Source/ImGuiManager.cpp | 16 +---- .../Code/Source/WhiteBoxSystemComponent.cpp | 8 +-- 28 files changed, 26 insertions(+), 283 deletions(-) delete mode 100644 Code/Framework/AzFramework/AzFramework/API/AtomActiveInterface.h diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index a48f63afdf..827a393103 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -31,7 +31,6 @@ #include #include #include -#include #include @@ -1162,31 +1161,6 @@ void CSystem::SleepIfInactive() { return; } - -#if defined(WIN32) - if (!AZ::Interface::Get()) - { - WIN_HWND hRendWnd = GetIRenderer()->GetHWND(); - if (!hRendWnd) - { - return; - } - - AZ_TRACE_METHOD(); - // Loop here waiting for window to be activated. - for (int nLoops = 0; nLoops < 5; nLoops++) - { - WIN_HWND hActiveWnd = ::GetActiveWindow(); - if (hActiveWnd == hRendWnd) - { - break; - } - - AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty); - Sleep(5); - } - } -#endif } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index d293f9ca80..826810ef8a 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -68,7 +68,6 @@ #include #include #include -#include #include #include @@ -2462,21 +2461,6 @@ AZ_POP_DISABLE_WARNING m_env.pRenderer->SetViewport(0, 0, screenWidth, screenHeight); - // Skip splash screen rendering - if (!AZ::Interface::Get()) - { - // make sure it's rendered in full screen mode when triple buffering is enabled as well - for (size_t n = 0; n < 3; n++) - { - m_env.pRenderer->BeginFrame(); - m_env.pRenderer->SetCullMode(R_CULL_NONE); - m_env.pRenderer->SetState(GS_BLSRC_SRCALPHA | GS_BLDST_ONEMINUSSRCALPHA | GS_NODEPTHTEST); - m_env.pRenderer->Draw2dImageStretchMode(true); - m_env.pRenderer->Draw2dImage(x * vx, y * vy, w * vx, h * vy, pTex->GetTextureID(), 0.0f, 1.0f, 1.0f, 0.0f); - m_env.pRenderer->Draw2dImageStretchMode(false); - m_env.pRenderer->EndFrame(); - } - } #if defined(AZ_PLATFORM_IOS) || defined(AZ_PLATFORM_MAC) // Pump system events in order to update the screen AzFramework::ApplicationRequests::Bus::Broadcast(&AzFramework::ApplicationRequests::PumpSystemEventLoopUntilEmpty); diff --git a/Code/Framework/AzFramework/AzFramework/API/AtomActiveInterface.h b/Code/Framework/AzFramework/AzFramework/API/AtomActiveInterface.h deleted file mode 100644 index 80d4f6c867..0000000000 --- a/Code/Framework/AzFramework/AzFramework/API/AtomActiveInterface.h +++ /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. - * - */ -#pragma once - -#include - -namespace AzFramework -{ - class AtomActiveInterface - { - public: - AZ_RTTI(AtomActiveInterface, "{4BB59C86-0848-485D-AB28-700540470B2B}"); - - AtomActiveInterface() = default; - virtual ~AtomActiveInterface() = default; - }; -} // namespace AzFramework diff --git a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake index b126a192ac..88f68d8bab 100644 --- a/Code/Framework/AzFramework/AzFramework/azframework_files.cmake +++ b/Code/Framework/AzFramework/AzFramework/azframework_files.cmake @@ -14,7 +14,6 @@ set(FILES AzFrameworkModule.h AzFrameworkModule.cpp API/ApplicationAPI.h - API/AtomActiveInterface.h Application/Application.cpp Application/Application.h Archive/Archive.cpp diff --git a/Code/Framework/AzQtComponents/Platform/Windows/AzQtComponents/Utilities/HandleDpiAwareness_Windows.cpp b/Code/Framework/AzQtComponents/Platform/Windows/AzQtComponents/Utilities/HandleDpiAwareness_Windows.cpp index 9ffe06f7e3..b834995bd9 100644 --- a/Code/Framework/AzQtComponents/Platform/Windows/AzQtComponents/Utilities/HandleDpiAwareness_Windows.cpp +++ b/Code/Framework/AzQtComponents/Platform/Windows/AzQtComponents/Utilities/HandleDpiAwareness_Windows.cpp @@ -16,7 +16,6 @@ #include #include -#include #include namespace AzQtComponents diff --git a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp index 3f396894ff..869fa2fe25 100644 --- a/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp +++ b/Code/Sandbox/Editor/Core/LevelEditorMenuHandler.cpp @@ -23,7 +23,6 @@ #include "Objects/SelectionGroup.h" #include "ViewManager.h" -#include #include // Qt diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 41c49ab026..2bc4dcf10c 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -27,7 +27,6 @@ // AzFramework #include #include -#include // AzToolsFramework #include @@ -2417,42 +2416,7 @@ void CCryEditDoc::InitEmptyLevel(int /*resolution*/, int /*unitSize*/, bool /*bU void CCryEditDoc::CreateDefaultLevelAssets(int resolution, int unitSize) { - if (AZ::Interface::Get()) - { - AzToolsFramework::EditorLevelNotificationBus::Broadcast(&AzToolsFramework::EditorLevelNotificationBus::Events::OnNewLevelCreated); - } - else - { - bool isPrefabSystemEnabled = false; - AzFramework::ApplicationRequests::Bus::BroadcastResult( - isPrefabSystemEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled); - - if (!isPrefabSystemEnabled) - { - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - m_envProbeSliceAssetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, m_envProbeSliceRelativePath, - azrtti_typeid(), false); - - if (m_envProbeSliceAssetId.IsValid()) - { - AZ::Data::Asset asset = AZ::Data::AssetManager::Instance().FindOrCreateAsset( - m_envProbeSliceAssetId, AZ::Data::AssetLoadBehavior::Default); - if (asset) - { - m_terrainSize = resolution * unitSize; - const float halfTerrainSize = m_terrainSize / 2.0f; - - AZ::Transform worldTransform = AZ::Transform::CreateIdentity(); - worldTransform = AZ::Transform::CreateTranslation(AZ::Vector3(halfTerrainSize, halfTerrainSize, m_envProbeHeight / 2)); - - AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); - GetIEditor()->SuspendUndo(); - AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::Broadcast( - &AzToolsFramework::SliceEditorEntityOwnershipServiceRequests::InstantiateEditorSlice, asset, worldTransform); - } - } - } - } + AzToolsFramework::EditorLevelNotificationBus::Broadcast(&AzToolsFramework::EditorLevelNotificationBus::Events::OnNewLevelCreated); } void CCryEditDoc::OnEnvironmentPropertyChanged(IVariable* pVar) diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 9165809c7f..1a8d3a863d 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -40,7 +40,6 @@ # include #endif // defined(AZ_PLATFORM_WINDOWS) #include // for AzFramework::InputDeviceMouse -#include #include // AzQtComponents diff --git a/Code/Sandbox/Editor/IconManager.cpp b/Code/Sandbox/Editor/IconManager.cpp index 09c2d41035..3916ee7726 100644 --- a/Code/Sandbox/Editor/IconManager.cpp +++ b/Code/Sandbox/Editor/IconManager.cpp @@ -15,7 +15,6 @@ #include "IconManager.h" -#include #include // AzToolsFramework @@ -115,69 +114,11 @@ int CIconManager::GetIconTexture(const char* iconName) return 0; } - if (AZ::Interface::Get()) + ITexture* texture = GetIEditor()->GetRenderer() ? GetIEditor()->GetRenderer()->EF_LoadTexture(iconName) : nullptr; + if (texture) { - ITexture* texture = GetIEditor()->GetRenderer() ? GetIEditor()->GetRenderer()->EF_LoadTexture(iconName) : nullptr; - if (texture) - { - id = texture->GetTextureID(); - m_textures[iconName] = id; - } - } - else - { - QString ext = Path::GetExt(iconName); - QString actualName = iconName; - - char iconPath[AZ_MAX_PATH_LEN] = { 0 }; - gEnv->pFileIO->ResolvePath(actualName.toUtf8().data(), iconPath, AZ_MAX_PATH_LEN); - - // if we can't find it at the resolved path, try the devroot if necessary: - if (!gEnv->pFileIO->Exists(iconPath)) - { - if (iconName[0] != '@') // it has no specified alias - { - if (QString::compare(ext, "dds", Qt::CaseInsensitive) != 0) // if its a DDS, it comes out of processed files in @assets@, and assets is assumed by default (legacy renderer) - { - // check for a source file - AZStd::string iconFullPath; - bool pathFound = false; - using AssetSysReqBus = AzToolsFramework::AssetSystemRequestBus; - AssetSysReqBus::BroadcastResult(pathFound, &AssetSysReqBus::Events::GetFullSourcePathFromRelativeProductPath, iconName, iconFullPath); - - if (pathFound) - { - azstrncpy(iconPath, AZ_MAX_PATH_LEN, iconFullPath.c_str(), iconFullPath.length() + 1); - } - } - } - } - - CImageEx image; - // Load icon. - if (CImageUtil::LoadImage(iconPath, image)) - { - IRenderer* pRenderer(GetIEditor()->GetRenderer()); - if (pRenderer->GetRenderType() != eRT_DX11) - { - image.SwapRedAndBlue(); - } - - if (QString::compare(ext, "bmp", Qt::CaseInsensitive) == 0 || QString::compare(ext, "jpg", Qt::CaseInsensitive) == 0) - { - int sz = image.GetWidth() * image.GetHeight(); - uint8* buf = (uint8*)image.GetData(); - for (int i = 0; i < sz; i++) - { - uint32 alpha = max(max(buf[i * 4], buf[i * 4 + 1]), buf[i * 4 + 2]); - alpha *= 2; - buf[i * 4 + 3] = (alpha > 255) ? 255 : alpha; - } - } - - id = pRenderer->DownLoadToVideoMemory((unsigned char*)image.GetData(), image.GetWidth(), image.GetHeight(), eTF_R8G8B8A8, eTF_R8G8B8A8, 0, 0, 0); - m_textures[iconName] = id; - } + id = texture->GetTextureID(); + m_textures[iconName] = id; } return id; diff --git a/Code/Sandbox/Editor/LayoutWnd.cpp b/Code/Sandbox/Editor/LayoutWnd.cpp index 34a96bca53..54389f30c1 100644 --- a/Code/Sandbox/Editor/LayoutWnd.cpp +++ b/Code/Sandbox/Editor/LayoutWnd.cpp @@ -24,7 +24,6 @@ #include #include -#include #include // for AzQtComponents::Style // Editor diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index 96f4da7312..eadc137900 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -42,7 +42,6 @@ AZ_POP_DISABLE_WARNING #include #include #include -#include // AzToolsFramework #include @@ -1095,7 +1094,7 @@ void MainWindow::InitActions() QAction* saveLevelStatsAction = am->AddAction(ID_TOOLS_LOGMEMORYUSAGE, tr("Save Level Statistics")) .SetStatusTip(tr("Logs Editor memory usage.")); - if( saveLevelStatsAction && AZ::Interface::Get()) + if( saveLevelStatsAction ) { saveLevelStatsAction->setEnabled(false); } @@ -1191,13 +1190,6 @@ void MainWindow::InitActions() .SetIcon(Style::icon("Audio")) .SetApplyHoverEffect(); - if (!AZ::Interface::Get()) - { - am->AddAction(ID_TERRAIN_TIMEOFDAYBUTTON, tr("Time of Day Editor")) - .SetToolTip(tr("Open Time of Day")) - .SetApplyHoverEffect(); - } - am->AddAction(ID_OPEN_UICANVASEDITOR, tr(LyViewPane::UiEditor)) .SetToolTip(tr("Open UI Editor")) .SetApplyHoverEffect(); @@ -1654,10 +1646,6 @@ void MainWindow::RegisterStdViewClasses() AzAssetBrowserWindow::RegisterViewClass(); AssetEditorWindow::RegisterViewClass(); - if (!AZ::Interface::Get()) - { - CTimeOfDayDialog::RegisterViewClass(); - } #ifdef ThumbnailDemo ThumbnailsSampleWidget::RegisterViewClass(); #endif diff --git a/Code/Sandbox/Editor/RenderViewport.cpp b/Code/Sandbox/Editor/RenderViewport.cpp index cac1840b75..3e726f2468 100644 --- a/Code/Sandbox/Editor/RenderViewport.cpp +++ b/Code/Sandbox/Editor/RenderViewport.cpp @@ -42,7 +42,6 @@ # include #endif // defined(AZ_PLATFORM_WINDOWS) #include // for AzFramework::InputDeviceMouse -#include // AzQtComponents #include @@ -275,13 +274,10 @@ void CRenderViewport::resizeEvent(QResizeEvent* event) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, width(), height()); - if (AZ::Interface::Get()) - { - // 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. - m_windowResizedEvent = true; - } + // 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. + m_windowResizedEvent = true; } ////////////////////////////////////////////////////////////////////////// @@ -1553,14 +1549,6 @@ void CRenderViewport::OnRender() if (levelIsDisplayable) { m_renderer->SetViewport(0, 0, m_renderer->GetWidth(), m_renderer->GetHeight(), m_nCurViewportID); - - if (!AZ::Interface::Get()) - { - m_engine->Tick(); - m_engine->Update(); - - m_engine->RenderWorld(SHDF_ALLOW_AO | SHDF_ALLOWPOSTPROCESS | SHDF_ALLOW_WATER | SHDF_ALLOWHDR | SHDF_ZPASS, SRenderingPassInfo::CreateGeneralPassRenderingInfo(m_Camera), __FUNCTION__); - } } else { @@ -3659,11 +3647,8 @@ bool CRenderViewport::CreateRenderContext() { m_bRenderContextCreated = true; - if (AZ::Interface::Get()) - { - AzFramework::WindowRequestBus::Handler::BusConnect(renderOverlayHWND()); - AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, renderOverlayHWND()); - } + AzFramework::WindowRequestBus::Handler::BusConnect(renderOverlayHWND()); + AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, renderOverlayHWND()); WIN_HWND oldContext = m_renderer->GetCurrentContextHWND(); m_renderer->CreateContext(renderOverlayHWND()); diff --git a/Code/Sandbox/Editor/ToolbarManager.cpp b/Code/Sandbox/Editor/ToolbarManager.cpp index 01bd7be82b..bbb3ef6790 100644 --- a/Code/Sandbox/Editor/ToolbarManager.cpp +++ b/Code/Sandbox/Editor/ToolbarManager.cpp @@ -16,7 +16,6 @@ // AzCore #include -#include #include // Qt diff --git a/Code/Sandbox/Editor/ViewManager.cpp b/Code/Sandbox/Editor/ViewManager.cpp index 7dd0f3e033..334e78a826 100644 --- a/Code/Sandbox/Editor/ViewManager.cpp +++ b/Code/Sandbox/Editor/ViewManager.cpp @@ -34,7 +34,6 @@ #include "EditorViewportWidget.h" #include "CryEditDoc.h" -#include #include AZ_CVAR(bool, ed_useAtomNativeViewport, true, nullptr, AZ::ConsoleFunctorFlags::Null, "Use the new Atom-native Editor viewport (experimental, not yet stable"); @@ -42,7 +41,7 @@ AZ_CVAR(bool, ed_useAtomNativeViewport, true, nullptr, AZ::ConsoleFunctorFlags:: bool CViewManager::IsMultiViewportEnabled() { // Enable multi-viewport for legacy renderer, or if we're using the new fully Atom-native viewport - return !AZ::Interface::Get() || ed_useAtomNativeViewport; + return ed_useAtomNativeViewport; } ////////////////////////////////////////////////////////////////////// @@ -81,7 +80,7 @@ CViewManager::CViewManager() RegisterQtViewPane(GetIEditor(), "Left", LyViewPane::CategoryViewport, viewportOptions); viewportOptions.viewportType = ET_ViewportCamera; - if (ed_useAtomNativeViewport && AZ::Interface::Get()) + if (ed_useAtomNativeViewport) { RegisterQtViewPaneWithName(GetIEditor(), "Perspective", LyViewPane::CategoryViewport, viewportOptions); } diff --git a/Code/Sandbox/Editor/ViewPane.cpp b/Code/Sandbox/Editor/ViewPane.cpp index 43e4330113..480e39bedf 100644 --- a/Code/Sandbox/Editor/ViewPane.cpp +++ b/Code/Sandbox/Editor/ViewPane.cpp @@ -33,7 +33,6 @@ // AzFramework #include -#include #include // Editor diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index ecfb155d79..b0dce80ec8 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -30,7 +30,6 @@ #include #include #include -#include #include #include #include @@ -163,7 +162,7 @@ void SandboxIntegrationManager::Setup() AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusConnect(); AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); // turn on the this debug display request bus implementation if no other implementation is active - if( !(AZ::Interface::Get() && AzFramework::DebugDisplayRequestBus::HasHandlers())) + if( !(AzFramework::DebugDisplayRequestBus::HasHandlers())) { m_debugDisplayBusImplementationActive = true; AzFramework::DebugDisplayRequestBus::Handler::BusConnect( diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp index 5ca6cf5ac6..362452a67e 100644 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp @@ -37,8 +37,6 @@ #include #include -#include - #include // Class to implement the WindowRequestBus::Handler instead of the QViewport class. @@ -365,7 +363,7 @@ bool QViewport::CreateRenderContext() HWND windowHandle = reinterpret_cast(QWidget::winId()); - if( AZ::Interface::Get() && m_renderContextCreated && windowHandle == m_lastHwnd) + if( m_renderContextCreated && windowHandle == m_lastHwnd) { // the hwnd has not changed, no need to destroy and recreate context (and swap chain etc) return false; @@ -377,13 +375,10 @@ bool QViewport::CreateRenderContext() { m_renderContextCreated = true; - if (AZ::Interface::Get()) - { - m_viewportRequests.get()->BusConnect(windowHandle); - AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, windowHandle); + m_viewportRequests.get()->BusConnect(windowHandle); + AzFramework::WindowSystemNotificationBus::Broadcast(&AzFramework::WindowSystemNotificationBus::Handler::OnWindowCreated, windowHandle); - m_lastHwnd = windowHandle; - } + m_lastHwnd = windowHandle; StorePreviousContext(); GetIEditor()->GetEnv()->pRenderer->CreateContext(windowHandle); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp index f04e156afd..90731488f4 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.cpp @@ -62,12 +62,10 @@ namespace AZ AtomBridgeSystemComponent::AtomBridgeSystemComponent() { - AZ::Interface::Register(this); } AtomBridgeSystemComponent::~AtomBridgeSystemComponent() { - AZ::Interface::Unregister(this); } void AtomBridgeSystemComponent::GetProvidedServices(ComponentDescriptor::DependencyArrayType& provided) diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h index 2ffd966216..da75d3c35c 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeSystemComponent.h @@ -17,7 +17,6 @@ #include -#include #include #include @@ -37,7 +36,6 @@ namespace AZ class AtomBridgeSystemComponent : public Component - , public AzFramework::AtomActiveInterface , public AzFramework::Render::RenderSystemRequestBus::Handler , public AzFramework::Components::DeprecatedComponentsRequestBus::Handler , public Render::Bootstrap::NotificationBus::Handler diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp index b6ff2cb66d..997b7c3b0c 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp @@ -36,12 +36,10 @@ namespace AZ BuilderComponent::BuilderComponent() { - AZ::Interface::Register(this); } BuilderComponent::~BuilderComponent() { - AZ::Interface::Unregister(this); } void BuilderComponent::Activate() diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h index 4e75fd2a88..d6c462cc43 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h @@ -13,7 +13,6 @@ #pragma once #include -#include namespace AZ { @@ -21,7 +20,6 @@ namespace AZ { class BuilderComponent final : public AZ::Component - , public AzFramework::AtomActiveInterface { public: AZ_COMPONENT(BuilderComponent, "{D1FE015B-8431-4155-8FD0-8197F246901A}"); diff --git a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp index d57105a589..1327045806 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Pipeline/RCExt/Actor/ActorBuilder.cpp @@ -43,7 +43,6 @@ #include #include #include -#include #include diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h index 1a185edccc..416705bff4 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.h @@ -22,7 +22,6 @@ #include #include #include -#include #include #include @@ -130,11 +129,7 @@ namespace EMotionFX provided.push_back(AZ_CRC("EMotionFXActorService", 0xd6e8f48d)); provided.push_back(AZ_CRC("MeshService", 0x71d8a455)); provided.push_back(AZ_CRC("CharacterPhysicsDataService", 0x34757927)); - - if (AZ::Interface::Get()) - { - provided.push_back(AZ_CRC("MaterialReceiverService", 0x0d1a6a74)); - } + provided.push_back(AZ_CRC("MaterialReceiverService", 0x0d1a6a74)); } static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index bcb1e3f300..42deabda49 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -822,7 +822,7 @@ namespace EMotionFX bool EditorActorComponent::IsAtomDisabled() const { - return !AZ::Interface::Get(); + return false; } void EditorActorComponent::OnActorReady(Actor* actor) diff --git a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp index bd1fbfb464..d7fcd3e56e 100644 --- a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp @@ -24,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -334,14 +333,7 @@ namespace GradientSignal AZStd::unique_ptr EditorImageBuilderWorker::LoadImageFromPath(const AZStd::string& fullPath) { - if (AZ::Interface::Get()) - { - return AtomLoadImageFromPath(fullPath); - } - else - { - return LegacyLoadImageFromPath(fullPath); - } + return AtomLoadImageFromPath(fullPath); } AZStd::unique_ptr EditorImageBuilderWorker::LoadImageSettingsFromPath(const AZStd::string& fullPath) diff --git a/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp b/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp index 6c370e091c..07ab3b0a42 100644 --- a/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp +++ b/Gems/ImGui/Code/Editor/ImGuiEditorWindowSystemComponent.cpp @@ -18,7 +18,6 @@ #include "ImGuiEditorWindowSystemComponent.h" #include "ImGuiMainWindow.h" #include -#include static const char* s_ImGuiQtViewPaneName = "ImGui Editor"; @@ -60,19 +59,5 @@ namespace ImGui void ImGuiEditorWindowSystemComponent::NotifyRegisterViews() { - if (!AZ::Interface::Get()) - { - // The Tools->ImGui menu currently crashes trying to enable a render pipeline when this is invoked - // Disable this menu item for now - // [GFX TODO][ATOM-4607] - QtViewOptions options; - options.canHaveMultipleInstances = false; - AzToolsFramework::EditorRequests::Bus::Broadcast( - &AzToolsFramework::EditorRequests::RegisterViewPane, - s_ImGuiQtViewPaneName, - "Tools", - options, - [](QWidget* parent = nullptr) { return new ImGui::ImGuiMainWindow(parent); }); - } } } diff --git a/Gems/ImGui/Code/Source/ImGuiManager.cpp b/Gems/ImGui/Code/Source/ImGuiManager.cpp index e10a59bde1..c9b32ac692 100644 --- a/Gems/ImGui/Code/Source/ImGuiManager.cpp +++ b/Gems/ImGui/Code/Source/ImGuiManager.cpp @@ -26,7 +26,6 @@ #include #include #include -#include #include #include #include @@ -380,14 +379,8 @@ void ImGuiManager::Render() TransformationMatrices backupSceneMatrices; - AZ::u32 backBufferWidth = 0; - AZ::u32 backBufferHeight = 0; - - if (AZ::Interface::Get()) - { - backBufferWidth = m_windowSize.m_width; - backBufferHeight = m_windowSize.m_height; - } + AZ::u32 backBufferWidth = m_windowSize.m_width; + AZ::u32 backBufferHeight = m_windowSize.m_height; // Find ImGui Render Resolution. int renderRes[2]; @@ -759,10 +752,7 @@ void ImGuiManager::RenderImGuiBuffers(const ImVec2& scaleRects) //@rky: Only render the main ImGui if it is visible if (m_clientMenuBarState != DisplayState::Hidden) { - if (AZ::Interface::Get()) - { - OtherActiveImGuiRequestBus::Broadcast(&OtherActiveImGuiRequestBus::Events::RenderImGuiBuffers, *drawData); - } + OtherActiveImGuiRequestBus::Broadcast(&OtherActiveImGuiRequestBus::Events::RenderImGuiBuffers, *drawData); } } diff --git a/Gems/WhiteBox/Code/Source/WhiteBoxSystemComponent.cpp b/Gems/WhiteBox/Code/Source/WhiteBoxSystemComponent.cpp index 6f24d409c9..8dc37c94fe 100644 --- a/Gems/WhiteBox/Code/Source/WhiteBoxSystemComponent.cpp +++ b/Gems/WhiteBox/Code/Source/WhiteBoxSystemComponent.cpp @@ -19,7 +19,6 @@ #include #include -#include namespace WhiteBox { @@ -63,12 +62,7 @@ namespace WhiteBox SetRenderMeshInterfaceBuilder( []() -> AZStd::unique_ptr { - if (AZ::Interface::Get()) - { - return AZStd::make_unique(); - } - - return AZStd::make_unique(); + return AZStd::make_unique(); }); WhiteBoxRequestBus::Handler::BusConnect(); From 6b0871946657a67be530c76924c21314c258a3e8 Mon Sep 17 00:00:00 2001 From: michabr <82236305+michabr@users.noreply.github.com> Date: Mon, 3 May 2021 13:58:54 -0700 Subject: [PATCH 046/185] Fix UI Canvas loading in Launcher (#468) (#515) * Fix UI Canvas loading in Launcher (#468) * Resolve merge conflict --- Gems/LyShine/Code/Source/LyShine.cpp | 7 +++---- Gems/LyShine/Code/Source/UiCanvasComponent.cpp | 11 +++++------ Gems/LyShine/Code/Source/UiCanvasManager.cpp | 2 ++ 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/Gems/LyShine/Code/Source/LyShine.cpp b/Gems/LyShine/Code/Source/LyShine.cpp index 286e756ffa..3ea451b7c5 100644 --- a/Gems/LyShine/Code/Source/LyShine.cpp +++ b/Gems/LyShine/Code/Source/LyShine.cpp @@ -72,6 +72,8 @@ #include #include +#include + #include "Animation/UiAnimationSystem.h" #include "World/UiCanvasAssetRefComponent.h" #include "World/UiCanvasProxyRefComponent.h" @@ -425,11 +427,8 @@ void CLyShine::Render() { FRAME_PROFILER(__FUNCTION__, gEnv->pSystem, PROFILE_UI); - // LYSHINE_ATOM_TODO - convert to use Atom interface to check for null renderer - if (!gEnv || !gEnv->pRenderer || gEnv->pRenderer->GetRenderType() == ERenderType::eRT_Null) + if (AZ::RHI::IsNullRenderer()) { - // if the renderer is not initialized or it is the null renderer (e.g. running as a server) - // then do nothing return; } diff --git a/Gems/LyShine/Code/Source/UiCanvasComponent.cpp b/Gems/LyShine/Code/Source/UiCanvasComponent.cpp index 2af773734c..8578e6b8eb 100644 --- a/Gems/LyShine/Code/Source/UiCanvasComponent.cpp +++ b/Gems/LyShine/Code/Source/UiCanvasComponent.cpp @@ -257,13 +257,13 @@ namespace UiRenderer* GetUiRendererForGame() { CLyShine* lyShine = static_cast(gEnv->pLyShine); - return lyShine->GetUiRenderer(); + return lyShine ? lyShine->GetUiRenderer() : nullptr; } UiRenderer* GetUiRendererForEditor() { CLyShine* lyShine = static_cast(gEnv->pLyShine); - return lyShine->GetUiRendererForEditor(); + return lyShine ? lyShine->GetUiRendererForEditor() : nullptr; } bool IsValidInteractable(const AZ::EntityId& entityId) @@ -4255,8 +4255,8 @@ UiCanvasComponent* UiCanvasComponent::FixupPostLoad(AZ::Entity* canvasEntity, AZ // Initialize the target canvas size and uniform scale // This should be done before calling InGamePostActivate so that the // canvas space rects of the elements are accurate - AZ_Assert(gEnv->pRenderer, "Attempting to access IRenderer before it has been initialized"); - if (gEnv->pRenderer) + UiRenderer* uiRenderer = forEditor ? GetUiRendererForEditor() : GetUiRendererForGame(); + if (uiRenderer) // can be null in automated testing { AZ::Vector2 targetCanvasSize; if (canvasSize) @@ -4265,8 +4265,7 @@ UiCanvasComponent* UiCanvasComponent::FixupPostLoad(AZ::Entity* canvasEntity, AZ } else { - targetCanvasSize.SetX(static_cast(gEnv->pRenderer->GetOverlayWidth())); - targetCanvasSize.SetY(static_cast(gEnv->pRenderer->GetOverlayHeight())); + targetCanvasSize = uiRenderer->GetViewportSize(); } canvasComponent->SetTargetCanvasSizeAndUniformScale(!forEditor, targetCanvasSize); } diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.cpp b/Gems/LyShine/Code/Source/UiCanvasManager.cpp index 6575a1d2f0..958dba0ab8 100644 --- a/Gems/LyShine/Code/Source/UiCanvasManager.cpp +++ b/Gems/LyShine/Code/Source/UiCanvasManager.cpp @@ -612,10 +612,12 @@ void UiCanvasManager::RenderLoadedCanvases() m_fontTextureHasChanged = false; } +#ifdef LYSHINE_ATOM_TODO // render target conversion to Atom // clear the stencil buffer before rendering the loaded canvases - required for masking // NOTE: We want to use ClearTargetsImmediately instead of ClearTargetsLater since we will not be setting the render target ColorF viewportBackgroundColor(0, 0, 0, 0); // if clearing color we want to set alpha to zero also gEnv->pRenderer->ClearTargetsImmediately(FRT_CLEAR_STENCIL, viewportBackgroundColor); +#endif for (auto canvas : m_loadedCanvases) { From 93254944feea0cb1994092cb536dcb1f1fe39f94 Mon Sep 17 00:00:00 2001 From: Vincent Liu <5900509+onecent1101@users.noreply.github.com> Date: Mon, 3 May 2021 14:02:39 -0700 Subject: [PATCH 047/185] [SPEC-6602] Add module class to make sure profile build generate required Qt binaries (#509) --- Gems/AWSCore/Code/CMakeLists.txt | 10 ++--- .../AWSCoreResourceMappingToolModule.cpp | 44 +++++++++++++++++++ .../awscore_resourcemappingtool_files.cmake | 3 +- 3 files changed, 48 insertions(+), 9 deletions(-) create mode 100644 Gems/AWSCore/Code/Source/AWSCoreResourceMappingToolModule.cpp diff --git a/Gems/AWSCore/Code/CMakeLists.txt b/Gems/AWSCore/Code/CMakeLists.txt index 468530be31..a58b02d1d4 100644 --- a/Gems/AWSCore/Code/CMakeLists.txt +++ b/Gems/AWSCore/Code/CMakeLists.txt @@ -86,7 +86,7 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) ) ly_add_target( - NAME AWSCore.ResourceMappintTool MODULE + NAME AWSCore.ResourceMappingTool MODULE NAMESPACE Gem OUTPUT_SUBDIRECTORY AWSCoreEditorQtBin FILES_CMAKE @@ -94,15 +94,11 @@ if (PAL_TRAIT_BUILD_HOST_TOOLS) INCLUDE_DIRECTORIES PRIVATE Include/Private - PUBLIC - Include/Public BUILD_DEPENDENCIES PRIVATE - 3rdParty::Qt::Core - 3rdParty::Qt::Widgets - AZ::AzToolsFramework + Gem::AWSCore.Editor.Static ) - ly_add_dependencies(AWSCore.Editor AWSCore.ResourceMappintTool) + ly_add_dependencies(AWSCore.Editor AWSCore.ResourceMappingTool) endif() ################################################################################ diff --git a/Gems/AWSCore/Code/Source/AWSCoreResourceMappingToolModule.cpp b/Gems/AWSCore/Code/Source/AWSCoreResourceMappingToolModule.cpp new file mode 100644 index 0000000000..794ee6c880 --- /dev/null +++ b/Gems/AWSCore/Code/Source/AWSCoreResourceMappingToolModule.cpp @@ -0,0 +1,44 @@ +/* +* 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 +#include + +namespace AWSCore +{ + class AWSCoreResourceMappingToolModule + : public AZ::Module + { + public: + AZ_RTTI(AWSCoreResourceMappingToolModule, "{9D16F400-009C-47FF-A186-E48BEB73D94D}", AZ::Module); + AZ_CLASS_ALLOCATOR(AWSCoreResourceMappingToolModule, AZ::SystemAllocator, 0); + + AWSCoreResourceMappingToolModule() + { + m_descriptors.insert(m_descriptors.end(), + { + AWSCoreEditorSystemComponent::CreateDescriptor(), + }); + } + + ~AWSCoreResourceMappingToolModule() override = default; + + AZ::ComponentTypeList GetRequiredSystemComponents() const override + { + return AZ::ComponentTypeList{azrtti_typeid()}; + } + }; +} + +// DO NOT MODIFY THIS LINE UNLESS YOU RENAME THE GEM +// The first parameter should be GemName_GemIdLower +// The second should be the fully qualified name of the class above +AZ_DECLARE_MODULE_CLASS(Gem_AWSCore_ResourceMappingTool, AWSCore::AWSCoreResourceMappingToolModule) diff --git a/Gems/AWSCore/Code/awscore_resourcemappingtool_files.cmake b/Gems/AWSCore/Code/awscore_resourcemappingtool_files.cmake index b67c50e955..466a2c917f 100644 --- a/Gems/AWSCore/Code/awscore_resourcemappingtool_files.cmake +++ b/Gems/AWSCore/Code/awscore_resourcemappingtool_files.cmake @@ -10,6 +10,5 @@ # set(FILES - Include/Private/Editor/UI/AWSCoreResourceMappingToolAction.h - Source/Editor/UI/AWSCoreResourceMappingToolAction.cpp + Source/AWSCoreResourceMappingToolModule.cpp ) From f4def0c93fd20bd0b885c06276dcf0927e298963 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 3 May 2021 16:33:06 -0500 Subject: [PATCH 048/185] Minor compile warning cleanup --- Code/Sandbox/Editor/CryEditDoc.cpp | 2 +- .../Editor/EditorImageBuilderComponent.cpp | 33 ------------------- 2 files changed, 1 insertion(+), 34 deletions(-) diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 2bc4dcf10c..6f3afa6850 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -2414,7 +2414,7 @@ void CCryEditDoc::InitEmptyLevel(int /*resolution*/, int /*unitSize*/, bool /*bU GetIEditor()->SetStatusText("Ready"); } -void CCryEditDoc::CreateDefaultLevelAssets(int resolution, int unitSize) +void CCryEditDoc::CreateDefaultLevelAssets([[maybe_unused]] int resolution, [[maybe_unused]] int unitSize) { AzToolsFramework::EditorLevelNotificationBus::Broadcast(&AzToolsFramework::EditorLevelNotificationBus::Events::OnNewLevelCreated); } diff --git a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp index d7fcd3e56e..cc207b59a3 100644 --- a/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp +++ b/Gems/GradientSignal/Code/Source/Editor/EditorImageBuilderComponent.cpp @@ -257,39 +257,6 @@ namespace GradientSignal return AZ::Uuid::CreateString("{7520DF20-16CA-4CF6-A6DB-D96759A09EE4}"); } - static AZStd::unique_ptr LegacyLoadImageFromPath(const AZStd::string& fullPath) - { - ImageProcessing::IImageObjectPtr imageObject; - ImageProcessing::ImageProcessingRequestBus::BroadcastResult(imageObject, &ImageProcessing::ImageProcessingRequests::LoadImage, - fullPath); - - if (!imageObject) - { - return {}; - } - - //create a new image asset - auto imageAsset = AZStd::make_unique(); - - if (!imageAsset) - { - return {}; - } - - imageAsset->m_imageWidth = imageObject->GetWidth(0); - imageAsset->m_imageHeight = imageObject->GetHeight(0); - imageAsset->m_imageFormat = imageObject->GetPixelFormat(); - - AZ::u8* mem = nullptr; - AZ::u32 pitch = 0; - AZ::u32 mipBufferSize = imageObject->GetMipBufSize(0); - imageObject->GetImagePointer(0, mem, pitch); - - imageAsset->m_imageData = { mem, mem + mipBufferSize }; - - return imageAsset; - } - static ImageProcessing::EPixelFormat AtomPixelFormatToLegacyPixelFormat(ImageProcessingAtom::EPixelFormat atomPixFormat) { // This could be dangerous to do if these enums have differences in the middle. From 8b0b3f4d02e560bae6255c1c9fc4db409722b5c3 Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Mon, 3 May 2021 16:42:11 -0500 Subject: [PATCH 049/185] [LYN-3078] Removed legacy CMaterial and all related/unused classes. --- .../CryMaterialsCommands_test.py | 75 - .../CryMaterialsCommands_test_case.py | 116 - Code/CryEngine/CryCommon/IShader.h | 1 - .../AzToolsFrameworkModule.cpp | 2 - .../MaterialBrowser/MaterialBrowserBus.h | 43 - .../MaterialBrowserComponent.cpp | 65 - .../MaterialBrowserComponent.h | 41 - .../MaterialBrowser/MaterialThumbnail.cpp | 67 - .../MaterialBrowser/MaterialThumbnail.h | 86 - .../aztoolsframework_files.cmake | 5 - .../Editor/Controls/PreviewModelCtrl.cpp | 35 - .../Editor/Controls/PreviewModelCtrl.h | 6 - .../ReflectedPropertyControl/PropertyCtrl.cpp | 1 - .../PropertyGenericCtrl.cpp | 20 - .../PropertyGenericCtrl.h | 11 - .../PropertyResourceCtrl.cpp | 2 - .../ReflectedPropertyCtrl.cpp | 10 - .../ReflectedPropertyItem.cpp | 3 - .../ReflectedPropertyControl/ReflectedVar.cpp | 2 - .../ReflectedVarWrapper.cpp | 2 - Code/Sandbox/Editor/CryEdit.cpp | 23 - Code/Sandbox/Editor/CryEdit.h | 3 - Code/Sandbox/Editor/CryEditDoc.cpp | 11 - Code/Sandbox/Editor/DisplaySettings.cpp | 25 - .../Sandbox/Editor/EditorToolsApplication.cpp | 4 - Code/Sandbox/Editor/ErrorReport.h | 1 - Code/Sandbox/Editor/Export/ExportManager.cpp | 75 - Code/Sandbox/Editor/Export/ExportManager.h | 2 - Code/Sandbox/Editor/GameExporter.cpp | 49 - Code/Sandbox/Editor/GameExporter.h | 1 - Code/Sandbox/Editor/GameResourcesExporter.cpp | 13 +- Code/Sandbox/Editor/GameResourcesExporter.h | 1 - Code/Sandbox/Editor/IEditor.h | 4 - Code/Sandbox/Editor/IEditorImpl.cpp | 16 +- Code/Sandbox/Editor/IEditorImpl.h | 2 - Code/Sandbox/Editor/Include/IErrorReport.h | 1 - Code/Sandbox/Editor/LevelInfo.cpp | 10 - Code/Sandbox/Editor/LevelInfo.h | 1 - Code/Sandbox/Editor/Lib/Tests/IEditorMock.h | 1 - .../Lib/Tests/test_MaterialPythonFuncs.cpp | 68 - Code/Sandbox/Editor/MainWindow.cpp | 2 - Code/Sandbox/Editor/MatEditPreviewDlg.cpp | 149 -- Code/Sandbox/Editor/MatEditPreviewDlg.h | 66 - Code/Sandbox/Editor/Material/Material.cpp | 1982 --------------- Code/Sandbox/Editor/Material/Material.h | 315 --- .../Editor/Material/MaterialBrowser.cpp | 1792 ------------- .../Sandbox/Editor/Material/MaterialBrowser.h | 248 -- .../Editor/Material/MaterialBrowser.ui | 87 - .../Material/MaterialBrowserFilterModel.cpp | 652 ----- .../Material/MaterialBrowserFilterModel.h | 240 -- .../Material/MaterialBrowserSearchFilters.cpp | 140 -- .../Material/MaterialBrowserSearchFilters.h | 64 - .../Editor/Material/MaterialDialog.qrc | 23 - .../Editor/Material/MaterialHelpers.cpp | 372 --- .../Sandbox/Editor/Material/MaterialHelpers.h | 67 - .../Editor/Material/MaterialImageListCtrl.cpp | 834 ------- .../Editor/Material/MaterialImageListCtrl.h | 164 -- .../Editor/Material/MaterialLibrary.cpp | 151 -- .../Sandbox/Editor/Material/MaterialLibrary.h | 47 - .../Editor/Material/MaterialManager.cpp | 2095 ---------------- .../Sandbox/Editor/Material/MaterialManager.h | 300 --- .../Material/MaterialPreviewModelView.cpp | 77 - .../Material/MaterialPreviewModelView.h | 35 - .../Editor/Material/MaterialPythonFuncs.cpp | 2208 ----------------- .../Editor/Material/MaterialPythonFuncs.h | 34 - .../Editor/Material/PreviewModelView.cpp | 416 ---- .../Editor/Material/PreviewModelView.h | 173 -- .../Editor/Material/images/filestatus_00.png | 3 - .../Editor/Material/images/filestatus_01.png | 3 - .../Editor/Material/images/filestatus_02.png | 3 - .../Editor/Material/images/filestatus_03.png | 3 - .../Editor/Material/images/filestatus_04.png | 3 - .../Editor/Material/images/filestatus_05.png | 3 - .../Editor/Material/images/filestatus_06.png | 3 - .../Editor/Material/images/material_00.png | 3 - .../Editor/Material/images/material_01.png | 3 - .../Editor/Material/images/material_02.png | 3 - .../Editor/Material/images/material_03.png | 3 - .../Editor/Material/images/material_04.png | 3 - .../Editor/Material/images/material_05.png | 3 - .../Editor/Material/images/material_06.png | 3 - .../Editor/Material/images/material_07.png | 3 - .../Material/images/material_browser_00.png | 3 - .../Material/images/material_browser_01.png | 3 - .../Material/images/material_browser_02.png | 3 - .../Material/images/material_browser_03.png | 3 - Code/Sandbox/Editor/MaterialSender.cpp | 60 - Code/Sandbox/Editor/MaterialSender.h | 175 -- Code/Sandbox/Editor/ModelViewport.cpp | 47 +- Code/Sandbox/Editor/ModelViewport.h | 10 - Code/Sandbox/Editor/Objects/AxisGizmo.cpp | 3 - Code/Sandbox/Editor/Objects/AxisGizmo.h | 2 - Code/Sandbox/Editor/Objects/BaseObject.cpp | 82 - Code/Sandbox/Editor/Objects/BaseObject.h | 27 - Code/Sandbox/Editor/Objects/EntityObject.cpp | 33 - Code/Sandbox/Editor/Objects/EntityObject.h | 8 - Code/Sandbox/Editor/Objects/ObjectLoader.cpp | 9 - .../Sandbox/Editor/Objects/SelectionGroup.cpp | 12 +- .../Editor/Objects/StatObjValidator.cpp | 200 -- .../Sandbox/Editor/Objects/StatObjValidator.h | 32 - .../RenderHelpers/AxisHelperExtended.cpp | 213 -- .../Editor/RenderHelpers/AxisHelperExtended.h | 44 - Code/Sandbox/Editor/Resource.h | 3 - Code/Sandbox/Editor/SurfaceInfoPicker.cpp | 535 ---- Code/Sandbox/Editor/SurfaceInfoPicker.h | 220 -- Code/Sandbox/Editor/SurfaceTypeValidator.cpp | 1 - .../TrackView/TrackViewSequenceManager.cpp | 3 - Code/Sandbox/Editor/Util/Variable.h | 2 +- .../Editor/Util/VariablePropertyType.cpp | 2 +- .../Editor/Util/VariablePropertyType.h | 2 +- Code/Sandbox/Editor/Util/VariableTypeInfo.cpp | 4 - Code/Sandbox/Editor/editor_lib_files.cmake | 34 - .../Editor/editor_lib_test_files.cmake | 1 - .../Objects/ComponentEntityObject.cpp | 55 - .../Objects/ComponentEntityObject.h | 5 - .../Animation/UiAnimViewSequenceManager.cpp | 1 - 116 files changed, 9 insertions(+), 15510 deletions(-) delete mode 100755 AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test.py delete mode 100755 AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test_case.py delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserBus.h delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.cpp delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.h delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialThumbnail.cpp delete mode 100644 Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialThumbnail.h delete mode 100644 Code/Sandbox/Editor/Lib/Tests/test_MaterialPythonFuncs.cpp delete mode 100644 Code/Sandbox/Editor/MatEditPreviewDlg.cpp delete mode 100644 Code/Sandbox/Editor/MatEditPreviewDlg.h delete mode 100644 Code/Sandbox/Editor/Material/Material.cpp delete mode 100644 Code/Sandbox/Editor/Material/Material.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialBrowser.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialBrowser.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialBrowser.ui delete mode 100644 Code/Sandbox/Editor/Material/MaterialBrowserFilterModel.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialBrowserFilterModel.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialBrowserSearchFilters.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialBrowserSearchFilters.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialDialog.qrc delete mode 100644 Code/Sandbox/Editor/Material/MaterialHelpers.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialHelpers.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialImageListCtrl.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialImageListCtrl.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialLibrary.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialLibrary.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialManager.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialManager.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialPreviewModelView.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialPreviewModelView.h delete mode 100644 Code/Sandbox/Editor/Material/MaterialPythonFuncs.cpp delete mode 100644 Code/Sandbox/Editor/Material/MaterialPythonFuncs.h delete mode 100644 Code/Sandbox/Editor/Material/PreviewModelView.cpp delete mode 100644 Code/Sandbox/Editor/Material/PreviewModelView.h delete mode 100644 Code/Sandbox/Editor/Material/images/filestatus_00.png delete mode 100644 Code/Sandbox/Editor/Material/images/filestatus_01.png delete mode 100644 Code/Sandbox/Editor/Material/images/filestatus_02.png delete mode 100644 Code/Sandbox/Editor/Material/images/filestatus_03.png delete mode 100644 Code/Sandbox/Editor/Material/images/filestatus_04.png delete mode 100644 Code/Sandbox/Editor/Material/images/filestatus_05.png delete mode 100644 Code/Sandbox/Editor/Material/images/filestatus_06.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_00.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_01.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_02.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_03.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_04.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_05.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_06.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_07.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_browser_00.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_browser_01.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_browser_02.png delete mode 100644 Code/Sandbox/Editor/Material/images/material_browser_03.png delete mode 100644 Code/Sandbox/Editor/MaterialSender.cpp delete mode 100644 Code/Sandbox/Editor/MaterialSender.h delete mode 100644 Code/Sandbox/Editor/Objects/StatObjValidator.cpp delete mode 100644 Code/Sandbox/Editor/Objects/StatObjValidator.h delete mode 100644 Code/Sandbox/Editor/RenderHelpers/AxisHelperExtended.cpp delete mode 100644 Code/Sandbox/Editor/RenderHelpers/AxisHelperExtended.h delete mode 100644 Code/Sandbox/Editor/SurfaceInfoPicker.cpp delete mode 100644 Code/Sandbox/Editor/SurfaceInfoPicker.h diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test.py deleted file mode 100755 index 41ae0608a4..0000000000 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test.py +++ /dev/null @@ -1,75 +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. -""" - -# -# This is a pytest module to test the in-Editor Python API from ViewPane.h -# -import pytest -pytest.importorskip('ly_test_tools') - -import sys -import os -sys.path.append(os.path.dirname(__file__)) -from hydra_utils import launch_test_case - - -@pytest.mark.SUITE_sandbox -@pytest.mark.parametrize('launcher_platform', ['windows_editor']) -@pytest.mark.parametrize('project', ['AutomatedTesting']) -@pytest.mark.parametrize('level', ['auto_test']) -class TestLegacyCryMaterialsCommandsAutomation(object): - - def test_Legacy_CryMaterials(self, request, editor, level, launcher_platform): - - unexpected_lines=[] - expected_lines = [ - # "Material Settings/Shader updated correctly", # Disabled, SPEC-3590 - # "Material Settings/Surface Type updated correctly", # Disabled, SPEC-3590 - "Texture Maps/Diffuse/Tiling/IsTileU updated correctly", - "Texture Maps/Diffuse/Tiling/TileU updated correctly", - "Texture Maps/Diffuse/Rotator/Type updated correctly", - "Texture Maps/Diffuse/Rotator/Amplitude updated correctly", - "Texture Maps/Diffuse/Oscillator/AmplitudeU updated correctly", - "Opacity Settings/Opacity updated correctly", - "Opacity Settings/AlphaTest updated correctly", - "Opacity Settings/Additive updated correctly", - "Lighting Settings/Diffuse Color updated correctly", - "Lighting Settings/Specular Color updated correctly", - "Lighting Settings/Emissive Intensity updated correctly", - "Lighting Settings/Emissive Color updated correctly", - "Advanced/Allow layer activation updated correctly", - "Advanced/2 Sided updated correctly", - "Advanced/No Shadow updated correctly", - "Advanced/Use Scattering updated correctly", - "Advanced/Hide After Breaking updated correctly", - "Advanced/Fog Volume Shading Quality High updated correctly", - "Advanced/Blend Terrain Color updated correctly", - "Advanced/Voxel Coverage updated correctly", - "Advanced/Propagate Opacity Settings updated correctly", - "Advanced/Propagate Lighting Settings updated correctly", - "Advanced/Propagate Advanced Settings updated correctly", - "Advanced/Propagate Texture Maps updated correctly", - "Advanced/Propagate Shader Params updated correctly", - "Advanced/Propagate Shader Generation updated correctly", - "Advanced/Propagate Vertex Deformation updated correctly", - # "Shader Params/Blend Factor updated correctly", # Disabled, SPEC-3590 - # "Shader Params/Indirect bounce color updated correctly", # Disabled, SPEC-3590 - "Vertex Deformation/Type updated correctly", - "Vertex Deformation/Wave Length X updated correctly", - "Vertex Deformation/Wave X/Level updated correctly", - "Vertex Deformation/Wave X/Amplitude updated correctly", - "Vertex Deformation/Wave X/Phase updated correctly", - "Vertex Deformation/Wave X/Frequency updated correctly" - ] - - test_case_file = os.path.join(os.path.dirname(__file__), 'CryMaterialsCommands_test_case.py') - launch_test_case(editor, test_case_file, expected_lines, unexpected_lines) - diff --git a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test_case.py b/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test_case.py deleted file mode 100755 index 913b1ace24..0000000000 --- a/AutomatedTesting/Gem/PythonTests/EditorPythonBindings/CryMaterialsCommands_test_case.py +++ /dev/null @@ -1,116 +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. -""" - -# Tests the legacy Python API for CryMaterials while the Editor is running - -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.legacy.material as material -import azlmbr.math as math - -materialName = 'materials/ter_layer_green' -print(f'Starting CryMaterial test case using material {materialName}') - - -def MaterialPropertyTest(property, value, doReset=True): - try: - # get old value and attempt to set new value - oldValue = material.get_property(materialName, property) - if oldValue == value: - print(f'>>> `{property}` already set to {oldValue}') - return - material.set_property(materialName, property, value) - - # test that the set new value worked - newValue = material.get_property(materialName, property) - if oldValue != newValue: - print(f"{property} updated correctly") - - # reset back to old value - if doReset: - material.set_property(materialName, property, oldValue) - except: - print(f'!!! hit an exception when setting `{property}` to {value}') - - -color = math.Color() -color.r = 255.0 -color.g = 128.0 -color.b = 64.0 -color.a = 0.0 - -# Material Settings -# MaterialPropertyTest("Material Settings/Shader", "Geometrybeam") # Disabled, SPEC-3590 -# MaterialPropertyTest("Material Settings/Surface Type", "grass") # Disabled, SPEC-3590 - -# Texture Maps -MaterialPropertyTest("Texture Maps/Diffuse/Tiling/IsTileU", False) -MaterialPropertyTest("Texture Maps/Diffuse/Tiling/IsTileV", False) -MaterialPropertyTest("Texture Maps/Diffuse/Tiling/TileU", 0.42) -MaterialPropertyTest("Texture Maps/Diffuse/Rotator/Type", 'Oscillated Rotation') -MaterialPropertyTest("Texture Maps/Diffuse/Rotator/Amplitude", 42.0) -MaterialPropertyTest("Texture Maps/Diffuse/Oscillator/TypeU", 'Fixed Moving') -MaterialPropertyTest("Texture Maps/Diffuse/Oscillator/AmplitudeU", 42.0) - -# Vertex Deformation -MaterialPropertyTest("Vertex Deformation/Type", 'Sin Wave') -MaterialPropertyTest("Vertex Deformation/Wave Length X", 42.0) -MaterialPropertyTest("Vertex Deformation/Type", 'Perlin 3D') -MaterialPropertyTest("Vertex Deformation/Noise Scale", math.Vector3(1.1, 2.2, 3.3)) - -# Opacity Settings -MaterialPropertyTest("Opacity Settings/Opacity", 42) -MaterialPropertyTest("Opacity Settings/AlphaTest", 2) -MaterialPropertyTest("Opacity Settings/Additive", True) - -# Lighting Settings -MaterialPropertyTest("Lighting Settings/Diffuse Color", color) -MaterialPropertyTest("Lighting Settings/Specular Color", color) -MaterialPropertyTest("Lighting Settings/Emissive Intensity", 42.0) -MaterialPropertyTest("Lighting Settings/Emissive Color", color) -MaterialPropertyTest("Lighting Settings/Specular Level", 2.0) - -# Advanced -MaterialPropertyTest("Advanced/Allow layer activation", False) -MaterialPropertyTest("Advanced/2 Sided", True) -MaterialPropertyTest("Advanced/No Shadow", True) -MaterialPropertyTest("Advanced/Use Scattering", True) -MaterialPropertyTest("Advanced/Hide After Breaking", True) -MaterialPropertyTest("Advanced/Fog Volume Shading Quality High", True) -MaterialPropertyTest("Advanced/Blend Terrain Color", True) -MaterialPropertyTest("Advanced/Voxel Coverage", 0.42) -# --- MaterialPropertyTest("Advanced/Link to Material", "materials/ter_layer_blue") # Works, but clears on UI refresh -MaterialPropertyTest("Advanced/Propagate Opacity Settings", True) -MaterialPropertyTest("Advanced/Propagate Lighting Settings", True) -MaterialPropertyTest("Advanced/Propagate Advanced Settings", True) -MaterialPropertyTest("Advanced/Propagate Texture Maps", True) -MaterialPropertyTest("Advanced/Propagate Shader Params", True) -MaterialPropertyTest("Advanced/Propagate Shader Generation", True) -MaterialPropertyTest("Advanced/Propagate Vertex Deformation", True) - -# Shader parameters vary with each Shader, just testing a couple of them... -# MaterialPropertyTest("Shader Params/Blend Factor", 7.0, False) # Disabled, SPEC-3590 -# MaterialPropertyTest("Shader Params/Indirect bounce color", color, False) # Disabled, SPEC-3590 - -### These values are reset to False when set. Left them here commented for reference. -# MaterialPropertyTest("Shader Generation Params/Dust & Turbulence", True) -# MaterialPropertyTest("Shader Generation Params/Receive Shadows", True) -# MaterialPropertyTest("Shader Generation Params/UV Vignetting", True) - -# Vertex Deformation -MaterialPropertyTest("Vertex Deformation/Type", "Sin Wave") -MaterialPropertyTest("Vertex Deformation/Wave Length X", 42.0) -MaterialPropertyTest("Vertex Deformation/Wave X/Level", 42.0) -MaterialPropertyTest("Vertex Deformation/Wave X/Amplitude", 42.0) -MaterialPropertyTest("Vertex Deformation/Wave X/Phase", 42.0) -MaterialPropertyTest("Vertex Deformation/Wave X/Frequency", 42.0) - -editor.EditorToolsApplicationRequestBus(bus.Broadcast, 'ExitNoPrompt') diff --git a/Code/CryEngine/CryCommon/IShader.h b/Code/CryEngine/CryCommon/IShader.h index 1e8553ac57..7fcbdefebb 100644 --- a/Code/CryEngine/CryCommon/IShader.h +++ b/Code/CryEngine/CryCommon/IShader.h @@ -52,7 +52,6 @@ struct SShaderItem; class ITexture; struct IMaterial; struct SParam; -class CMaterial; struct SShaderSerializeContext; struct IAnimNode; struct SSkinningData; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp index e7037c8936..373787e7dd 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AzToolsFrameworkModule.cpp @@ -53,7 +53,6 @@ #include #include #include -#include #include namespace AzToolsFramework @@ -93,7 +92,6 @@ namespace AzToolsFramework AzToolsFramework::SliceDependencyBrowserComponent::CreateDescriptor(), AzToolsFramework::Thumbnailer::ThumbnailerComponent::CreateDescriptor(), AzToolsFramework::AssetBrowser::AssetBrowserComponent::CreateDescriptor(), - AzToolsFramework::MaterialBrowser::MaterialBrowserComponent::CreateDescriptor(), AzToolsFramework::EditorInteractionSystemComponent::CreateDescriptor(), AzToolsFramework::Components::EditorComponentAPIComponent::CreateDescriptor(), AzToolsFramework::Components::EditorLevelComponentAPIComponent::CreateDescriptor(), diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserBus.h deleted file mode 100644 index b0d625b6e4..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserBus.h +++ /dev/null @@ -1,43 +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 - -namespace AZ -{ - namespace Data - { - struct AssetId; - } -} - -namespace AzToolsFramework -{ - namespace MaterialBrowser - { - class MaterialBrowserRequests - : public AZ::EBusTraits - { - public: - - // Only a single handler is allowed - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - - virtual bool HasRecord(const AZ::Data::AssetId& assetId) = 0; - virtual bool IsMultiMaterial(const AZ::Data::AssetId& assetId) = 0; - }; - - using MaterialBrowserRequestBus = AZ::EBus; - } // namespace MaterialBrowser -} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.cpp deleted file mode 100644 index f64d4af23d..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.cpp +++ /dev/null @@ -1,65 +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 - -#include -#include -#include -#include -#include -#include - -#include -AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // 4251: 'QBrush::d': class 'QScopedPointer' needs to have dll-interface to be used by clients of class 'QBrush' -#include -AZ_POP_DISABLE_WARNING - -namespace AzToolsFramework -{ - namespace MaterialBrowser - { - MaterialBrowserComponent::MaterialBrowserComponent() - { - } - - void MaterialBrowserComponent::Activate() - { - using namespace Thumbnailer; - using namespace AssetBrowser; - const char* contextName = "MaterialBrowser"; - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterContext, contextName); - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(FolderThumbnailCache), contextName); - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(SourceThumbnailCache), contextName); - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(MaterialThumbnailCache), contextName); - ThumbnailerRequestsBus::Broadcast(&ThumbnailerRequests::RegisterThumbnailProvider, MAKE_TCACHE(SourceControlThumbnailCache), contextName); - } - - void MaterialBrowserComponent::Deactivate() - { - } - - void MaterialBrowserComponent::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serialize = azrtti_cast(context); - if (serialize) - { - serialize->Class(); - } - } - - void MaterialBrowserComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC("ThumbnailerService", 0x65422b97)); - } - } // namespace MaterialBrowser -} // namespace AzToolsFramework - diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.h deleted file mode 100644 index 93a48cf22c..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialBrowserComponent.h +++ /dev/null @@ -1,41 +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 - -namespace AzToolsFramework -{ - namespace MaterialBrowser - { - //! MaterialBrowserComponent allows initialization of MaterialBrowser systems, such as thumbnails - class MaterialBrowserComponent - : public AZ::Component - { - public: - AZ_COMPONENT(MaterialBrowserComponent, "{121F3F3B-2412-490D-9E3E-C205C677F476}") - - MaterialBrowserComponent(); - virtual ~MaterialBrowserComponent() = default; - - ////////////////////////////////////////////////////////////////////////// - // AZ::Component - ////////////////////////////////////////////////////////////////////////// - void Activate() override; - void Deactivate() override; - static void Reflect(AZ::ReflectContext* context); - - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required); - }; - } // namespace MaterialBrowser -} // namespace AzToolsFramework diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialThumbnail.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialThumbnail.cpp deleted file mode 100644 index e04df8937c..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialThumbnail.cpp +++ /dev/null @@ -1,67 +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 - -#include - -namespace AzToolsFramework -{ - namespace MaterialBrowser - { - static constexpr const char* SimpleMaterialIconPath = ":/MaterialBrowser/images/material_04.png"; - static constexpr const char* MultiMaterialIconPath = ":/MaterialBrowser/images/material_06.png"; - - ////////////////////////////////////////////////////////////////////////// - // MaterialThumbnail - ////////////////////////////////////////////////////////////////////////// - MaterialThumbnail::MaterialThumbnail(Thumbnailer::SharedThumbnailKey key) - : Thumbnail(key) - { - auto productKey = azrtti_cast(m_key.data()); - AZ_Assert(productKey, "Incorrect key type, excpected ProductThumbnailKey"); - - bool multiMat = false; - MaterialBrowserRequestBus::BroadcastResult(multiMat, &MaterialBrowserRequests::IsMultiMaterial, productKey->GetAssetId()); - - QString iconPath = multiMat ? MultiMaterialIconPath : SimpleMaterialIconPath; - m_pixmap.load(iconPath); - m_state = m_pixmap.isNull() ? State::Failed : State::Ready; - } - - ////////////////////////////////////////////////////////////////////////// - // MaterialThumbnailCache - ////////////////////////////////////////////////////////////////////////// - MaterialThumbnailCache::MaterialThumbnailCache() - : ThumbnailCache() {} - - MaterialThumbnailCache::~MaterialThumbnailCache() = default; - - int MaterialThumbnailCache::GetPriority() const - { - return 1; - } - - const char* MaterialThumbnailCache::GetProviderName() const - { - return ProviderName; - } - - bool MaterialThumbnailCache::IsSupportedThumbnail(Thumbnailer::SharedThumbnailKey key) const - { - return azrtti_istypeof(key.data()); - } - - } // namespace MaterialBrowser -} // namespace AzToolsFramework - -#include "MaterialBrowser/moc_MaterialThumbnail.cpp" diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialThumbnail.h b/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialThumbnail.h deleted file mode 100644 index 60a2bb11e5..0000000000 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/MaterialBrowser/MaterialThumbnail.h +++ /dev/null @@ -1,86 +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 -#endif - -namespace AzToolsFramework -{ - namespace MaterialBrowser - { - //! Material Browser uses only 2 thumbnails: simple and multimaterial - class MaterialThumbnail - : public Thumbnailer::Thumbnail - { - Q_OBJECT - public: - MaterialThumbnail(Thumbnailer::SharedThumbnailKey key); - }; - - namespace - { - class MaterialKeyHash - { - public: - size_t operator()(const Thumbnailer::SharedThumbnailKey& /*val*/) const - { - return 0; // there is only 2 thumbnails in this cache - } - }; - - class MaterialKeyEqual - { - public: - bool operator()(const Thumbnailer::SharedThumbnailKey& val1, const Thumbnailer::SharedThumbnailKey& val2) const - { - auto productThumbnailKey1 = azrtti_cast(val1.data()); - auto productThumbnailKey2 = azrtti_cast(val2.data()); - if (!productThumbnailKey1 || !productThumbnailKey2) - { - return false; - } - - // check whether keys point to single or multimaterial asset type - bool multiMat1 = false; - bool multiMat2 = false; - MaterialBrowserRequestBus::BroadcastResult(multiMat1, &MaterialBrowserRequests::IsMultiMaterial, productThumbnailKey1->GetAssetId()); - MaterialBrowserRequestBus::BroadcastResult(multiMat2, &MaterialBrowserRequests::IsMultiMaterial, productThumbnailKey2->GetAssetId()); - return multiMat1 == multiMat2; - } - }; - } - - //! MaterialBrowserEntry thumbnails - class MaterialThumbnailCache - : public Thumbnailer::ThumbnailCache - { - public: - MaterialThumbnailCache(); - ~MaterialThumbnailCache() override; - - int GetPriority() const override; - const char* GetProviderName() const override; - - static constexpr const char* ProviderName = "CryMaterial Thumbnails"; - - protected: - bool IsSupportedThumbnail(Thumbnailer::SharedThumbnailKey key) const override; - }; - } // namespace MaterialBrowser -} // namespace AzToolsFramework - - diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake index 4cf121c517..a7fcf2e711 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/aztoolsframework_files.cmake @@ -70,11 +70,6 @@ set(FILES AssetCatalog/PlatformAddressedAssetCatalog.cpp AssetCatalog/PlatformAddressedAssetCatalogManager.h AssetCatalog/PlatformAddressedAssetCatalogManager.cpp - MaterialBrowser/MaterialBrowserBus.h - MaterialBrowser/MaterialBrowserComponent.cpp - MaterialBrowser/MaterialBrowserComponent.h - MaterialBrowser/MaterialThumbnail.cpp - MaterialBrowser/MaterialThumbnail.h Thumbnails/ThumbnailerComponent.cpp Thumbnails/ThumbnailerComponent.h Thumbnails/LoadingThumbnail.cpp diff --git a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp b/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp index 5746e9db2f..9b07f59e6a 100644 --- a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp +++ b/Code/Sandbox/Editor/Controls/PreviewModelCtrl.cpp @@ -365,10 +365,6 @@ bool CPreviewModelCtrl::Render() } _smart_ptr pMaterial; - if (m_pCurrentMaterial) - { - pMaterial = m_pCurrentMaterial->GetMatInfo(); - } if (m_bPrecacheMaterial) { @@ -430,11 +426,6 @@ bool CPreviewModelCtrl::Render() m_pRenderer->EF_ADDDlight(&m_lights[i], passInfo); } - if (m_pCurrentMaterial) - { - m_pCurrentMaterial->DisableHighlightForFrame(); - } - if (m_bShowObject) { RenderObject(pMaterial, passInfo); @@ -778,32 +769,6 @@ void CPreviewModelCtrl::SetRotation(bool bEnable) m_bRotate = bEnable; } -void CPreviewModelCtrl::SetMaterial(CMaterial* pMaterial) -{ - if (pMaterial) - { - if ((pMaterial->GetFlags() & MTL_FLAG_NOPREVIEW)) - { - m_pCurrentMaterial = 0; - if (isVisible()) - { - update(); - } - return; - } - } - m_pCurrentMaterial = pMaterial; - if (isVisible()) - { - update(); - } -} - -CMaterial* CPreviewModelCtrl::GetMaterial() -{ - return m_pCurrentMaterial; -} - void CPreviewModelCtrl::OnEditorNotifyEvent(EEditorNotifyEvent event) { switch (event) diff --git a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h b/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h index 73839612af..6388be9fd5 100644 --- a/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h +++ b/Code/Sandbox/Editor/Controls/PreviewModelCtrl.h @@ -22,8 +22,6 @@ #include -#include - #endif struct IRenderNode; @@ -71,9 +69,6 @@ public: int heightForWidth(int w) const override; bool hasHeightForWidth() const override; - void SetMaterial(CMaterial* pMaterial); - CMaterial* GetMaterial(); - void GetImageOffscreen(CImageEx& image, const QSize& customSize = QSize(0, 0)); void GetCameraTM(Matrix34& cameraTM); @@ -192,7 +187,6 @@ protected: float m_tileY; float m_tileSizeX; float m_tileSizeY; - _smart_ptr m_pCurrentMaterial; CameraChangeCallback m_cameraChangeCallback; void* m_pCameraChangeUserData; diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp index c21aff046e..f0367ffdc1 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyCtrl.cpp @@ -29,7 +29,6 @@ void RegisterReflectedVarHandlers() EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew AnimationPropertyWidgetHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew FileResourceSelectorWidgetHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew ShaderPropertyHandler()); - EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew MaterialPropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew ReverbPresetPropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew SequencePropertyHandler()); EBUS_EVENT(AzToolsFramework::PropertyTypeRegistrationMessages::Bus, RegisterPropertyType, aznew SequenceIdPropertyHandler()); diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp index 3d17e77bb0..75344b2172 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.cpp @@ -27,7 +27,6 @@ // Editor #include "ShadersDialog.h" -#include "Material/MaterialManager.h" #include "SelectLightAnimationDialog.h" #include "SelectSequenceDialog.h" #include "SelectEAXPresetDlg.h" @@ -88,25 +87,6 @@ void ShaderPropertyEditor::onEditClicked() } } -void MaterialPropertyEditor::onEditClicked() -{ -} - -void MaterialPropertyEditor::onButton2Clicked() -{ - // Open material browser dialog. - IDataBaseItem *pItem = GetIEditor()->GetMaterialManager()->GetSelectedItem(); - if (pItem) - { - QString value = pItem->GetName(); - value.replace('\\', '/'); - if (value.length() >= MAX_PATH) - value = value.left(MAX_PATH); - SetValue(value); - } - else - SetValue(QString()); -} void ReverbPresetPropertyEditor::onEditClicked() { diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h index d5ec0045c4..cdbb18ae12 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyGenericCtrl.h @@ -109,16 +109,6 @@ public: void onEditClicked() override; }; -class MaterialPropertyEditor - : public GenericPopupPropertyEditor -{ -public: - MaterialPropertyEditor(QWidget* pParent = nullptr) - : GenericPopupPropertyEditor(pParent, true){} - void onEditClicked() override; - void onButton2Clicked() override; -}; - class ReverbPresetPropertyEditor : public GenericPopupPropertyEditor { @@ -179,7 +169,6 @@ public: #define CONST_AZ_CRC(name, value) AZ::u32(value) using ShaderPropertyHandler = GenericPopupWidgetHandler; -using MaterialPropertyHandler = GenericPopupWidgetHandler; using ReverbPresetPropertyHandler = GenericPopupWidgetHandler; using MissionObjPropertyHandler = GenericPopupWidgetHandler; using SequencePropertyHandler = GenericPopupWidgetHandler; diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyResourceCtrl.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyResourceCtrl.cpp index a66a73eaa4..e698b86341 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyResourceCtrl.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/PropertyResourceCtrl.cpp @@ -111,14 +111,12 @@ private: { case ePropertyTexture: case ePropertyModel: - case ePropertyMaterial: newPath.replace("\\\\", "/"); } switch (m_propertyType) { case ePropertyTexture: case ePropertyModel: - case ePropertyMaterial: case ePropertyFile: if (newPath.size() > MAX_PATH) { diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp index 92610021b9..a188ee117b 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyCtrl.cpp @@ -361,16 +361,6 @@ void ReflectedPropertyControl::CreateItems(XmlNodeRef node, CVarBlockPtr& outBlo textureVar->Set(textureName); } } - else if (!azstricmp(type, "material")) - { - CSmartVariable materialVar; - AddVariable(group, materialVar, child->getTag(), humanReadableName.toUtf8().data(), strDescription.toUtf8().data(), func, pUserData, IVariable::DT_MATERIAL); - const char* materialName; - if (child->getAttr("value", &materialName)) - { - materialVar->Set(materialName); - } - } else if (!azstricmp(type, "color")) { CSmartVariable colorVar; diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp index 055fc26a15..13584d9b82 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedPropertyItem.cpp @@ -269,7 +269,6 @@ void ReflectedPropertyItem::SetVariable(IVariable *var) m_reflectedVarAdapter = new ReflectedVarUserAdapter; break; case ePropertyShader: - case ePropertyMaterial: case ePropertyEquip: case ePropertyReverbPreset: case ePropertyGameToken: @@ -576,7 +575,6 @@ void ReflectedPropertyItem::SetValue(const QString& sValue, bool bRecordUndo, bo case ePropertyTexture: case ePropertyModel: - case ePropertyMaterial: value.replace('\\', '/'); break; } @@ -586,7 +584,6 @@ void ReflectedPropertyItem::SetValue(const QString& sValue, bool bRecordUndo, bo { case ePropertyTexture: case ePropertyModel: - case ePropertyMaterial: case ePropertyFile: if (value.length() >= MAX_PATH) { diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedVar.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedVar.cpp index a805c07a2f..12165d2be8 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedVar.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedVar.cpp @@ -286,8 +286,6 @@ AZ::u32 CReflectedVarGenericProperty::handler() { case ePropertyShader: return AZ_CRC("ePropertyShader", 0xc40932f1); - case ePropertyMaterial: - return AZ_CRC("ePropertyMaterial", 0xf324dffa); case ePropertyEquip: return AZ_CRC("ePropertyEquip", 0x66ffd290); case ePropertyReverbPreset: diff --git a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp index 84a7f8c26f..b2fc07073f 100644 --- a/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp +++ b/Code/Sandbox/Editor/Controls/ReflectedPropertyControl/ReflectedVarWrapper.cpp @@ -455,8 +455,6 @@ void ReflectedVarGenericPropertyAdapter::SyncReflectedVarToIVar(IVariable *pVari { QString value; pVariable->Get(value); - if (m_reflectedVar->m_propertyType == ePropertyMaterial) - value.replace('\\', '/'); m_reflectedVar->m_value = value.toUtf8().data(); } diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index e118104687..44f328b309 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -102,7 +102,6 @@ AZ_POP_DISABLE_WARNING #include "ModelViewport.h" #include "FileTypeUtils.h" #include "PluginManager.h" -#include "Material/MaterialManager.h" #include "IEditorImpl.h" #include "StartupLogoDialog.h" @@ -459,9 +458,6 @@ void CCryEditApp::RegisterActionHandlers() ON_COMMAND(ID_CHANGEMOVESPEED_INCREASE, OnChangemovespeedIncrease) ON_COMMAND(ID_CHANGEMOVESPEED_DECREASE, OnChangemovespeedDecrease) ON_COMMAND(ID_CHANGEMOVESPEED_CHANGESTEP, OnChangemovespeedChangestep) - ON_COMMAND(ID_MATERIAL_ASSIGNCURRENT, OnMaterialAssigncurrent) - ON_COMMAND(ID_MATERIAL_RESETTODEFAULT, OnMaterialResettodefault) - ON_COMMAND(ID_MATERIAL_GETMATERIAL, OnMaterialGetmaterial) ON_COMMAND(ID_FILE_SAVELEVELRESOURCES, OnFileSavelevelresources) ON_COMMAND(ID_CLEAR_REGISTRY, OnClearRegistryData) ON_COMMAND(ID_VALIDATELEVEL, OnValidatelevel) @@ -4180,25 +4176,6 @@ void CCryEditApp::OnSwitchcameraNext() } } -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnMaterialAssigncurrent() -{ - CUndo undo("Assign Material To Selection"); - GetIEditor()->GetMaterialManager()->Command_AssignToSelection(); -} - -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnMaterialResettodefault() -{ - GetIEditor()->GetMaterialManager()->Command_ResetSelection(); -} - -////////////////////////////////////////////////////////////////////////// -void CCryEditApp::OnMaterialGetmaterial() -{ - GetIEditor()->GetMaterialManager()->Command_SelectFromObject(); -} - ////////////////////////////////////////////////////////////////////////// void CCryEditApp::OnOpenAssetBrowserView() { diff --git a/Code/Sandbox/Editor/CryEdit.h b/Code/Sandbox/Editor/CryEdit.h index 8c0c4bd59b..bce7f0c90d 100644 --- a/Code/Sandbox/Editor/CryEdit.h +++ b/Code/Sandbox/Editor/CryEdit.h @@ -417,9 +417,6 @@ private: void OnChangemovespeedIncrease(); void OnChangemovespeedDecrease(); void OnChangemovespeedChangestep(); - void OnMaterialAssigncurrent(); - void OnMaterialResettodefault(); - void OnMaterialGetmaterial(); void OnFileSavelevelresources(); void OnClearRegistryData(); void OnValidatelevel(); diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 41c49ab026..c144d93c46 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -51,7 +51,6 @@ #include "CryEdit.h" #include "ActionManager.h" #include "Include/IObjectManager.h" -#include "Material/MaterialManager.h" #include "ErrorReportDialog.h" #include "SurfaceTypeValidator.h" #include "ShaderCache.h" @@ -357,8 +356,6 @@ void CCryEditDoc::Save(TDocMultiArchive& arrXmlAr) SerializeFogSettings((*arrXmlAr[DMAS_GENERAL])); // Serialize Missions ////////////////////////////////////////////////// SerializeMissions(arrXmlAr, currentMissionName, false); - //! Serialize material manager. - GetIEditor()->GetMaterialManager()->Serialize((*arrXmlAr[DMAS_GENERAL]).root, (*arrXmlAr[DMAS_GENERAL]).bLoading); SerializeShaderCache((*arrXmlAr[DMAS_GENERAL_NAMED_DATA])); SerializeNameSelection((*arrXmlAr[DMAS_GENERAL])); @@ -513,14 +510,6 @@ void CCryEditDoc::Load(TDocMultiArchive& arrXmlAr, const QString& szFilename) ////////////////////////////////////////////////////////////////////////// (*arrXmlAr[DMAS_GENERAL]).root->getAttr("WaterColor", m_waterColor); - ////////////////////////////////////////////////////////////////////////// - // Load materials. - ////////////////////////////////////////////////////////////////////////// - { - CAutoLogTime logtime("Load MaterialManager"); - GetIEditor()->GetMaterialManager()->Serialize((*arrXmlAr[DMAS_GENERAL]).root, (*arrXmlAr[DMAS_GENERAL]).bLoading); - } - ////////////////////////////////////////////////////////////////////////// // Load View Settings ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/DisplaySettings.cpp b/Code/Sandbox/Editor/DisplaySettings.cpp index bd4372ae70..75e5c54ae9 100644 --- a/Code/Sandbox/Editor/DisplaySettings.cpp +++ b/Code/Sandbox/Editor/DisplaySettings.cpp @@ -22,7 +22,6 @@ // Editor #include "Settings.h" -#include "Material/MaterialManager.h" @@ -112,30 +111,6 @@ void CDisplaySettings::SetDebugFlags(int flags) //SetCVarInt( "sys_enable_budgetmonitoring",(m_debugFlags&DBG_BUDGET_MONITORING) ? 4:0 ); //SetCVarInt( "Profile",(m_debugFlags&DBG_FRAMEPROFILE) ? 1:0 ); - - if (CMaterialManager* pMaterialManager = GetIEditor()->GetMaterialManager()) - { - int mask = pMaterialManager->GetHighlightMask(); - if (m_debugFlags & DBG_HIGHLIGHT_BREAKABLE) - { - mask |= eHighlight_Breakable; - } - else - { - mask &= ~eHighlight_Breakable; - } - - if (m_debugFlags & DBG_HIGHLIGHT_MISSING_SURFACE_TYPE) - { - mask |= eHighlight_NoSurfaceType; - } - else - { - mask &= ~eHighlight_NoSurfaceType; - } - - pMaterialManager->SetHighlightMask(mask); - } } ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Sandbox/Editor/EditorToolsApplication.cpp b/Code/Sandbox/Editor/EditorToolsApplication.cpp index 97caaf612a..2e3d70795a 100644 --- a/Code/Sandbox/Editor/EditorToolsApplication.cpp +++ b/Code/Sandbox/Editor/EditorToolsApplication.cpp @@ -21,14 +21,12 @@ #include #include #include -#include // Editor #include "MainWindow.h" #include "CryEdit.h" #include "DisplaySettingsPythonFuncs.h" #include "GameEngine.h" -#include "Material/MaterialPythonFuncs.h" #include "PythonEditorFuncs.h" #include "TrackView/TrackViewPythonFuncs.h" #include "Include/IObjectManager.h" @@ -65,7 +63,6 @@ namespace EditorInternal RegisterComponentDescriptor(AzToolsFramework::DisplaySettingsPythonFuncsHandler::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::MainWindowEditorFuncsHandler::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::ObjectManagerFuncsHandler::CreateDescriptor()); - RegisterComponentDescriptor(AzToolsFramework::MaterialPythonFuncsHandler::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::PythonEditorComponent::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::PythonEditorFuncsHandler::CreateDescriptor()); RegisterComponentDescriptor(AzToolsFramework::DisplaySettingsComponent::CreateDescriptor()); @@ -81,7 +78,6 @@ namespace EditorInternal components.emplace_back(azrtti_typeid()); components.emplace_back(azrtti_typeid()); - components.emplace_back(azrtti_typeid()); // Add new Bus-based Python Bindings components.emplace_back(azrtti_typeid()); diff --git a/Code/Sandbox/Editor/ErrorReport.h b/Code/Sandbox/Editor/ErrorReport.h index f78410be62..b13f8ae120 100644 --- a/Code/Sandbox/Editor/ErrorReport.h +++ b/Code/Sandbox/Editor/ErrorReport.h @@ -19,7 +19,6 @@ #pragma once // forward declarations. -class CMaterial; class CParticleItem; #include "BaseLibraryItem.h" diff --git a/Code/Sandbox/Editor/Export/ExportManager.cpp b/Code/Sandbox/Editor/Export/ExportManager.cpp index b41872595a..638977b191 100644 --- a/Code/Sandbox/Editor/Export/ExportManager.cpp +++ b/Code/Sandbox/Editor/Export/ExportManager.cpp @@ -23,7 +23,6 @@ // Editor #include "Geometry/EdGeometry.h" -#include "Material/Material.h" #include "ViewManager.h" #include "OBJExporter.h" #include "OCMExporter.h" @@ -79,47 +78,6 @@ Export::CMesh::CMesh() } -void Export::CMesh::SetMaterial(CMaterial* pMtl, CBaseObject* pBaseObj) -{ - if (!pMtl) - { - cry_strcpy(material.name, pBaseObj->GetName().toUtf8().data()); - return; - } - - cry_strcpy(material.name, pMtl->GetFullName().toUtf8().data()); - - _smart_ptr matInfo = pMtl->GetMatInfo(); - IRenderShaderResources* pRes = matInfo->GetShaderItem().m_pShaderResources; - if (!pRes) - { - return; - } - - ColorF difColor = pRes->GetColorValue(EFTT_DIFFUSE); - material.diffuse.r = difColor.r; - material.diffuse.g = difColor.g; - material.diffuse.b = difColor.b; - material.diffuse.a = difColor.a; - - ColorF specColor = pRes->GetColorValue(EFTT_SPECULAR); - material.specular.r = specColor.r; - material.specular.g = specColor.g; - material.specular.b = specColor.b; - material.specular.a = specColor.a; - - material.opacity = pRes->GetStrengthValue(EFTT_OPACITY); - material.smoothness = pRes->GetStrengthValue(EFTT_SMOOTHNESS); - - SetTexture(material.mapDiffuse, pRes, EFTT_DIFFUSE); - SetTexture(material.mapSpecular, pRes, EFTT_SPECULAR); - SetTexture(material.mapOpacity, pRes, EFTT_OPACITY); - SetTexture(material.mapNormals, pRes, EFTT_NORMALS); - SetTexture(material.mapDecal, pRes, EFTT_DECAL_OVERLAY); - SetTexture(material.mapDisplacement, pRes, EFTT_HEIGHT); -} - - ////////////////////////////////////////////////////////// // CObject Export::CObject::CObject(const char* pName) @@ -416,18 +374,6 @@ void CExportManager::AddMesh(Export::CObject* pObj, const IIndexedMesh* pIndMesh pObj->m_texCoords.push_back(tc); } - CMaterial* pMtl = 0; - - if (m_pBaseObj) - { - pMtl = m_pBaseObj->GetRenderMaterial(); - } - - if (pMtl) - { - pObj->SetMaterialName(pMtl->GetFullName().toUtf8().data()); - } - if (pIndMesh->GetSubSetCount() && !(pIndMesh->GetSubSetCount() == 1 && pIndMesh->GetSubSet(0).nNumIndices == 0)) { for (int i = 0; i < pIndMesh->GetSubSetCount(); ++i) @@ -447,23 +393,6 @@ void CExportManager::AddMesh(Export::CObject* pObj, const IIndexedMesh* pIndMesh pMesh->m_faces.push_back(face); } - if (pMtl) - { - if (pMtl->IsMultiSubMaterial()) - { - CMaterial* pSubMtl = 0; - if (sms.nMatID < pMtl->GetSubMaterialCount()) - { - pSubMtl = pMtl->GetSubMaterial(sms.nMatID); - } - pMesh->SetMaterial(pSubMtl, m_pBaseObj); - } - else - { - pMesh->SetMaterial(pMtl, m_pBaseObj); - } - } - pObj->m_meshes.push_back(pMesh); } } @@ -497,10 +426,6 @@ void CExportManager::AddMesh(Export::CObject* pObj, const IIndexedMesh* pIndMesh } } - if (m_pBaseObj && pMtl) - { - pMesh->SetMaterial(pMtl, m_pBaseObj); - } pObj->m_meshes.push_back(pMesh); } } diff --git a/Code/Sandbox/Editor/Export/ExportManager.h b/Code/Sandbox/Editor/Export/ExportManager.h index 8904ef08ed..a27e54b085 100644 --- a/Code/Sandbox/Editor/Export/ExportManager.h +++ b/Code/Sandbox/Editor/Export/ExportManager.h @@ -43,8 +43,6 @@ namespace Export virtual int GetFaceCount() const { return m_faces.size(); } virtual const Face* GetFaceBuffer() const { return m_faces.size() ? &m_faces[0] : 0; } - void SetMaterial(CMaterial* pMtl, CBaseObject* pBaseObj); - private: std::vector m_faces; diff --git a/Code/Sandbox/Editor/GameExporter.cpp b/Code/Sandbox/Editor/GameExporter.cpp index 8f0b6f6d0f..64e1fc6514 100644 --- a/Code/Sandbox/Editor/GameExporter.cpp +++ b/Code/Sandbox/Editor/GameExporter.cpp @@ -27,8 +27,6 @@ #include "Mission.h" #include "ShaderCache.h" #include "UsedResources.h" -#include "Material/MaterialManager.h" -#include "Material/MaterialLibrary.h" #include "WaitProgress.h" #include "Util/CryMemFile.h" #include "Objects/ObjectManager.h" @@ -336,11 +334,6 @@ void CGameExporter::ExportLevelData(const QString& path, bool bExportMission) ExportMapInfo(root); - ////////////////////////////////////////////////////////////////////////// - // Export materials. - ExportMaterials(root, path); - ////////////////////////////////////////////////////////////////////////// - CCryEditDoc* pDocument = pEditor->GetDocument(); CMission* pCurrentMission = 0; @@ -508,48 +501,6 @@ void CGameExporter::ExportMapInfo(XmlNodeRef& node) xmlAr.root = node; } -////////////////////////////////////////////////////////////////////////// -void CGameExporter::ExportMaterials(XmlNodeRef& levelDataNode, const QString& path) -{ - ////////////////////////////////////////////////////////////////////////// - // Export materials manager. - CMaterialManager* pManager = GetIEditor()->GetMaterialManager(); - pManager->Export(levelDataNode); - - QString filename = Path::Make(path, MATERIAL_LEVEL_LIBRARY_FILE); - - bool bHaveItems = true; - - int numMtls = 0; - - XmlNodeRef nodeMaterials = XmlHelpers::CreateXmlNode("MaterialsLibrary"); - // Export Materials local level library. - for (int i = 0; i < pManager->GetLibraryCount(); i++) - { - XmlNodeRef nodeLib = nodeMaterials->newChild("Library"); - CMaterialLibrary* pLib = (CMaterialLibrary*)pManager->GetLibrary(i); - if (pLib->GetItemCount() > 0) - { - bHaveItems = false; - // Export this library. - numMtls += pManager->ExportLib(pLib, nodeLib); - } - } - if (!bHaveItems) - { - XmlString xmlData = nodeMaterials->getXML(); - - CCryMemFile file; - file.Write(xmlData.c_str(), xmlData.length()); - m_levelPak.m_pakFile.UpdateFile(filename.toUtf8().data(), file); - } - else - { - m_levelPak.m_pakFile.RemoveFile(filename.toUtf8().data()); - } - m_numExportedMaterials = numMtls; -} - ////////////////////////////////////////////////////////////////////////// void CGameExporter::ExportLevelResourceList(const QString& path) { diff --git a/Code/Sandbox/Editor/GameExporter.h b/Code/Sandbox/Editor/GameExporter.h index 52731a7000..a428046f0a 100644 --- a/Code/Sandbox/Editor/GameExporter.h +++ b/Code/Sandbox/Editor/GameExporter.h @@ -98,7 +98,6 @@ private: void ExportLevelResourceList(const QString& path); void ExportLevelUsedResourceList(const QString& path); void ExportLevelShaderCache(const QString& path); - void ExportMaterials(XmlNodeRef& levelDataNode, const QString& path); void ExportGameData(const QString& path); void ExportFileList(const QString& path, const QString& levelName); diff --git a/Code/Sandbox/Editor/GameResourcesExporter.cpp b/Code/Sandbox/Editor/GameResourcesExporter.cpp index 564396d090..8a6c547dca 100644 --- a/Code/Sandbox/Editor/GameResourcesExporter.cpp +++ b/Code/Sandbox/Editor/GameResourcesExporter.cpp @@ -21,7 +21,6 @@ // Editor #include "UsedResources.h" #include "GameEngine.h" -#include "Material/MaterialManager.h" #include "Include/IObjectManager.h" #include "WaitProgress.h" @@ -51,7 +50,7 @@ void CGameResourcesExporter::ChooseDirectory() void CGameResourcesExporter::GatherAllLoadedResources() { m_files.clear(); - m_files.reserve(100000); // count from GetResourceList, GetFilesFromObjects, GetFilesFromMaterials ... is unknown + m_files.reserve(100000); // count from GetResourceList, GetFilesFromObjects ... is unknown auto pResList = gEnv->pCryPak->GetResourceList(AZ::IO::IArchive::RFOM_Level); { @@ -62,7 +61,6 @@ void CGameResourcesExporter::GatherAllLoadedResources() } GetFilesFromObjects(); - GetFilesFromMaterials(); } ////////////////////////////////////////////////////////////////////////// @@ -158,12 +156,3 @@ void CGameResourcesExporter::GetFilesFromObjects() Append(m_files, rs.files); } - -////////////////////////////////////////////////////////////////////////// -void CGameResourcesExporter::GetFilesFromMaterials() -{ - CUsedResources rs; - GetIEditor()->GetMaterialManager()->GatherUsedResources(rs); - Append(m_files, rs.files); -} - diff --git a/Code/Sandbox/Editor/GameResourcesExporter.h b/Code/Sandbox/Editor/GameResourcesExporter.h index b408cbb42f..8236458cb3 100644 --- a/Code/Sandbox/Editor/GameResourcesExporter.h +++ b/Code/Sandbox/Editor/GameResourcesExporter.h @@ -44,7 +44,6 @@ private: void GetFilesFromObjects(); void GetFilesFromVarBlock(CVarBlock* pVB); void GetFilesFromVariable(IVariable* pVar); - void GetFilesFromMaterials(); }; #endif // CRYINCLUDE_EDITOR_GAMERESOURCESEXPORTER_H diff --git a/Code/Sandbox/Editor/IEditor.h b/Code/Sandbox/Editor/IEditor.h index 838f48573d..c03b99e128 100644 --- a/Code/Sandbox/Editor/IEditor.h +++ b/Code/Sandbox/Editor/IEditor.h @@ -46,9 +46,7 @@ class CGameEngine; struct IIconManager; class CToolBoxManager; class CClassFactory; -class CMaterialManager; class CMusicManager; -class CMaterail; struct IEditorParticleManager; class CEAXPresetManager; class CErrorReport; @@ -544,8 +542,6 @@ struct IEditor virtual CSettingsManager* GetSettingsManager() = 0; //! Get DB manager that own items of specified type. virtual IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType) = 0; - //! Get Manager of Materials. - virtual CMaterialManager* GetMaterialManager() = 0; virtual IBaseLibraryManager* GetMaterialManagerLibrary() = 0; // Vladimir@conffx virtual IEditorMaterialManager* GetIEditorMaterialManager() = 0; // Vladimir@Conffx //! Returns IconManager. diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index 060bf41189..61d24db90c 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -53,7 +53,6 @@ AZ_POP_DISABLE_WARNING #include "KeyboardCustomizationSettings.h" #include "Export/ExportManager.h" #include "LevelIndependentFileMan.h" -#include "Material/MaterialManager.h" #include "TrackView/TrackViewSequenceManager.h" #include "AnimationContext.h" #include "GameEngine.h" @@ -167,7 +166,6 @@ CEditorImpl::CEditorImpl() , m_pAnimationContext(nullptr) , m_pSequenceManager(nullptr) , m_pToolBoxManager(nullptr) - , m_pMaterialManager(nullptr) , m_pMusicManager(nullptr) , m_pErrorReport(nullptr) , m_pLasLoadedLevelErrorReport(nullptr) @@ -222,7 +220,6 @@ CEditorImpl::CEditorImpl() m_pIconManager = new CIconManager; m_pUndoManager = new CUndoManager; m_pToolBoxManager = new CToolBoxManager; - m_pMaterialManager = new CMaterialManager(regCtx); m_pAlembicCompiler = new CAlembicCompiler(); m_pSequenceManager = new CTrackViewSequenceManager; m_pAnimationContext = new CAnimationContext; @@ -342,7 +339,6 @@ CEditorImpl::~CEditorImpl() m_bExiting = true; // Can't save level after this point (while Crash) SAFE_RELEASE(m_pSourceControl); - SAFE_DELETE(m_pMaterialManager) SAFE_DELETE(m_pAlembicCompiler) SAFE_DELETE(m_pIconManager) SAFE_DELETE(m_pViewManager) @@ -412,7 +408,6 @@ void CEditorImpl::SetGameEngine(CGameEngine* ge) m_pObjectManager->LoadClassTemplates("Editor"); m_pObjectManager->RegisterCVars(); - m_pMaterialManager->Set3DEngine(); m_pAnimationContext->Init(); } @@ -1000,13 +995,8 @@ void CEditorImpl::CloseView(const GUID& classId) } } -IDataBaseManager* CEditorImpl::GetDBItemManager(EDataBaseItemType itemType) +IDataBaseManager* CEditorImpl::GetDBItemManager([[maybe_unused]] EDataBaseItemType itemType) { - switch (itemType) - { - case EDB_TYPE_MATERIAL: - return m_pMaterialManager; - } return 0; } @@ -1772,13 +1762,13 @@ SEditorSettings* CEditorImpl::GetEditorSettings() // Vladimir@Conffx IBaseLibraryManager* CEditorImpl::GetMaterialManagerLibrary() { - return m_pMaterialManager; + return nullptr; } // Vladimir@Conffx IEditorMaterialManager* CEditorImpl::GetIEditorMaterialManager() { - return m_pMaterialManager; + return nullptr; } IImageUtil* CEditorImpl::GetImageUtil() diff --git a/Code/Sandbox/Editor/IEditorImpl.h b/Code/Sandbox/Editor/IEditorImpl.h index 3c440dd5fc..d17a94807f 100644 --- a/Code/Sandbox/Editor/IEditorImpl.h +++ b/Code/Sandbox/Editor/IEditorImpl.h @@ -180,7 +180,6 @@ public: bool IsSelectionLocked(); IDataBaseManager* GetDBItemManager(EDataBaseItemType itemType); - CMaterialManager* GetMaterialManager() { return m_pMaterialManager; } CMusicManager* GetMusicManager() { return m_pMusicManager; }; IBackgroundTaskManager* GetBackgroundTaskManager() override; @@ -379,7 +378,6 @@ protected: CAnimationContext* m_pAnimationContext; CTrackViewSequenceManager* m_pSequenceManager; CToolBoxManager* m_pToolBoxManager; - CMaterialManager* m_pMaterialManager; CAlembicCompiler* m_pAlembicCompiler; CMusicManager* m_pMusicManager; CErrorReport* m_pErrorReport; diff --git a/Code/Sandbox/Editor/Include/IErrorReport.h b/Code/Sandbox/Editor/Include/IErrorReport.h index 8afe269324..f25a1163a3 100644 --- a/Code/Sandbox/Editor/Include/IErrorReport.h +++ b/Code/Sandbox/Editor/Include/IErrorReport.h @@ -21,7 +21,6 @@ #include // forward declarations. -class CMaterial; class CParticleItem; class CBaseObject; class CBaseLibraryItem; diff --git a/Code/Sandbox/Editor/LevelInfo.cpp b/Code/Sandbox/Editor/LevelInfo.cpp index 4b8a6d5cac..81441a3797 100644 --- a/Code/Sandbox/Editor/LevelInfo.cpp +++ b/Code/Sandbox/Editor/LevelInfo.cpp @@ -20,7 +20,6 @@ // Editor #include "Util/fastlib.h" -#include "Material/MaterialManager.h" // for CMaterialManager #include @@ -67,7 +66,6 @@ void CLevelInfo::Validate() // Validate level. ValidateObjects(); - ValidateMaterials(); if (m_pReport->GetErrorCount() == 0) { @@ -186,11 +184,3 @@ void CLevelInfo::ValidateObjects() } } } - -////////////////////////////////////////////////////////////////////////// -void CLevelInfo::ValidateMaterials() -{ - // Validate all objects - CBaseObjectsArray objects; - GetIEditor()->GetMaterialManager()->Validate(); -} diff --git a/Code/Sandbox/Editor/LevelInfo.h b/Code/Sandbox/Editor/LevelInfo.h index 0611ad652e..515a21886e 100644 --- a/Code/Sandbox/Editor/LevelInfo.h +++ b/Code/Sandbox/Editor/LevelInfo.h @@ -27,7 +27,6 @@ public: private: void ValidateObjects(); - void ValidateMaterials(); IErrorReport* m_pReport; }; diff --git a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h index 45810da2cf..6659e41122 100644 --- a/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h +++ b/Code/Sandbox/Editor/Lib/Tests/IEditorMock.h @@ -91,7 +91,6 @@ public: MOCK_METHOD0(GetObjectManager, struct IObjectManager* ()); MOCK_METHOD0(GetSettingsManager, CSettingsManager* ()); MOCK_METHOD1(GetDBItemManager, IDataBaseManager* (EDataBaseItemType)); - MOCK_METHOD0(GetMaterialManager, CMaterialManager* ()); MOCK_METHOD0(GetMaterialManagerLibrary, IBaseLibraryManager* ()); MOCK_METHOD0(GetIEditorMaterialManager, IEditorMaterialManager* ()); MOCK_METHOD0(GetIconManager, IIconManager* ()); diff --git a/Code/Sandbox/Editor/Lib/Tests/test_MaterialPythonFuncs.cpp b/Code/Sandbox/Editor/Lib/Tests/test_MaterialPythonFuncs.cpp deleted file mode 100644 index c27608b695..0000000000 --- a/Code/Sandbox/Editor/Lib/Tests/test_MaterialPythonFuncs.cpp +++ /dev/null @@ -1,68 +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 -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace MaterialPythonFuncsUnitTests -{ - - class MaterialPythonBindingsFixture - : public testing::Test - { - public: - AzToolsFramework::ToolsApplication m_app; - - void SetUp() override - { - AzFramework::Application::Descriptor appDesc; - appDesc.m_enableDrilling = false; - - m_app.Start(appDesc); - // Without this, the user settings component would attempt to save on finalize/shutdown. Since the file is - // shared across the whole engine, if multiple tests are run in parallel, the saving could cause a crash - // in the unit tests. - AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); - m_app.RegisterComponentDescriptor(AzToolsFramework::MaterialPythonFuncsHandler::CreateDescriptor()); - } - - void TearDown() override - { - m_app.Stop(); - } - }; - - TEST_F(MaterialPythonBindingsFixture, MaterialEditorCommands_ApiExists) - { - AZ::BehaviorContext* behaviorContext = m_app.GetBehaviorContext(); - ASSERT_TRUE(behaviorContext); - - EXPECT_TRUE(behaviorContext->m_methods.find("create") != behaviorContext->m_methods.end()); - EXPECT_TRUE(behaviorContext->m_methods.find("create_multi") != behaviorContext->m_methods.end()); - EXPECT_TRUE(behaviorContext->m_methods.find("convert_to_multi") != behaviorContext->m_methods.end()); - EXPECT_TRUE(behaviorContext->m_methods.find("duplicate_current") != behaviorContext->m_methods.end()); - EXPECT_TRUE(behaviorContext->m_methods.find("merge_selection") != behaviorContext->m_methods.end()); - EXPECT_TRUE(behaviorContext->m_methods.find("delete_current") != behaviorContext->m_methods.end()); - EXPECT_TRUE(behaviorContext->m_methods.find("get_submaterial") != behaviorContext->m_methods.end()); - EXPECT_TRUE(behaviorContext->m_methods.find("get_property") != behaviorContext->m_methods.end()); - EXPECT_TRUE(behaviorContext->m_methods.find("set_property") != behaviorContext->m_methods.end()); - } -} diff --git a/Code/Sandbox/Editor/MainWindow.cpp b/Code/Sandbox/Editor/MainWindow.cpp index 96f4da7312..44d65af8cd 100644 --- a/Code/Sandbox/Editor/MainWindow.cpp +++ b/Code/Sandbox/Editor/MainWindow.cpp @@ -94,13 +94,11 @@ AZ_POP_DISABLE_WARNING #include "TimeOfDayDialog.h" #include "Dialogs/PythonScriptsDialog.h" -#include "Material/MaterialManager.h" #include "EngineSettingsManager.h" #include "AzAssetBrowser/AzAssetBrowserWindow.h" #include "AssetEditor/AssetEditorWindow.h" #include "GridSettingsDialog.h" -#include "MaterialSender.h" #include "ActionManager.h" // uncomment this to show thumbnail demo widget diff --git a/Code/Sandbox/Editor/MatEditPreviewDlg.cpp b/Code/Sandbox/Editor/MatEditPreviewDlg.cpp deleted file mode 100644 index 4bac9b5e76..0000000000 --- a/Code/Sandbox/Editor/MatEditPreviewDlg.cpp +++ /dev/null @@ -1,149 +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 "MatEditPreviewDlg.h" - -// Qt -#include -#include -#include - -// Editor -#include "Material/MaterialManager.h" -#include "Material/MaterialPreviewModelView.h" - - -///////////////////////////////////////////////////////////////////////////// -// CMatEditPreviewDlg dialog - - -CMatEditPreviewDlg::CMatEditPreviewDlg(QWidget* parent) - : QDialog(parent) -{ - setAttribute(Qt::WA_DeleteOnClose); - setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); - - setWindowTitle(tr("Material Preview")); - - /* create sub controls */ - m_previewCtrl.reset(new MaterialPreviewModelView(this)); - m_menubar.reset(new QMenuBar); - - /* configure layout */ - QVBoxLayout* layout = new QVBoxLayout(); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(m_menubar.data()); - layout->addWidget(m_previewCtrl.data()); - layout->setStretchFactor(m_previewCtrl.data(), 1); - setLayout(layout); - - GetIEditor()->GetMaterialManager()->AddListener(this); - - SetupMenuBar(); - - OnPreviewPlane(); - m_previewCtrl->SetMaterial(GetIEditor()->GetMaterialManager()->GetCurrentMaterial() ? GetIEditor()->GetMaterialManager()->GetCurrentMaterial()->GetMatInfo() : nullptr); - m_previewCtrl->Update(); -} - -CMatEditPreviewDlg::~CMatEditPreviewDlg() -{ - GetIEditor()->GetMaterialManager()->RemoveListener(this); -} - -QSize CMatEditPreviewDlg::sizeHint() const -{ - return QSize(450, 400); -} - -void CMatEditPreviewDlg::showEvent(QShowEvent* e) -{ - QDialog::showEvent(e); - resize(sizeHint()); // Because WindowDecorationWrapper resizes it to the minimum for some reason. -} - -////////////////////////////////////////////////////////////////////////// -void CMatEditPreviewDlg::SetupMenuBar() -{ - QMenu* menu; - QAction* action; - - menu = m_menubar->addMenu(tr("Preview")); - action = menu->addAction(tr("&Plane")); - connect(action, &QAction::triggered, this, &CMatEditPreviewDlg::OnPreviewPlane); - action = menu->addAction(tr("&Sphere")); - connect(action, &QAction::triggered, this, &CMatEditPreviewDlg::OnPreviewSphere); - action = menu->addAction(tr("&Box")); - connect(action, &QAction::triggered, this, &CMatEditPreviewDlg::OnPreviewBox); - action = menu->addAction(tr("&Teapot")); - connect(action, &QAction::triggered, this, &CMatEditPreviewDlg::OnPreviewTeapot); - action = menu->addAction(tr("&Custom")); - connect(action, &QAction::triggered, this, &CMatEditPreviewDlg::OnPreviewCustom); -} - -////////////////////////////////////////////////////////////////////////// -void CMatEditPreviewDlg::OnPreviewSphere() -{ - m_previewCtrl->LoadModelFile("Objects/MtlSphere.cgf"); -} - -////////////////////////////////////////////////////////////////////////// -void CMatEditPreviewDlg::OnPreviewBox() -{ - m_previewCtrl->LoadModelFile("Objects/MtlBox.cgf"); -} - -////////////////////////////////////////////////////////////////////////// -void CMatEditPreviewDlg::OnPreviewTeapot() -{ - m_previewCtrl->LoadModelFile("Objects/MtlTeapot.cgf"); -} - -////////////////////////////////////////////////////////////////////////// -void CMatEditPreviewDlg::OnPreviewPlane() -{ - m_previewCtrl->LoadModelFile("Objects/MtlPlane.cgf"); -} - -////////////////////////////////////////////////////////////////////////// -void CMatEditPreviewDlg::OnPreviewCustom() -{ - const QString fullFileName = - QFileDialog::getOpenFileName(this, tr("Custom Model"), QString(), tr("Objects (*.cgf);;All files (*.*)")); - if (!fullFileName.isNull()) - { - m_previewCtrl->LoadModelFile(fullFileName); - } -} - -///////////////////////////////////////////////////////////////////////////// -// CMatEditPreviewDlg message handlers - -void CMatEditPreviewDlg::OnDataBaseItemEvent([[maybe_unused]] IDataBaseItem* pItem, EDataBaseItemEvent event) -{ - switch (event) - { - case EDB_ITEM_EVENT_SELECTED: - case EDB_ITEM_EVENT_ADD: - case EDB_ITEM_EVENT_CHANGED: - m_previewCtrl->SetMaterial(GetIEditor()->GetMaterialManager()->GetCurrentMaterial() ? GetIEditor()->GetMaterialManager()->GetCurrentMaterial()->GetMatInfo() : nullptr); - break; - case EDB_ITEM_EVENT_DELETE: - m_previewCtrl->SetMaterial(nullptr); - break; - } -} - -#include diff --git a/Code/Sandbox/Editor/MatEditPreviewDlg.h b/Code/Sandbox/Editor/MatEditPreviewDlg.h deleted file mode 100644 index 870d1b901e..0000000000 --- a/Code/Sandbox/Editor/MatEditPreviewDlg.h +++ /dev/null @@ -1,66 +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_MATEDITPREVIEWDLG_H -#define CRYINCLUDE_EDITOR_MATEDITPREVIEWDLG_H - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include - -#include "IDataBaseManager.h" -#endif - -class MaterialPreviewModelView; -class QMenuBar; - -// MatEditPreviewDlg.h : header file -// - -///////////////////////////////////////////////////////////////////////////// -// CMatEditPreviewDlg dialog -class CMatEditPreviewDlg - : public QDialog - , public IDataBaseManagerListener -{ - Q_OBJECT - // Construction -public: - CMatEditPreviewDlg(QWidget* parent); // standard constructor - ~CMatEditPreviewDlg(); - - QSize sizeHint() const override; - void showEvent(QShowEvent*) override; - - //Functions - - virtual void OnDataBaseItemEvent(IDataBaseItem* pItem, EDataBaseItemEvent event); - -protected: - void SetupMenuBar(); - -private slots: - void OnPreviewSphere(); - void OnPreviewPlane(); - void OnPreviewBox(); - void OnPreviewTeapot(); - void OnPreviewCustom(); - -private: - QScopedPointer m_previewCtrl; - QScopedPointer m_menubar; -}; - -#endif // CRYINCLUDE_EDITOR_MATEDITPREVIEWDLG_H diff --git a/Code/Sandbox/Editor/Material/Material.cpp b/Code/Sandbox/Editor/Material/Material.cpp deleted file mode 100644 index 3d642a53dd..0000000000 --- a/Code/Sandbox/Editor/Material/Material.cpp +++ /dev/null @@ -1,1982 +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 "Material.h" - -// Editor -#include "MaterialHelpers.h" -#include "MaterialManager.h" -#include "UsedResources.h" -#include "ErrorReport.h" -#include "Include/ISourceControl.h" -#include "Undo/IUndoObject.h" - - -static SInputShaderResources defaultShaderResource; - -////////////////////////////////////////////////////////////////////////// -CMaterial::CMaterial(const QString& name, int nFlags) - : m_highlightFlags(0) - , m_dccMaterialHash(0) -{ - m_scFileAttributes = SCC_FILE_ATTRIBUTE_NORMAL; - - m_pParent = 0; - - m_shaderResources = defaultShaderResource; - m_shaderResources.m_LMaterial.m_Opacity = 1; - m_shaderResources.m_LMaterial.m_Diffuse.Set(1.0f, 1.0f, 1.0f, 1.0f); - m_shaderResources.m_LMaterial.m_Specular.Set(0.045f, 0.045f, 0.045f, 1.0f); // default 59 spec + div by Gamma exponent -> lin - m_shaderResources.m_LMaterial.m_Smoothness = 10.0f; - - m_mtlFlags = nFlags; - ZeroStruct(m_shaderItem); - - // Default shader. - m_shaderName = "Illum"; - m_nShaderGenMask = 0; - - m_name = name; - m_bRegetPublicParams = true; - m_bKeepPublicParamsValues = false; - m_bIgnoreNotifyChange = false; - m_bDummyMaterial = false; - - m_pMatInfo = NULL; - m_propagationFlags = 0; - - m_allowLayerActivation = true; -} - -CMaterial::CMaterial(const CMaterial& rhs) - : m_scFileAttributes{rhs.m_scFileAttributes} - , m_pParent{nullptr} - , m_shaderResources{rhs.m_shaderResources} - , m_mtlFlags{rhs.m_mtlFlags} - , m_shaderName{rhs.m_shaderName} - , m_nShaderGenMask{rhs.m_nShaderGenMask} - , m_bRegetPublicParams{rhs.m_bRegetPublicParams} - , m_bKeepPublicParamsValues{rhs.m_bKeepPublicParamsValues} - , m_bDummyMaterial{rhs.m_bDummyMaterial} - , m_pMatInfo{nullptr} - , m_propagationFlags{rhs.m_propagationFlags} - , m_allowLayerActivation{rhs.m_allowLayerActivation} - , m_dccMaterialHash(rhs.m_dccMaterialHash) -{ - ZeroStruct(m_shaderItem); - m_name = rhs.m_name; -} - -////////////////////////////////////////////////////////////////////////// -CMaterial::~CMaterial() -{ - if (IsModified()) - { - Save(false); - } - - // Release used shader. - SAFE_RELEASE(m_shaderItem.m_pShader); - SAFE_RELEASE(m_shaderItem.m_pShaderResources); - - if (m_pMatInfo) - { - m_pMatInfo->SetUserData(0); - m_pMatInfo = 0; - } - - if (!m_subMaterials.empty()) - { - for (int i = 0; i < m_subMaterials.size(); i++) - { - if (m_subMaterials[i]) - { - m_subMaterials[i]->m_pParent = NULL; - } - } - - m_subMaterials.clear(); - } - - if (!IsPureChild() && !(GetFlags() & MTL_FLAG_UIMATERIAL)) - { - // Unregister this material from manager. - // Don't use here local variable m_pManager. Manager can be destroyed. - if (GetIEditor()->GetMaterialManager()) - { - GetIEditor()->GetMaterialManager()->DeleteItem(this); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetName(const QString& name) -{ - if (name != m_name) - { - QString oldName = GetFullName(); - m_name = name; - - if (!IsPureChild()) - { - if (GetIEditor()->GetMaterialManager()) - { - GetIEditor()->GetMaterialManager()->OnRenameItem(this, oldName); - } - - if (m_pMatInfo) - { - GetIEditor()->Get3DEngine()->GetMaterialManager()->RenameMaterial(m_pMatInfo, GetName().toUtf8().data()); - } - } - else - { - if (m_pMatInfo) - { - m_pMatInfo->SetName(m_name.toUtf8().data()); - } - } - - NotifyChanged(); - } - - if (m_shaderItem.m_pShaderResources) - { - // Only for correct warning message purposes. - m_shaderItem.m_pShaderResources->SetMaterialName(m_name.toUtf8().data()); - } -} - - -////////////////////////////////////////////////////////////////////////// -QString CMaterial::GetFilename() const -{ - return GetIEditor()->GetMaterialManager()->MaterialToFilename(IsPureChild() && m_pParent ? m_pParent->m_name : m_name); -} - -////////////////////////////////////////////////////////////////////////// -int CMaterial::GetTextureFilenames(QStringList& outFilenames) const -{ - for (auto& iter : m_shaderResources.m_TexturesResourcesMap ) - { - const SEfResTexture* pTexture = (const SEfResTexture*) &(iter.second); - QString name = QtUtil::ToQString(pTexture->m_Name); - if (name.isEmpty()) - { - AZ_Warning("Shaders System", false, "Error: CMaterial::GetTextureFilenames - texture slot name does not exist for slot %d", iter.first ); - continue; - } - - // Collect image filenames - if (IResourceCompilerHelper::IsSourceImageFormatSupported(name.toUtf8().data())) - { - stl::push_back_unique(outFilenames, Path::GamePathToFullPath(name)); - } - - // collect source files used in DCC tools - QString dccFilename; - if (CFileUtil::CalculateDccFilename(name, dccFilename)) - { - stl::push_back_unique(outFilenames, Path::GamePathToFullPath(dccFilename)); - } - } - - if (IsMultiSubMaterial()) - { - for (int i = 0; i < GetSubMaterialCount(); ++i) - { - CMaterial* pSubMtl = GetSubMaterial(i); - if (pSubMtl) - { - pSubMtl->GetTextureFilenames(outFilenames); - } - } - } - - return outFilenames.size(); -} - -////////////////////////////////////////////////////////////////////////// -int CMaterial::GetAnyTextureFilenames(QStringList& outFilenames) const -{ - for ( auto& iter : m_shaderResources.m_TexturesResourcesMap ) - { - QString name = QtUtil::ToQString( iter.second.m_Name); - if (name.isEmpty()) - { - continue; - } - - // Collect any filenames - stl::push_back_unique(outFilenames, Path::GamePathToFullPath(name)); - } - - if (IsMultiSubMaterial()) - { - for (int i = 0; i < GetSubMaterialCount(); ++i) - { - CMaterial* pSubMtl = GetSubMaterial(i); - if (pSubMtl) - { - pSubMtl->GetAnyTextureFilenames(outFilenames); - } - } - } - - return outFilenames.size(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::UpdateFileAttributes(bool useSourceControl) -{ - QString filename = GetFilename(); - if (filename.isEmpty()) - { - return; - } - - m_scFileAttributes = CFileUtil::GetAttributes(filename.toUtf8().data(), useSourceControl); -} - -////////////////////////////////////////////////////////////////////////// -uint32 CMaterial::GetFileAttributes() -{ - if (IsDummy()) - { - return m_scFileAttributes; - } - - if (IsPureChild() && m_pParent) - { - return m_pParent->GetFileAttributes(); - } - - UpdateFileAttributes(); - return m_scFileAttributes; -}; - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetShaderName(const QString& shaderName) -{ - if (m_shaderName != shaderName) - { - m_bRegetPublicParams = true; - m_bKeepPublicParamsValues = false; - - RecordUndo("Change Shader"); - } - - m_shaderName = shaderName; - if (QString::compare(m_shaderName, "nodraw", Qt::CaseInsensitive) == 0) - { - m_mtlFlags |= MTL_FLAG_NODRAW; - } - else - { - m_mtlFlags &= ~MTL_FLAG_NODRAW; - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::CheckSpecialConditions() -{ - if (QString::compare(m_shaderName, "nodraw", Qt::CaseInsensitive) == 0) - { - m_mtlFlags |= MTL_FLAG_NODRAW; - } - else - { - m_mtlFlags &= ~MTL_FLAG_NODRAW; - } - - // If environment texture name have auto/nearest cubemap in it, force material to use auto cube-map for it. - SEfResTexture* pTextureRes = m_shaderResources.GetTextureResource(EFTT_ENV); - if (!pTextureRes) - return; - - if (!pTextureRes->m_Name.empty()) - { - const char* sAtPos; - sAtPos = strstr(pTextureRes->m_Name.c_str(), "auto_2d"); - if (sAtPos) - { - pTextureRes->m_Sampler.m_eTexType = eTT_Auto2D; // Force Auto-2D - } - sAtPos = strstr(pTextureRes->m_Name.c_str(), "nearest_cubemap"); - if (sAtPos) - { - pTextureRes->m_Sampler.m_eTexType = eTT_NearestCube; // Force Nearest Cubemap - } - } - - // Force auto 2D map if user sets texture type - if (pTextureRes->m_Sampler.m_eTexType == eTT_Auto2D) - { - pTextureRes->m_Name = "auto_2d"; - } - - // Force nearest cube map if user sets texture type - if (pTextureRes->m_Sampler.m_eTexType == eTT_NearestCube) - { - pTextureRes->m_Name = "nearest_cubemap"; - m_mtlFlags |= MTL_FLAG_REQUIRE_NEAREST_CUBEMAP; - } -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterial::LoadShader() -{ - if (m_bDummyMaterial) - { - return true; - } - - CheckSpecialConditions(); - - GetIEditor()->GetErrorReport()->SetCurrentValidatorItem(this); - - m_shaderResources.m_ResFlags = m_mtlFlags; - - QString sShader = m_shaderName; - if (sShader.isEmpty()) - { - sShader = ""; - } - - QByteArray n = m_name.toUtf8(); - m_shaderResources.m_szMaterialName = n.data(); - SShaderItem newShaderItem = GetIEditor()->GetRenderer()->EF_LoadShaderItem(sShader.toUtf8().data(), false, 0, &m_shaderResources, m_nShaderGenMask); - - // Shader not found - if (newShaderItem.m_pShader && (newShaderItem.m_pShader->GetFlags() & EF_NOTFOUND) != 0) - { - CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_WARNING, "Failed to load shader \"%s\" in material \"%s\"", newShaderItem.m_pShader->GetName(), m_name.toUtf8().constData()); - } - - // Release previously used shader (Must be After new shader is loaded, for speed). - SAFE_RELEASE(m_shaderItem.m_pShader); - SAFE_RELEASE(m_shaderItem.m_pShaderResources); - - m_shaderItem = newShaderItem; - if (!m_shaderItem.m_pShader) - { - CErrorRecord err; - - err.error = QObject::tr("Failed to Load Shader %1").arg(m_shaderName); - err.pItem = this; - - GetIEditor()->GetErrorReport()->ReportError(err); - GetIEditor()->GetErrorReport()->SetCurrentValidatorItem(NULL); - return false; - } - - IShader* pShader = m_shaderItem.m_pShader; - m_nShaderGenMask = pShader->GetGenerationMask(); - if (pShader->GetFlags() & EF_NOPREVIEW) - { - m_mtlFlags |= MTL_FLAG_NOPREVIEW; - } - else - { - m_mtlFlags &= ~MTL_FLAG_NOPREVIEW; - } - - ////////////////////////////////////////////////////////////////////////// - // Reget shader parms. - ////////////////////////////////////////////////////////////////////////// - if (m_bRegetPublicParams) - { - if (m_bKeepPublicParamsValues) - { - m_bKeepPublicParamsValues = false; - m_publicVarsCache = XmlHelpers::CreateXmlNode("PublicParams"); - - MaterialHelpers::SetXmlFromShaderParams(m_shaderResources, m_publicVarsCache); - } - - m_shaderResources.m_ShaderParams = pShader->GetPublicParams(); - m_bRegetPublicParams = false; - } - - ////////////////////////////////////////////////////////////////////////// - // If we have XML node with public parameters loaded, apply it on shader parms. - ////////////////////////////////////////////////////////////////////////// - if (m_publicVarsCache) - { - MaterialHelpers::SetShaderParamsFromXml(m_shaderResources, m_publicVarsCache); - GetIEditor()->GetMaterialManager()->OnUpdateProperties(this, false); - m_publicVarsCache = 0; - } - - ////////////////////////////////////////////////////////////////////////// - // Set shader parms. - if (m_shaderItem.m_pShaderResources) - { - m_shaderItem.m_pShaderResources->SetShaderParams(&m_shaderResources, m_shaderItem.m_pShader); - } - ////////////////////////////////////////////////////////////////////////// - - gEnv->pRenderer->UpdateShaderItem(&m_shaderItem, nullptr); - - ////////////////////////////////////////////////////////////////////////// - // Set Shader Params for material layers - ////////////////////////////////////////////////////////////////////////// - if (m_pMatInfo) - { - UpdateMatInfo(); - } - - GetIEditor()->GetMaterialManager()->OnLoadShader(this); - GetIEditor()->GetErrorReport()->SetCurrentValidatorItem(NULL); - - return true; -} - -bool CMaterial::LoadMaterialLayers() -{ - if (!m_pMatInfo) - { - return false; - } - - if (m_shaderItem.m_pShader && m_shaderItem.m_pShaderResources) - { - // mask generation for base material shader - uint32 nMaskGenBase = m_shaderItem.m_pShader->GetGenerationMask(); - SShaderGen* pShaderGenBase = m_shaderItem.m_pShader->GetGenerationParams(); - - for (uint32 l(0); l < MTL_LAYER_MAX_SLOTS; ++l) - { - SMaterialLayerResources* pCurrLayer = &m_pMtlLayerResources[l]; - pCurrLayer->m_nFlags |= MTL_FLAG_NODRAW; - if (!pCurrLayer->m_shaderName.isEmpty()) - { - if (QString::compare(pCurrLayer->m_shaderName, "nodraw", Qt::CaseInsensitive) == 0) - { - // no shader = skip layer - pCurrLayer->m_shaderName.clear(); - continue; - } - - IShader* pNewShader = GetIEditor()->GetRenderer()->EF_LoadShader(pCurrLayer->m_shaderName.toUtf8().data(), 0); - - // Check if shader loaded - if (!pNewShader || (pNewShader->GetFlags() & EF_NOTFOUND) != 0) - { - CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_WARNING, "Failed to load material layer shader \"%s\" in material \"%s\"", pCurrLayer->m_shaderName.toUtf8().constData(), m_pMatInfo->GetName()); - if (!pNewShader) - { - continue; - } - } - - if (!pCurrLayer->m_pMatLayer) - { - pCurrLayer->m_pMatLayer = m_pMatInfo->CreateLayer(); - } - - // mask generation for base material shader - uint64 nMaskGenLayer = 0; - SShaderGen* pShaderGenLayer = pNewShader->GetGenerationParams(); - if (pShaderGenBase && pShaderGenLayer) - { - for (int nLayerBit(0); nLayerBit < pShaderGenLayer->m_BitMask.size(); ++nLayerBit) - { - SShaderGenBit* pLayerBit = pShaderGenLayer->m_BitMask[nLayerBit]; - - for (int nBaseBit(0); nBaseBit < pShaderGenBase->m_BitMask.size(); ++nBaseBit) - { - SShaderGenBit* pBaseBit = pShaderGenBase->m_BitMask[nBaseBit]; - - // Need to check if flag name is common to both shaders (since flags values can be different), if so activate it on this layer - if (nMaskGenBase & pBaseBit->m_Mask) - { - if (!pLayerBit->m_ParamName.empty() && !pBaseBit->m_ParamName.empty()) - { - if (pLayerBit->m_ParamName == pBaseBit->m_ParamName) - { - nMaskGenLayer |= pLayerBit->m_Mask; - break; - } - } - } - } - } - } - - // Reload with proper flags - SShaderItem newShaderItem = GetIEditor()->GetRenderer()->EF_LoadShaderItem(pCurrLayer->m_shaderName.toUtf8().data(), false, 0, &pCurrLayer->m_shaderResources, nMaskGenLayer); - if (!newShaderItem.m_pShader || (newShaderItem.m_pShader->GetFlags() & EF_NOTFOUND) != 0) - { - CryWarning(VALIDATOR_MODULE_EDITOR, VALIDATOR_WARNING, "Failed to load material layer shader \"%s\" in material \"%s\"", pCurrLayer->m_shaderName.toUtf8().data(), m_pMatInfo->GetName()); - if (!newShaderItem.m_pShader) - { - continue; - } - } - - SShaderItem& pCurrShaderItem = pCurrLayer->m_pMatLayer->GetShaderItem(); - - if (newShaderItem.m_pShader) - { - newShaderItem.m_pShader->AddRef(); - } - - // Release previously used shader (Must be After new shader is loaded, for speed). - SAFE_RELEASE(pCurrShaderItem.m_pShader); - SAFE_RELEASE(pCurrShaderItem.m_pShaderResources); - SAFE_RELEASE(newShaderItem.m_pShaderResources); - - pCurrShaderItem.m_pShader = newShaderItem.m_pShader; - // Copy resources from base material - pCurrShaderItem.m_pShaderResources = m_shaderItem.m_pShaderResources->Clone(); - pCurrShaderItem.m_nTechnique = newShaderItem.m_nTechnique; - pCurrShaderItem.m_nPreprocessFlags = newShaderItem.m_nPreprocessFlags; - - // set default params - if (pCurrLayer->m_bRegetPublicParams) - { - pCurrLayer->m_shaderResources.m_ShaderParams = pCurrShaderItem.m_pShader->GetPublicParams(); - } - - pCurrLayer->m_bRegetPublicParams = false; - - if (pCurrLayer->m_publicVarsCache) - { - MaterialHelpers::SetShaderParamsFromXml(pCurrLayer->m_shaderResources, pCurrLayer->m_publicVarsCache); - pCurrLayer->m_publicVarsCache = 0; - } - - if (pCurrShaderItem.m_pShaderResources) - { - pCurrShaderItem.m_pShaderResources->SetShaderParams(&pCurrLayer->m_shaderResources, pCurrShaderItem.m_pShader); - } - - // Activate layer - pCurrLayer->m_nFlags &= ~MTL_FLAG_NODRAW; - } - } - - return true; - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// - -void CMaterial::UpdateMaterialLayers() -{ - if (m_pMatInfo && m_shaderItem.m_pShaderResources) - { - m_pMatInfo->SetLayerCount(MTL_LAYER_MAX_SLOTS); - - uint8 nMaterialLayerFlags = 0; - - for (int l(0); l < MTL_LAYER_MAX_SLOTS; ++l) - { - SMaterialLayerResources* pCurrLayer = &m_pMtlLayerResources[l]; - if (pCurrLayer && !pCurrLayer->m_shaderName.isEmpty() && pCurrLayer->m_pMatLayer) - { - pCurrLayer->m_pMatLayer->SetFlags(pCurrLayer->m_nFlags); - m_pMatInfo->SetLayer(l, pCurrLayer->m_pMatLayer); - - if ((pCurrLayer->m_nFlags & MTL_LAYER_USAGE_NODRAW)) - { - if (!QString::compare(pCurrLayer->m_shaderName, "frozenlayerwip", Qt::CaseInsensitive)) - { - nMaterialLayerFlags |= MTL_LAYER_FROZEN; - } - } - } - } - - if (m_shaderItem.m_pShaderResources) - { - m_shaderItem.m_pShaderResources->SetMtlLayerNoDrawFlags(nMaterialLayerFlags); - } - } -} - -void CMaterial::UpdateMatInfo() -{ - if (m_pMatInfo) - { - // Mark material invalid. - m_pMatInfo->SetFlags(m_mtlFlags); - m_pMatInfo->SetShaderItem(m_shaderItem); - m_pMatInfo->SetShaderName(m_shaderName.toUtf8().constData()); - m_pMatInfo->SetSurfaceType(m_surfaceType.toUtf8().constData()); - - LoadMaterialLayers(); - UpdateMaterialLayers(); - - m_pMatInfo->SetMaterialLinkName(m_linkedMaterial.toUtf8().data()); - - if (IsMultiSubMaterial()) - { - m_pMatInfo->SetSubMtlCount(m_subMaterials.size()); - for (unsigned int i = 0; i < m_subMaterials.size(); i++) - { - if (m_subMaterials[i]) - { - m_pMatInfo->SetSubMtl(i, m_subMaterials[i]->GetMatInfo()); - } - else - { - m_pMatInfo->SetSubMtl(i, NULL); - } - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -CVarBlock* CMaterial::GetPublicVars(SInputShaderResources& pShaderResources) -{ - return MaterialHelpers::GetPublicVars(pShaderResources); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetShaderParamPublicScript() -{ - IShader* pShader = m_shaderItem.m_pShader; - - if (!pShader) - { - return; - } - - if (m_shaderResources.m_ShaderParams.size() == 0 || pShader->GetPublicParams().size() == 0) - { - return; - } - - // We want to inspect public shader param and paste the m_script into our shader resource param script - for (int i = 0; i < m_shaderResources.m_ShaderParams.size(); ++i) - { - SShaderParam ¤tShaderParam = m_shaderResources.m_ShaderParams.at(i); - for (int j = 0; j < pShader->GetPublicParams().size(); ++j) - { - const SShaderParam &publicShaderParam = pShader->GetPublicParams().at(j); - if ((currentShaderParam.m_Name == publicShaderParam.m_Name) && (currentShaderParam.m_Type == publicShaderParam.m_Type)) - { - currentShaderParam.m_Script = publicShaderParam.m_Script; - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetPublicVars(CVarBlock* pPublicVars, CMaterial* pMtl) -{ - if (!pMtl->GetShaderResources().m_ShaderParams.empty()) - { - RecordUndo("Set Public Vars"); - } - - MaterialHelpers::SetPublicVars(pPublicVars, pMtl->GetShaderResources(), pMtl->GetShaderItem().m_pShaderResources, pMtl->GetShaderItem().m_pShader); - - GetIEditor()->GetMaterialManager()->OnUpdateProperties(this, false); -} - -////////////////////////////////////////////////////////////////////////// -CVarBlock* CMaterial::GetShaderGenParamsVars() -{ - return MaterialHelpers::GetShaderGenParamsVars(GetShaderItem().m_pShader, m_nShaderGenMask); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetShaderGenParamsVars(CVarBlock* pBlock) -{ - RecordUndo("Change Shader GenMask"); - - uint64 nGenMask = MaterialHelpers::SetShaderGenParamsVars(GetShaderItem().m_pShader, pBlock); - if (m_nShaderGenMask != nGenMask) - { - m_bRegetPublicParams = true; - m_bKeepPublicParamsValues = true; - m_nShaderGenMask = nGenMask; - } -} - -////////////////////////////////////////////////////////////////////////// -unsigned int CMaterial::GetTexmapUsageMask() const -{ - int mask = 0; - if (m_shaderItem.m_pShader) - { - IShader* pTempl = m_shaderItem.m_pShader; - if (pTempl) - { - mask = pTempl->GetUsedTextureTypes(); - } - } - return mask; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::Update() -{ - // Reload shader item with new resources and shader. - LoadShader(); - - // Mark library as modified. - SetModified(); - - GetIEditor()->SetModifiedFlag(); - - // When modifying pure child, mark his parent as modified. - if (IsPureChild() && m_pParent) - { - m_pParent->SetModified(); - } -} - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -void CMaterial::Serialize(SerializeContext& ctx) -{ - //CBaseLibraryItem::Serialize( ctx ); - - XmlNodeRef node = ctx.node; - if (ctx.bLoading) - { - m_bIgnoreNotifyChange = true; - m_bRegetPublicParams = true; - - SInputShaderResources& sr = m_shaderResources; - m_shaderResources = defaultShaderResource; - - // Loading - int flags = m_mtlFlags; - if (node->getAttr("MtlFlags", flags)) - { - m_mtlFlags &= ~(MTL_FLAGS_SAVE_MASK); - m_mtlFlags |= (flags & (MTL_FLAGS_SAVE_MASK)); - } - - uint32 dccMaterialHash = 0; - node->getAttr("DccMaterialHash", dccMaterialHash); - SetDccMaterialHash(dccMaterialHash); - - if (!IsMultiSubMaterial()) - { - node->getAttr("Shader", m_shaderName); - node->getAttr("GenMask", m_nShaderGenMask); - - if (!(m_mtlFlags & MTL_64BIT_SHADERGENMASK)) - { - uint32 nShaderGenMask = 0; - node->getAttr("GenMask", nShaderGenMask); - m_nShaderGenMask = nShaderGenMask; - } - else - { - node->getAttr("GenMask", m_nShaderGenMask); - } - - // Remap flags if needed - if (!(m_mtlFlags & MTL_64BIT_SHADERGENMASK)) - { - m_nShaderGenMask = GetIEditor()->GetRenderer()->EF_GetRemapedShaderMaskGen(m_shaderName.toUtf8().data(), m_nShaderGenMask); - m_mtlFlags |= MTL_64BIT_SHADERGENMASK; - } - - if (node->getAttr("StringGenMask", m_pszShaderGenMask)) - { - m_nShaderGenMask = GetIEditor()->GetRenderer()->EF_GetShaderGlobalMaskGenFromString(m_shaderName.toUtf8().data(), m_pszShaderGenMask.toUtf8().data(), m_nShaderGenMask); // get common mask gen - } - else - { - // version doens't has string gen mask yet ? Remap flags if needed - m_nShaderGenMask = GetIEditor()->GetRenderer()->EF_GetRemapedShaderMaskGen(m_shaderName.toUtf8().data(), m_nShaderGenMask, ((m_mtlFlags & MTL_64BIT_SHADERGENMASK) != 0)); - } - m_mtlFlags |= MTL_64BIT_SHADERGENMASK; - - node->getAttr("SurfaceType", m_surfaceType); - node->getAttr("LayerAct", m_allowLayerActivation); - - MaterialHelpers::SetLightingFromXml(sr, node); - - MaterialHelpers::SetTexturesFromXml(sr, node); - MaterialHelpers::MigrateXmlLegacyData(sr, node); - } - - ////////////////////////////////////////////////////////////////////////// - // Check if we have a link name and if any propagation settings were - // present - ////////////////////////////////////////////////////////////////////////// - XmlNodeRef pLinkName = node->findChild("MaterialLinkName"); - if (pLinkName) - { - m_linkedMaterial = pLinkName->getAttr("name"); - } - else - { - m_linkedMaterial = QString(); - } - - XmlNodeRef pPropagationFlags = node->findChild("MaterialPropagationFlags"); - if (pPropagationFlags) - { - pPropagationFlags->getAttr("flags", m_propagationFlags); - } - else - { - m_propagationFlags = 0; - } - - ////////////////////////////////////////////////////////////////////////// - // Check if we have vertex deform. - ////////////////////////////////////////////////////////////////////////// - MaterialHelpers::SetVertexDeformFromXml(m_shaderResources, node); - - // Serialize sub materials. - - const auto ResizeSubMaterials = [this](size_t count) - { - for (size_t i = count; i < m_subMaterials.size(); ++i) - { - if (auto& pSubMtl = m_subMaterials[i]) - { - pSubMtl->m_pParent = nullptr; - } - } - m_subMaterials.resize(count); - }; - - XmlNodeRef childsNode = node->findChild("SubMaterials"); - if (childsNode && !ctx.bIgnoreChilds) - { - QString name; - int nSubMtls = childsNode->getChildCount(); - ResizeSubMaterials(nSubMtls); - for (int i = 0; i < nSubMtls; i++) - { - auto& pSubMtl = m_subMaterials[i]; - XmlNodeRef mtlNode = childsNode->getChild(i); - if (mtlNode->isTag("Material")) - { - mtlNode->getAttr("Name", name); - if (pSubMtl && pSubMtl->IsPureChild()) - { - pSubMtl->SetName(name); - } - else - { - if (pSubMtl) - { - pSubMtl->m_pParent = nullptr; - } - - pSubMtl = new CMaterial(name, MTL_FLAG_PURE_CHILD); - pSubMtl->m_pParent = this; - } - - SerializeContext childCtx(ctx); - childCtx.node = mtlNode; - pSubMtl->Serialize(childCtx); - - pSubMtl->m_shaderResources.m_SortPrio = nSubMtls - i - 1; - } - else - { - if (pSubMtl) - { - pSubMtl->m_pParent = nullptr; - pSubMtl = nullptr; - } - - if (mtlNode->getAttr("Name", name)) - { - CMaterial* pMtl = GetIEditor()->GetMaterialManager()->LoadMaterial(name); - if (pMtl && !pMtl->IsMultiSubMaterial()) - { - pSubMtl = pMtl; - } - } - } - } - - m_subMaterials.erase(std::remove(m_subMaterials.begin(), m_subMaterials.end(), nullptr), m_subMaterials.end()); - } - else - { - ResizeSubMaterials(0); - } - - UpdateMatInfo(); - - ////////////////////////////////////////////////////////////////////////// - // Load public parameters. - ////////////////////////////////////////////////////////////////////////// - m_publicVarsCache = node->findChild("PublicParams"); - - ////////////////////////////////////////////////////////////////////////// - // Load material layers data - ////////////////////////////////////////////////////////////////////////// - XmlNodeRef mtlLayersNode = node->findChild("MaterialLayers"); - if (mtlLayersNode) - { - int nChildCount = min((int) MTL_LAYER_MAX_SLOTS, (int) mtlLayersNode->getChildCount()); - for (int l = 0; l < nChildCount; ++l) - { - XmlNodeRef layerNode = mtlLayersNode->getChild(l); - if (layerNode) - { - if (layerNode->getAttr("Name", m_pMtlLayerResources[l].m_shaderName)) - { - m_pMtlLayerResources[l].m_bRegetPublicParams = true; - - bool bNoDraw = false; - layerNode->getAttr("NoDraw", bNoDraw); - - m_pMtlLayerResources[l].m_publicVarsCache = layerNode->findChild("PublicParams"); - - if (bNoDraw) - { - m_pMtlLayerResources[l].m_nFlags |= MTL_LAYER_USAGE_NODRAW; - } - else - { - m_pMtlLayerResources[l].m_nFlags &= ~MTL_LAYER_USAGE_NODRAW; - } - - - bool bFadeOut = false; - layerNode->getAttr("FadeOut", bFadeOut); - if (bFadeOut) - { - m_pMtlLayerResources[l].m_nFlags |= MTL_LAYER_USAGE_FADEOUT; - } - else - { - m_pMtlLayerResources[l].m_nFlags &= ~MTL_LAYER_USAGE_FADEOUT; - } - } - } - } - } - - if (ctx.bUndo) - { - LoadShader(); - UpdateMatInfo(); - } - - m_bIgnoreNotifyChange = false; - - // If copy pasting or undo send update event. - if (ctx.bCopyPaste || ctx.bUndo) - { - NotifyChanged(); - } - - // NotifyChanged calls SetModified but since we just loaded it, its not actually changed. - SetModified(false); - } - else // If !ctx.bLoading - { - int extFlags = MTL_64BIT_SHADERGENMASK; - { - const QString& name = GetName(); - const size_t len = name.length(); - if (len > 4 && strstri(name.toUtf8().data() + (len - 4), "_con")) - { - extFlags |= MTL_FLAG_CONSOLE_MAT; - } - } - - // Saving. - node->setAttr("MtlFlags", m_mtlFlags | extFlags); - node->setAttr("DccMaterialHash", GetDccMaterialHash()); - - if (!IsMultiSubMaterial()) - { - // store shader gen bit mask string - m_pszShaderGenMask = GetIEditor()->GetRenderer()->EF_GetStringFromShaderGlobalMaskGen(m_shaderName.toUtf8().data(), m_nShaderGenMask).c_str(); - - node->setAttr("Shader", m_shaderName.toUtf8().data()); - node->setAttr("GenMask", m_nShaderGenMask); - node->setAttr("StringGenMask", m_pszShaderGenMask.toUtf8().data()); - node->setAttr("SurfaceType", m_surfaceType.toUtf8().data()); - - //if (!m_shaderName.IsEmpty() && (stricmp(m_shaderName,"nodraw") != 0)) - { - MaterialHelpers::SetXmlFromLighting(m_shaderResources, node); - MaterialHelpers::SetXmlFromTextures(m_shaderResources, node); - } - } - - ////////////////////////////////////////////////////////////////////////// - // Save out the link name if present and the propagation flags - ////////////////////////////////////////////////////////////////////////// - if (!m_linkedMaterial.isEmpty()) - { - XmlNodeRef pLinkName = node->newChild("MaterialLinkName"); - pLinkName->setAttr("name", m_linkedMaterial.toUtf8().data()); - } - - if (m_propagationFlags) - { - XmlNodeRef pPropagationFlags = node->newChild("MaterialPropagationFlags"); - pPropagationFlags->setAttr("flags", m_propagationFlags); - } - - ////////////////////////////////////////////////////////////////////////// - // Check if we have vertex deform. - ////////////////////////////////////////////////////////////////////////// - MaterialHelpers::SetXmlFromVertexDeform(m_shaderResources, node); - - if (GetSubMaterialCount() > 0) - { - // Serialize sub materials. - - // Let's not serialize empty submaterials at the end of the list. - // Note that IDs of the remaining submaterials stay intact. - int count = GetSubMaterialCount(); - while (count > 0 && !GetSubMaterial(count - 1)) - { - --count; - } - - XmlNodeRef childsNode = node->newChild("SubMaterials"); - - for (int i = 0; i < count; ++i) - { - CMaterial* const pSubMtl = GetSubMaterial(i); - if (pSubMtl && pSubMtl->IsPureChild()) - { - XmlNodeRef mtlNode = childsNode->newChild("Material"); - mtlNode->setAttr("Name", pSubMtl->GetName().toUtf8().data()); - SerializeContext childCtx(ctx); - childCtx.node = mtlNode; - pSubMtl->Serialize(childCtx); - } - else - { - XmlNodeRef mtlNode = childsNode->newChild("MaterialRef"); - if (pSubMtl) - { - mtlNode->setAttr("Name", pSubMtl->GetName().toUtf8().data()); - } - } - } - } - - ////////////////////////////////////////////////////////////////////////// - // Save public parameters. - ////////////////////////////////////////////////////////////////////////// - if (m_publicVarsCache) - { - node->addChild(m_publicVarsCache); - } - else if (!m_shaderResources.m_ShaderParams.empty()) - { - XmlNodeRef publicsNode = node->newChild("PublicParams"); - MaterialHelpers::SetXmlFromShaderParams(m_shaderResources, publicsNode); - } - - ////////////////////////////////////////////////////////////////////////// - // Save material layers data - ////////////////////////////////////////////////////////////////////////// - - bool bMaterialLayers = false; - for (int l(0); l < MTL_LAYER_MAX_SLOTS; ++l) - { - if (!m_pMtlLayerResources[l].m_shaderName.isEmpty()) - { - bMaterialLayers = true; - break; - } - } - - if (bMaterialLayers) - { - XmlNodeRef mtlLayersNode = node->newChild("MaterialLayers"); - for (int l(0); l < MTL_LAYER_MAX_SLOTS; ++l) - { - XmlNodeRef layerNode = mtlLayersNode->newChild("Layer"); - if (!m_pMtlLayerResources[l].m_shaderName.isEmpty()) - { - layerNode->setAttr("Name", m_pMtlLayerResources[l].m_shaderName.toUtf8().data()); - layerNode->setAttr("NoDraw", m_pMtlLayerResources[l].m_nFlags & MTL_LAYER_USAGE_NODRAW); - layerNode->setAttr("FadeOut", m_pMtlLayerResources[l].m_nFlags & MTL_LAYER_USAGE_FADEOUT); - - if (m_pMtlLayerResources[l].m_publicVarsCache) - { - layerNode->addChild(m_pMtlLayerResources[l].m_publicVarsCache); - } - else if (!m_pMtlLayerResources[l].m_shaderResources.m_ShaderParams.empty()) - { - XmlNodeRef publicsNode = layerNode->newChild("PublicParams"); - MaterialHelpers::SetXmlFromShaderParams(m_pMtlLayerResources[l].m_shaderResources, publicsNode); - } - } - } - } - - if (GetSubMaterialCount() == 0 || GetParent()) - { - node->setAttr("LayerAct", m_allowLayerActivation); - } - } -} - -/* -////////////////////////////////////////////////////////////////////////// -void CMaterial::SerializePublics( XmlNodeRef &node,bool bLoading ) -{ -if (bLoading) -{ -} -else -{ -if (m_shaderParams.empty()) -return; -XmlNodeRef publicsNode = node->newChild( "PublicParams" ); - -for (int i = 0; i < m_shaderParams.size(); i++) -{ -XmlNodeRef paramNode = node->newChild( "Param" ); -SShaderParam *pParam = &m_shaderParams[i]; -paramNode->setAttr( "Name",pParam->m_Name ); -switch (pParam->m_Type) -{ -case eType_BYTE: -paramNode->setAttr( "Value",(int)pParam->m_Value.m_Byte ); -paramNode->setAttr( "Type",(int)pParam->m_Value.m_Byte ); -break; -case eType_SHORT: -paramNode->setAttr( "Value",(int)pParam->m_Value.m_Short ); -break; -case eType_INT: -paramNode->setAttr( "Value",(int)pParam->m_Value.m_Int ); -break; -case eType_FLOAT: -paramNode->setAttr( "Value",pParam->m_Value.m_Float ); -break; -case eType_STRING: -paramNode->setAttr( "Value",pParam->m_Value.m_String ); -break; -case eType_FCOLOR: -paramNode->setAttr( "Value",Vec3(pParam->m_Value.m_Color[0],pParam->m_Value.m_Color[1],pParam->m_Value.m_Color[2]) ); -break; -case eType_VECTOR: -paramNode->setAttr( "Value",Vec3(pParam->m_Value.m_Vector[0],pParam->m_Value.m_Vector[1],pParam->m_Value.m_Vector[2]) ); -break; -} -} -} -} -*/ - -////////////////////////////////////////////////////////////////////////// -void CMaterial::AssignToEntity(IRenderNode* pEntity) -{ - assert(pEntity); - pEntity->SetMaterial(GetMatInfo()); -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterial::IsBreakable2D() const -{ - if ((GetFlags() & MTL_FLAG_NODRAW) != 0) - { - return false; - } - - const QString& surfaceTypeName = GetSurfaceTypeName(); - if (ISurfaceTypeManager* pSurfaceManager = GetIEditor()->Get3DEngine()->GetMaterialManager()->GetSurfaceTypeManager()) - { - ISurfaceType* pSurfaceType = pSurfaceManager->GetSurfaceTypeByName(surfaceTypeName.toUtf8().data()); - if (pSurfaceType && pSurfaceType->GetBreakable2DParams() != 0) - { - return true; - } - } - - int count = GetSubMaterialCount(); - for (int i = 0; i < count; ++i) - { - const CMaterial* pSub = GetSubMaterial(i); - if (!pSub) - { - continue; - } - if (pSub->IsBreakable2D()) - { - return true; - } - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetFromMatInfo(_smart_ptr pMatInfo) -{ - assert(pMatInfo); - - m_shaderName = ""; - - ClearMatInfo(); - SetModified(true); - - m_mtlFlags = pMatInfo->GetFlags(); - if (m_mtlFlags & MTL_FLAG_MULTI_SUBMTL) - { - // Create sub materials. - SetSubMaterialCount(pMatInfo->GetSubMtlCount()); - for (int i = 0; i < GetSubMaterialCount(); i++) - { - _smart_ptr pChildMatInfo = pMatInfo->GetSubMtl(i); - if (!pChildMatInfo) - { - continue; - } - - if (pChildMatInfo->GetFlags() & MTL_FLAG_PURE_CHILD) - { - CMaterial* existingChild = GetSubMaterial(i); - if (existingChild) - { - existingChild->SetFromMatInfo(pChildMatInfo); - } - else - { - CMaterial* pChild = new CMaterial(pChildMatInfo->GetName(), pChildMatInfo->GetFlags()); - pChild->SetFromMatInfo(pChildMatInfo); - SetSubMaterial(i, pChild); - } - } - else - { - CMaterial* pChild = GetIEditor()->GetMaterialManager()->LoadMaterial(pChildMatInfo->GetName()); - pChild->SetFromMatInfo(pChildMatInfo); - SetSubMaterial(i, pChild); - } - } - } - else - { - SetShaderItem(pMatInfo->GetShaderItem()); - - if (m_shaderItem.m_pShaderResources) - { - m_shaderResources = SInputShaderResources(m_shaderItem.m_pShaderResources); - } - if (m_shaderItem.m_pShader) - { - // Get name of template. - IShader* pTemplShader = m_shaderItem.m_pShader; - if (pTemplShader) - { - m_nShaderGenMask = pTemplShader->GetGenerationMask(); - } - } - m_shaderName = pMatInfo->GetShaderName(); - ISurfaceType* pSurfaceType = pMatInfo->GetSurfaceType(); - if (pSurfaceType) - { - m_surfaceType = pSurfaceType->GetName(); - } - else - { - m_surfaceType = ""; - } - } - - // Mark as not modified. - SetModified(false); - - // Material link names - if (const char* szLinkName = pMatInfo->GetMaterialLinkName()) - { - m_linkedMaterial = szLinkName; - } - - ////////////////////////////////////////////////////////////////////////// - // Assign mat info. - m_pMatInfo = pMatInfo; - m_pMatInfo->SetUserData(this); - AddRef(); // Let IMaterial keep a reference to us. -} - -////////////////////////////////////////////////////////////////////////// -int CMaterial::GetSubMaterialCount() const -{ - return m_subMaterials.size(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetSubMaterialCount(int nSubMtlsCount) -{ - RecordUndo("Multi Material Change"); - m_subMaterials.resize(nSubMtlsCount); - UpdateMatInfo(); - NotifyChanged(); -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterial::GetSubMaterial(int index) const -{ - const int nSubMats = m_subMaterials.size(); - assert(index >= 0 && index < nSubMats); - - if (index < 0 || index >= nSubMats) - { - return NULL; - } - - return m_subMaterials[index]; -} - -////////////////////////////////////////////////////////////////////////// -int CMaterial::FindMaterialIndex(const QString& name) -{ - for (int i = 0; i < m_subMaterials.size(); ++i) - { - if (m_subMaterials[i]->GetName().compare(name) == 0) - { - return i; - } - } - - return -1; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetSubMaterial(int nSlot, CMaterial* mtl) -{ - RecordUndo("Multi Material Change"); - assert(nSlot >= 0 && nSlot < m_subMaterials.size()); - if (mtl) - { - if (mtl->IsMultiSubMaterial()) - { - return; - } - if (mtl->IsPureChild()) - { - mtl->m_pParent = this; - } - } - - if (m_subMaterials[nSlot]) - { - m_subMaterials[nSlot]->m_pParent = NULL; - } - m_subMaterials[nSlot] = mtl; - - if (!m_subMaterials[nSlot]) - { - m_subMaterials.erase(m_subMaterials.begin() + nSlot); - } - - UpdateMatInfo(); - NotifyChanged(); -} - -////////////////////////////////////////////////////////////////////////// -// This method will populate for the material editor the name and tool tip of the -// different textures of the current material -//CVarBlock* CMaterial::UpdateTextureNames(AZStd::unordered_map& textureVarsMap) -CVarBlock* CMaterial::UpdateTextureNames(CSmartVariableArray textureVars[EFTT_MAX]) -{ - CVarBlock* pTextureSlots = new CVarBlock; - IShader* pTemplShader = m_shaderItem.m_pShader; - int nTech = max(0, m_shaderItem.m_nTechnique); - SShaderTexSlots* pShaderSlots = pTemplShader ? pTemplShader->GetUsedTextureSlots(nTech) : nullptr; - - for (EEfResTextures nTexSlot = EEfResTextures(0); nTexSlot < EFTT_MAX; nTexSlot = EEfResTextures(nTexSlot + 1)) - { - if (!MaterialHelpers::IsAdjustableTexSlot((EEfResTextures)nTexSlot)) - { // do not take into account virtual slots (such as smoothness - normal's alpha) - // in theory this case should not happen as it is filtered from the source list. - continue; - } - - IVariable* pVar = textureVars[nTexSlot].GetVar(); - SShaderTextureSlot* pSlot = pShaderSlots ? pShaderSlots->m_UsedTextureSlots[nTexSlot] : nullptr; - - // If slot is NULL, fall back to default name - name here is the context name (i.e. diffuse, normal..) - // and not the actual texture file name - pVar->SetName(pSlot && pSlot->m_Name.length() ? pSlot->m_Name.c_str() : MaterialHelpers::LookupTexName((EEfResTextures) nTexSlot)); - pVar->SetDescription(pSlot && pSlot->m_Description.length() ? pSlot->m_Description.c_str() : MaterialHelpers::LookupTexDesc((EEfResTextures)nTexSlot)); - - int flags = pVar->GetFlags(); - - // TODO: slot->m_TexType gives expected sampler type (2D vs Cube etc). Could check/extract this here. - - // Not sure why this needs COLLAPSED added again, but without this all the slots expand - flags |= IVariable::UI_COLLAPSED; - - //clear the auto-expand flag if there is no texture assigned. - SEfResTexture* pTextureRes = m_shaderResources.GetTextureResource(nTexSlot); - bool noTextureName = (!pTextureRes ? true : pTextureRes->m_Name.empty()); - - if (noTextureName) - { - flags &= ~IVariable::UI_AUTO_EXPAND; - } - - // if slot is NULL, but we have reflection information, this slot isn't used - make the variable invisible - // unless there's a texture in the slot - if (pShaderSlots && !pSlot && noTextureName) - { - flags |= IVariable::UI_INVISIBLE; - } - else - { - flags &= ~IVariable::UI_INVISIBLE; - } - - pVar->SetFlags(flags); - - pTextureSlots->AddVariable(pVar); - } - - return pTextureSlots; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::ClearAllSubMaterials() -{ - RecordUndo("Multi Material Change"); - for (int i = 0; i < m_subMaterials.size(); i++) - { - if (m_subMaterials[i]) - { - m_subMaterials[i]->m_pParent = NULL; - m_subMaterials[i] = NULL; - } - } - UpdateMatInfo(); - NotifyChanged(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::Validate() -{ - if (IsDummy()) - { - CErrorRecord err; - err.error = QObject::tr("Material %1 file not found").arg(GetName()); - err.pItem = this; - GetIEditor()->GetErrorReport()->ReportError(err); - } - // Reload shader. - LoadShader(); - - // Validate sub materials. - for (int i = 0; i < m_subMaterials.size(); i++) - { - if (m_subMaterials[i]) - { - m_subMaterials[i]->Validate(); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::GatherUsedResources(CUsedResources& resources) -{ - if (!IsUsed()) - { - return; - } - - SInputShaderResources& sr = GetShaderResources(); - for (auto iter = sr.m_TexturesResourcesMap.begin(); iter != sr.m_TexturesResourcesMap.end(); ++iter) - { - SEfResTexture* pTexture = &iter->second; - if (!pTexture->m_Name.empty()) - { - resources.Add(pTexture->m_Name.c_str()); - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterial::CanModify(bool bSkipReadOnly) -{ - if (m_bDummyMaterial) - { - return false; - } - - if (IsPureChild() && GetParent()) - { - return GetParent()->CanModify(bSkipReadOnly); - } - - if (bSkipReadOnly) - { - // If read only or in pack, do not save. - if (m_scFileAttributes & (SCC_FILE_ATTRIBUTE_READONLY | SCC_FILE_ATTRIBUTE_INPAK)) - { - return false; - } - - // Managed file must be checked out. - if ((m_scFileAttributes & SCC_FILE_ATTRIBUTE_MANAGED) && !(m_scFileAttributes & SCC_FILE_ATTRIBUTE_CHECKEDOUT)) - { - return false; - } - } - else - { - // Only if in pack. - if (m_scFileAttributes & (SCC_FILE_ATTRIBUTE_INPAK)) - { - return false; - } - } - return true; -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterial::Save(bool bSkipReadOnly, const QString& fullPath) -{ - // Save our parent - if (IsPureChild()) - { - if (m_pParent) - { - return m_pParent->Save(bSkipReadOnly); - } - return false; - } - - if (m_mtlFlags & MTL_FLAG_UIMATERIAL) - { - return false; - } - - GetFileAttributes(); - - if (bSkipReadOnly && IsModified()) - { - // If read only or in pack, do not save. - if (m_scFileAttributes & (SCC_FILE_ATTRIBUTE_READONLY | SCC_FILE_ATTRIBUTE_INPAK)) - { - gEnv->pLog->LogError("Can't save material %s (read-only)", GetName().toUtf8().constData()); - } - - // Managed file must be checked out. - if ((m_scFileAttributes & SCC_FILE_ATTRIBUTE_MANAGED) && !(m_scFileAttributes & SCC_FILE_ATTRIBUTE_CHECKEDOUT)) - { - gEnv->pLog->LogError("Can't save material %s (need to check out)", GetName().toUtf8().constData()); - } - } - - if (!CanModify(bSkipReadOnly)) - { - return false; - } - - - // If filename is empty do not not save. - if (GetFilename().isEmpty()) - { - return false; - } - - // Save material XML to a file that corresponds to the material name with extension .mtl. - XmlNodeRef mtlNode = XmlHelpers::CreateXmlNode("Material"); - CBaseLibraryItem::SerializeContext ctx(mtlNode, false); - Serialize(ctx); - - bool saveSucceeded = false; - if (fullPath.isEmpty()) - { - // If no filepath was specified, get the filename using the relative path/unique identifier of this material - saveSucceeded = XmlHelpers::SaveXmlNode(GetIEditor()->GetFileUtil(), mtlNode, GetFilename().toUtf8().data()); - } - else - { - // If a filepath was specified, save to the specified location - saveSucceeded = XmlHelpers::SaveXmlNode(GetIEditor()->GetFileUtil(), mtlNode, fullPath.toUtf8().data()); - } - - if (saveSucceeded) - { - // If material successfully saved, clear modified flag. - SetModified(false); - for (int i = 0; i < GetSubMaterialCount(); ++i) - { - CMaterial* pSubMaterial = GetSubMaterial(i); - if (pSubMaterial) - { - pSubMaterial->SetModified(false); - } - } - } - else - { - AZ_Warning("Material Editor", false, "Material '%s' failed to save successfully. Check that the file is writable and has been successfully checked out in source control.", m_name.toUtf8().data()); - } - - return saveSucceeded; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::ClearMatInfo() -{ - m_pMatInfo = nullptr; -} - -////////////////////////////////////////////////////////////////////////// -_smart_ptr CMaterial::GetMatInfo(bool bUseExistingEngineMaterial) -{ - if (!m_pMatInfo) - { - if (m_bDummyMaterial) - { - m_pMatInfo = GetIEditor()->Get3DEngine()->GetMaterialManager()->GetDefaultMaterial(); - AddRef(); // Always keep dummy materials. - return m_pMatInfo; - } - - if (!IsMultiSubMaterial() && !m_shaderItem.m_pShader) - { - LoadShader(); - } - - if (!IsPureChild()) - { - if (bUseExistingEngineMaterial) - { - m_pMatInfo = GetIEditor()->Get3DEngine()->GetMaterialManager()->FindMaterial(GetName().toUtf8().data()); - } - - if (!m_pMatInfo) - { - m_pMatInfo = GetIEditor()->Get3DEngine()->GetMaterialManager()->CreateMaterial(GetName().toUtf8().data(), m_mtlFlags); - } - } - else - { - // Pure child should not be registered with the name. - m_pMatInfo = GetIEditor()->Get3DEngine()->GetMaterialManager()->CreateMaterial("", m_mtlFlags); - m_pMatInfo->SetName(GetName().toUtf8().data()); - } - m_mtlFlags = m_pMatInfo->GetFlags(); - UpdateMatInfo(); - - if (m_pMatInfo->GetUserData() != this) - { - m_pMatInfo->SetUserData(this); - AddRef(); // Let IMaterial keep a reference to us. - } - } - - return m_pMatInfo; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::NotifyChanged() -{ - if (m_bIgnoreNotifyChange) - { - return; - } - - if (!CanModify() && !IsModified() && CUndo::IsRecording()) - { - // Display Warning message. - Warning("Modifying read only material %s\r\nChanges will not be saved!", GetName().toUtf8().data()); - } - - SetModified(); - - GetIEditor()->GetMaterialManager()->OnItemChanged(this); -} - -////////////////////////////////////////////////////////////////////////// -class CUndoMaterial - : public IUndoObject -{ -public: - CUndoMaterial(CMaterial* pMaterial, const char* undoDescription, bool bForceUpdate) - { - assert(pMaterial); - - // Stores the current state of this object. - m_undoDescription = undoDescription; - - m_bIsSubMaterial = pMaterial->IsPureChild(); - - if (m_bIsSubMaterial) - { - CMaterial* pParentMaterial = pMaterial->GetParent(); - assert(pParentMaterial && !pParentMaterial->IsPureChild()); - if (pParentMaterial && !pParentMaterial->IsPureChild()) - { - bool bFound = false; - const int subMaterialCount = pParentMaterial->GetSubMaterialCount(); - for (int i = 0; i < subMaterialCount; ++i) - { - CMaterial* pSubMaterial = pParentMaterial->GetSubMaterial(i); - if (pSubMaterial == pMaterial) - { - bFound = true; - m_subMaterialName = pSubMaterial->GetName(); - break; - } - } - assert(bFound); - m_mtlName = pParentMaterial->GetName(); - } - } - else - { - m_mtlName = pMaterial->GetName(); - } - - // Save material XML to a file that corresponds to the material name with extension .mtl. - m_undo = XmlHelpers::CreateXmlNode("Material"); - CBaseLibraryItem::SerializeContext ctx(m_undo, false); - pMaterial->Serialize(ctx); - m_bForceUpdate = bForceUpdate; - } - -protected: - virtual void Release() { delete this; }; - - virtual int GetSize() - { - return sizeof(*this) + m_undoDescription.length() + m_mtlName.length(); - } - - virtual QString GetDescription() { return m_undoDescription; }; - - virtual void Undo(bool bUndo) - { - CMaterial* pMaterial = GetMaterial(); - - assert(pMaterial); - if (!pMaterial) - { - return; - } - - if (bUndo) - { - // Save current object state. - m_redo = XmlHelpers::CreateXmlNode("Material"); - CBaseLibraryItem::SerializeContext ctx(m_redo, false); - pMaterial->Serialize(ctx); - } - - CBaseLibraryItem::SerializeContext ctx(m_undo, true); - ctx.bUndo = bUndo; - pMaterial->Serialize(ctx); - - if (m_bForceUpdate && bUndo) - { - GetIEditor()->GetMaterialManager()->OnUpdateProperties(pMaterial, true); - } - } - - virtual void Redo() - { - CMaterial* pMaterial = GetMaterial(); - - if (!pMaterial) - { - return; - } - - CBaseLibraryItem::SerializeContext ctx(m_redo, true); - ctx.bUndo = true; - pMaterial->Serialize(ctx); - - if (m_bForceUpdate) - { - GetIEditor()->GetMaterialManager()->OnUpdateProperties(pMaterial, true); - } - } - -private: - CMaterial* GetMaterial() - { - CMaterial* pMaterial = (CMaterial*)GetIEditor()->GetMaterialManager()->FindItemByName(m_mtlName); - assert(pMaterial); - - if (pMaterial && m_bIsSubMaterial) - { - bool bFound = false; - const int subMaterialCount = pMaterial->GetSubMaterialCount(); - for (int i = 0; i < subMaterialCount; ++i) - { - CMaterial* pSubMaterial = pMaterial->GetSubMaterial(i); - if (pSubMaterial && (pSubMaterial->GetName() == m_subMaterialName)) - { - bFound = true; - pMaterial = pSubMaterial; - break; - } - } - assert(bFound && pMaterial); - } - - return pMaterial; - } - - QString m_undoDescription; - QString m_mtlName; - bool m_bIsSubMaterial; - QString m_subMaterialName; - XmlNodeRef m_undo; - XmlNodeRef m_redo; - bool m_bForceUpdate; -}; - -////////////////////////////////////////////////////////////////////////// -void CMaterial::RecordUndo(const char* sText, bool bForceUpdate) -{ - if (CUndo::IsRecording()) - { - CUndo::Record(new CUndoMaterial(this, sText, bForceUpdate)); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::OnMakeCurrent() -{ - UpdateFileAttributes(false); - - // If Shader not yet loaded, load it now. - if (!m_shaderItem.m_pShader) - { - LoadShader(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetSurfaceTypeName(const QString& surfaceType) -{ - m_surfaceType = surfaceType; - UpdateMatInfo(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::Reload() -{ - if (IsPureChild()) - { - if (m_pParent) - { - m_pParent->Reload(); - } - return; - } - if (IsDummy()) - { - return; - } - - XmlNodeRef mtlNode = GetISystem()->LoadXmlFromFile(GetFilename().toUtf8().data()); - if (!mtlNode) - { - return; - } - CBaseLibraryItem::SerializeContext serCtx(mtlNode, true); - serCtx.bUndo = true; // Simulate undo. - Serialize(serCtx); - - // was called by Simulate undo. - //UpdateMatInfo(); - //NotifyChanged(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::LinkToMaterial(const QString& name) -{ - m_linkedMaterial = name; - UpdateMatInfo(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::DisableHighlightForFrame() -{ - SetHighlightFlags(0); -} - -static ColorF Interpolate(const ColorF& a, const ColorF& b, float phase) -{ - const float oneMinusPhase = 1.0f - phase; - return ColorF(b.r * phase + a.r * oneMinusPhase, - b.g * phase + a.g * oneMinusPhase, - b.b * phase + a.b * oneMinusPhase, - b.a * phase + a.a * oneMinusPhase); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::UpdateHighlighting() -{ - if (!(GetFlags() & MTL_FLAG_NODRAW)) - { - const CInputLightMaterial& original = m_shaderResources.m_LMaterial; - CInputLightMaterial lm = original; - - ColorF highlightColor(0.0f, 0.0f, 0.0f, 1.0f); - float highlightIntensity = 0.0f; - - MAKE_SURE(GetIEditor()->GetMaterialManager(), return ); - GetIEditor()->GetMaterialManager()->GetHighlightColor(&highlightColor, &highlightIntensity, m_highlightFlags); - - if (m_shaderItem.m_pShaderResources) - { - ColorF diffuseColor = Interpolate(original.m_Diffuse, highlightColor, highlightIntensity); - ColorF emissiveColor = Interpolate(original.m_Emittance, highlightColor, highlightIntensity); - ColorF specularColor = Interpolate(original.m_Specular, highlightColor, highlightIntensity); - - // [Shader System TO DO] remove this hard coded association! - m_shaderItem.m_pShaderResources->SetColorValue(EFTT_DIFFUSE, diffuseColor); - m_shaderItem.m_pShaderResources->SetColorValue(EFTT_SPECULAR, specularColor); - m_shaderItem.m_pShaderResources->SetColorValue(EFTT_EMITTANCE, emissiveColor); - - m_shaderItem.m_pShaderResources->UpdateConstants(m_shaderItem.m_pShader); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterial::SetHighlightFlags(int highlightFlags) -{ - m_highlightFlags = highlightFlags; - - UpdateHighlighting(); -} - - -void CMaterial::SetShaderItem(const SShaderItem& shaderItem) -{ - SAFE_RELEASE(m_shaderItem.m_pShader); - SAFE_RELEASE(m_shaderItem.m_pShaderResources); - - m_shaderItem = shaderItem; - if (m_shaderItem.m_pShader) - { - m_shaderItem.m_pShader->AddRef(); - } - if (m_shaderItem.m_pShaderResources) - { - m_shaderItem.m_pShaderResources->AddRef(); - } -} diff --git a/Code/Sandbox/Editor/Material/Material.h b/Code/Sandbox/Editor/Material/Material.h deleted file mode 100644 index b311744e14..0000000000 --- a/Code/Sandbox/Editor/Material/Material.h +++ /dev/null @@ -1,315 +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_MATERIAL_MATERIAL_H -#define CRYINCLUDE_EDITOR_MATERIAL_MATERIAL_H -#pragma once - -#include -#include -#include "BaseLibraryItem.h" -#include "Include/IEditorMaterial.h" -#include "Util/Variable.h" -#include - -// forward declarations, -class CMaterialManager; -class CVarBlock; - -enum eMTL_PROPAGATION -{ - MTL_PROPAGATE_OPACITY = 1 << 0, - MTL_PROPAGATE_LIGHTING = 1 << 1, - MTL_PROPAGATE_ADVANCED = 1 << 2, - MTL_PROPAGATE_TEXTURES = 1 << 3, - MTL_PROPAGATE_SHADER_PARAMS = 1 << 4, - MTL_PROPAGATE_SHADER_GEN = 1 << 5, - MTL_PROPAGATE_VERTEX_DEF = 1 << 6, - MTL_PROPAGATE_LAYER_PRESETS = 1 << 7, - MTL_PROPAGATE_MATERIAL_SETTINGS = 1 << 8, - MTL_PROPAGATE_ALL = ( - MTL_PROPAGATE_OPACITY | - MTL_PROPAGATE_LIGHTING | - MTL_PROPAGATE_ADVANCED | - MTL_PROPAGATE_TEXTURES | - MTL_PROPAGATE_SHADER_PARAMS | - MTL_PROPAGATE_SHADER_GEN | - MTL_PROPAGATE_VERTEX_DEF | - MTL_PROPAGATE_LAYER_PRESETS | - MTL_PROPAGATE_MATERIAL_SETTINGS), - MTL_PROPAGATE_RESERVED = 1 << 9 -}; - -/** CMaterial class - Every Material is a member of material library. - Materials can have child sub materials, - Sub materials are applied to the same geometry of the parent material in the other material slots. -*/ - -struct SMaterialLayerResources -{ - SMaterialLayerResources() - : m_nFlags(MTL_LAYER_USAGE_REPLACEBASE) - , m_bRegetPublicParams(true) - , m_pMatLayer(0) - { - } - - uint8 m_nFlags; - bool m_bRegetPublicParams; - QString m_shaderName; - - _smart_ptr< IMaterialLayer > m_pMatLayer; - SInputShaderResources m_shaderResources; - XmlNodeRef m_publicVarsCache; -}; - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -class CRYEDIT_API CMaterial - : public IEditorMaterial -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING -public: - ////////////////////////////////////////////////////////////////////////// - CMaterial(const QString& name, int nFlags = 0); - CMaterial(const CMaterial& rhs); - ~CMaterial(); - - virtual EDataBaseItemType GetType() const { return EDB_TYPE_MATERIAL; }; - - void SetName(const QString& name); - - ////////////////////////////////////////////////////////////////////////// - QString GetFullName() const { return m_name; }; - - ////////////////////////////////////////////////////////////////////////// - // File properties of the material. - ////////////////////////////////////////////////////////////////////////// - QString GetFilename() const; - - //! Collect filenames of texture sources used in material - //! Return number of filenames - int GetTextureFilenames(QStringList& outFilenames) const; - int GetAnyTextureFilenames(QStringList& outFilenames) const; - - void UpdateFileAttributes(bool useSourceControl = true); - uint32 GetFileAttributes(); - ////////////////////////////////////////////////////////////////////////// - - //! Sets one or more material flags from EMaterialFlags enum. - void SetFlags(int flags) { m_mtlFlags = flags; }; - //! Query this material flags. - virtual int GetFlags() const { return m_mtlFlags; } - bool IsMultiSubMaterial() const { return (m_mtlFlags & MTL_FLAG_MULTI_SUBMTL) != 0; }; - bool IsPureChild() const { return (m_mtlFlags & MTL_FLAG_PURE_CHILD) != 0; } - - // Check if material is used. - bool IsUsed() const { /*return m_nUseCount > 0 || (m_mtlFlags & MTL_FLAG_ALWAYS_USED);*/ return true; }; - - virtual void GatherUsedResources(CUsedResources& resources); - - //! Set name of shader used by this material. - void SetShaderName(const QString& shaderName); - //! Get name of shader used by this material. - QString GetShaderName() const { return m_shaderName; }; - - virtual SInputShaderResources& GetShaderResources() { return m_shaderResources; }; - - //! Get public parameters of material in variable block. - CVarBlock* GetPublicVars(SInputShaderResources& pShaderResources); - - //! Set the shader public param m_script variable into our own m_script, script contains min/max for a given shader param value - void SetShaderParamPublicScript(); - - //! Sets variable block of public shader parameters. - //! VarBlock must be in same format as returned by GetPublicVars(). - void SetPublicVars(CVarBlock* pPublicVars, CMaterial* pMtl); - - //! Update names/descriptions in this variable array, return a variable block for replacing - CVarBlock* UpdateTextureNames(CSmartVariableArray textureVars[EFTT_MAX]); -// [Shader System] - Do To: add back with map usage: CVarBlock* UpdateTextureNames(AZStd::unordered_map& textureVarsMap); - - ////////////////////////////////////////////////////////////////////////// - CVarBlock* GetShaderGenParamsVars(); - void SetShaderGenParamsVars(CVarBlock* pBlock); - uint64 GetShaderGenMask() { return m_nShaderGenMask; } - void SetShaderGenMask(uint64 mask) { m_nShaderGenMask = mask; } - - //! Return variable block of shader params. - SShaderItem& GetShaderItem() { return m_shaderItem; }; - - //! Return material layers resources - SMaterialLayerResources* GetMtlLayerResources() { return m_pMtlLayerResources; }; - - //! Get texture map usage mask for shader in this material. - unsigned int GetTexmapUsageMask() const; - - //! Load new shader. - bool LoadShader(); - - //! Reload shader, update all shader parameters. - virtual void Update(); - - // Reload material settings from file. - // NOTICE: The function will remove all the sub-materials and recreate them! - void Reload(); - - //! Serialize material settings to xml. - virtual void Serialize(SerializeContext& ctx); - - //! Assign this material to static geometry. - void AssignToEntity(IRenderNode* pEntity); - - ////////////////////////////////////////////////////////////////////////// - // Surface types. - ////////////////////////////////////////////////////////////////////////// - virtual void SetSurfaceTypeName(const QString& surfaceType); - virtual const QString& GetSurfaceTypeName() const { return m_surfaceType; }; - bool IsBreakable2D() const; - - ////////////////////////////////////////////////////////////////////////// - // Child Sub materials. - ////////////////////////////////////////////////////////////////////////// - //! Get number of sub materials childs. - int GetSubMaterialCount() const; - //! Set number of sub materials childs. - void SetSubMaterialCount(int nSubMtlsCount); - //! Get sub material child by index. - CMaterial* GetSubMaterial(int index) const; - //! Find sub material index by name - int FindMaterialIndex(const QString& name); - // Set a material to the sub materials slot. - // Use NULL material pointer to clear slot. - void SetSubMaterial(int nSlot, CMaterial* mtl); - //! Remove all sub materials, does not change number of sub material slots. - void ClearAllSubMaterials(); - - //! Return pointer to engine material. - virtual _smart_ptr GetMatInfo(bool bUseExistingEngineMaterial = true); - // Clear stored pointer to engine material. - void ClearMatInfo(); - - //! Validate materials for errors. - void Validate(); - - // Check if material file can be modified. - // Will check file attributes if it is not read only. - bool CanModify(bool bSkipReadOnly = true); - - // Save material to file. - virtual bool Save(bool bSkipReadOnly = true, const QString& fullPath = ""); - - // Dummy material is just a placeholder item for materials that have not been found on disk. - void SetDummy(bool bDummy) { m_bDummyMaterial = bDummy; } - bool IsDummy() const { return m_bDummyMaterial != 0; } - - // Called by material manager when material selected as a current material. - void OnMakeCurrent(); - - void SetFromMatInfo(_smart_ptr pMatInfo); - - // Link a submaterial by name (used for value propagation in CMaterialUI) - void LinkToMaterial(const QString& name); - const QString& GetLinkedMaterialName() { return m_linkedMaterial; } - - // Return parent material for submaterial - CMaterial* GetParent() const {return m_pParent; } - - //! Loads material layers - bool LoadMaterialLayers(); - //! Updates material layers - void UpdateMaterialLayers(); - - void SetHighlightFlags(int highlightFlags); - void UpdateHighlighting(); - virtual void DisableHighlightForFrame(); - void RecordUndo(const char* sText, bool bForceUpdate = false); - - int GetPropagationFlags() const { return m_propagationFlags; } - void SetPropagationFlags(const int flags) { m_propagationFlags = flags; } - - bool LayerActivationAllowed() const { return m_allowLayerActivation; } - void SetLayerActivation(bool allowed) { m_allowLayerActivation = allowed; } - - uint32 GetDccMaterialHash() const { return m_dccMaterialHash; } - void SetDccMaterialHash(AZ::u32 hash) { m_dccMaterialHash = hash; } - void SetShaderItem(const SShaderItem& shaderItem); - -private: - void UpdateMatInfo(); - void CheckSpecialConditions(); - - void NotifyChanged(); - -private: - ////////////////////////////////////////////////////////////////////////// - // Variables. - ////////////////////////////////////////////////////////////////////////// - QString m_shaderName; - QString m_surfaceType; - QString m_linkedMaterial; - - //! Material flags. - int m_mtlFlags; - - // Hash for DCC material attributes, used to check if .dccmtl has changed - // If so, the source .mtl file will need to be rebuilt - uint32 m_dccMaterialHash; - - // Parent material, Only valid for Pure Childs. - CMaterial* m_pParent; - - ////////////////////////////////////////////////////////////////////////// - // Shader resources. - ////////////////////////////////////////////////////////////////////////// - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - SShaderItem m_shaderItem; - SInputShaderResources m_shaderResources; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - //CVarBlockPtr m_shaderParamsVar; - //! Common shader flags. - uint64 m_nShaderGenMask; - QString m_pszShaderGenMask; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - SMaterialLayerResources m_pMtlLayerResources[MTL_LAYER_MAX_SLOTS]; - - _smart_ptr m_pMatInfo; - - XmlNodeRef m_publicVarsCache; - - //! Array of sub materials. - std::vector<_smart_ptr > m_subMaterials; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - int m_nUseCount; - uint32 m_scFileAttributes; - - unsigned char m_highlightFlags; - - // The propagation flags are a bit combination of the MTL_PROPAGATION enum above - // and determine which properties get propagated to an optional linked material - // during ui editing - int m_propagationFlags; - - //! Material Used in level. - unsigned int m_bDummyMaterial : 1; // Dummy material, name specified but material file not found. - unsigned int m_bIgnoreNotifyChange : 1; // Do not send notifications about changes. - unsigned int m_bRegetPublicParams : 1; - unsigned int m_bKeepPublicParamsValues : 1; - - bool m_allowLayerActivation; -}; - -#endif // CRYINCLUDE_EDITOR_MATERIAL_MATERIAL_H diff --git a/Code/Sandbox/Editor/Material/MaterialBrowser.cpp b/Code/Sandbox/Editor/Material/MaterialBrowser.cpp deleted file mode 100644 index e39a29a47d..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialBrowser.cpp +++ /dev/null @@ -1,1792 +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 "MaterialBrowser.h" - -// Qt -#include - -// AzQtComponents -#include - -// AzToolsFramework -#include - -// Editor -#include "MaterialManager.h" -#include "Clipboard.h" -#include "MaterialImageListCtrl.h" -#include "StringDlg.h" - -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -#include -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - -enum -{ - MENU_UNDEFINED = CMaterialImageListCtrl::MaterialBrowserWidgetActionsStart, - MENU_CUT, - MENU_COPY, - MENU_COPY_NAME, - MENU_PASTE, - MENU_EXPLORE, - MENU_DUPLICATE, - MENU_EXTRACT, - MENU_RENAME, - MENU_DELETE, - MENU_RESET, - MENU_ASSIGNTOSELECTION, - MENU_SELECTASSIGNEDOBJECTS, - MENU_NUM_SUBMTL, - MENU_ADDNEW, - MENU_ADDNEW_MULTI, - MENU_CONVERT_TO_MULTI, - MENU_SUBMTL_MAKE, - MENU_SUBMTL_CLEAR, - MENU_SAVE_TO_FILE, - MENU_SAVE_TO_FILE_MULTI, - MENU_MERGE, - - MENU_SCM_ADD, - MENU_SCM_CHECK_OUT, - MENU_SCM_UNDO_CHECK_OUT, - MENU_SCM_GET_LATEST, - MENU_SCM_GET_LATEST_TEXTURES, -}; - -static QAction* CreateTreeViewAction(const char* text, const QKeySequence& shortcut, QWidget* shortcutContext, MaterialBrowserWidget* widget, void (MaterialBrowserWidget::*slot)()) -{ - QAction* action = new QAction(text, shortcutContext); - action->setShortcut(shortcut); - QObject::connect(action, &QAction::triggered, widget, slot); - widget->addAction(action); - return action; -} - -////////////////////////////////////////////////////////////////////////// -MaterialBrowserWidget::MaterialBrowserWidget(QWidget* parent) - : QWidget(parent) - , m_ui(new Ui::MaterialBrowser) - , m_filterModel(new MaterialBrowserFilterModel(this)) -{ - using namespace AzToolsFramework::AssetBrowser; - - m_ui->setupUi(this); - - // create some permanent (for the life of this widget) actions for shortcut handling - m_cutAction = CreateTreeViewAction("Cut", QKeySequence::Cut, m_ui->treeView, this, &MaterialBrowserWidget::OnCut); - m_copyAction = CreateTreeViewAction("Copy", QKeySequence::Copy, m_ui->treeView, this, &MaterialBrowserWidget::OnCopy); - m_pasteAction = CreateTreeViewAction("Paste", QKeySequence::Paste, m_ui->treeView, this, &MaterialBrowserWidget::OnPaste); - m_duplicateAction = CreateTreeViewAction("Duplicate", QKeySequence(Qt::CTRL + Qt::Key_D), m_ui->treeView, this, &MaterialBrowserWidget::OnDuplicate); - m_deleteAction = CreateTreeViewAction("Delete", QKeySequence::Delete, m_ui->treeView, this, &MaterialBrowserWidget::DeleteItem); - m_renameItemAction = CreateTreeViewAction("Rename", Qt::Key_F2, m_ui->treeView, this, &MaterialBrowserWidget::OnRenameItem); - m_addNewMaterialAction = CreateTreeViewAction("Add New Material", Qt::Key_Insert, m_ui->treeView, this, &MaterialBrowserWidget::OnAddNewMaterial); - - MaterialBrowserWidgetBus::Handler::BusConnect(); - - // Get the asset browser model - AssetBrowserComponentRequestBus::BroadcastResult(m_assetBrowserModel, &AssetBrowserComponentRequests::GetAssetBrowserModel); - AZ_Assert(m_assetBrowserModel, "Failed to get filebrowser model"); - - // Set up the filter model - m_filterModel->setSourceModel(m_assetBrowserModel); - m_ui->treeView->setModel(m_filterModel.data()); - m_ui->treeView->SetThumbnailContext("MaterialBrowser"); - m_ui->treeView->SetShowSourceControlIcons(true); - - m_ui->m_searchWidget->Setup(true, false); - m_filterModel->SetSearchFilter(m_ui->m_searchWidget); - connect(m_ui->m_searchWidget->GetFilter().data(), &AssetBrowserEntryFilter::updatedSignal, m_filterModel.data(), &MaterialBrowserFilterModel::SearchFilterUpdated); - - // Call LoadState to initialize the AssetBrowserTreeView's QTreeViewStateSaver - // This must be done BEFORE StartRecordUpdateJobs(). A race condition from the update jobs was causing a 5-10% crash/hang when opening the Material Editor. - m_ui->treeView->SetName("MaterialBrowserTreeView"); - - // Override the AssetBrowserTreeView's custom context menu - disconnect(m_ui->treeView, &QWidget::customContextMenuRequested, 0, 0); - connect(m_ui->treeView, &QWidget::customContextMenuRequested, this, [=](const QPoint& point) - { - CMaterialBrowserRecord record; - TryGetSelectedRecord(record); - ShowContextMenu(record, point); - }); - - connect(m_ui->treeView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MaterialBrowserWidget::OnSelectionChanged); - //Wait for the signal emitted on record update jobs finished, then we can restore the selection for the previous selected item - connect(this, SIGNAL(refreshSelection()), this, SLOT(OnRefreshSelection())); - - connect(this, SIGNAL(materialAdded()), this, SLOT(OnMaterialAdded())); - - m_bIgnoreSelectionChange = false; - m_bItemsValid = true; - - m_pMatMan = GetIEditor()->GetMaterialManager(); - m_pMatMan->AddListener(this); - m_pListener = NULL; - - m_viewType = VIEW_LEVEL; - m_pMaterialImageListCtrl = NULL; - m_pLastActiveMultiMaterial = 0; - - m_bNeedReload = false; - - m_bHighlightMaterial = false; - m_timeOfHighlight = 0; - - m_bShowOnlyCheckedOut = false; - - GetIEditor()->RegisterNotifyListener(this); -} - -////////////////////////////////////////////////////////////////////////// -MaterialBrowserWidget::~MaterialBrowserWidget() -{ - m_filterModel->CancelRecordUpdateJobs(); - m_filterModel->deleteLater(); - m_ui->treeView->SaveState(); - GetIEditor()->UnregisterNotifyListener(this); - - m_pMaterialImageListCtrl = NULL; - m_pMatMan->RemoveListener(this); - ClearItems(); - - if (m_bHighlightMaterial) - { - m_pMatMan->SetHighlightedMaterial(0); - } - - MaterialBrowserWidgetBus::Handler::BusDisconnect(); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::ClearItems() -{ - m_bIgnoreSelectionChange = true; - - if (m_pMaterialImageListCtrl) - { - QMaterialImageListModel* materialModel = - qobject_cast(m_pMaterialImageListCtrl->model()); - Q_ASSERT(materialModel); - materialModel->DeleteAllItems(); - } - - m_pLastActiveMultiMaterial = nullptr; - m_delayedSelection = nullptr; - - m_bIgnoreSelectionChange = false; -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::TryLoadRecordMaterial(CMaterialBrowserRecord& record) -{ - // If material already loaded ignore. - if (record.m_material) - { - return; - } - - m_bIgnoreSelectionChange = true; - // Try to load material for it. - record.m_material = m_pMatMan->LoadMaterial(record.GetRelativeFilePath().c_str(), false); - - m_filterModel->SetRecord(record); - m_bIgnoreSelectionChange = false; -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::TickRefreshMaterials() -{ - if (m_bHighlightMaterial) - { - uint32 t = GetTickCount(); - if ((t - m_timeOfHighlight) > 300) - { - m_bHighlightMaterial = false; - m_pMatMan->SetHighlightedMaterial(0); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnIdleUpdate: - { - TickRefreshMaterials(); - } - break; - case eNotify_OnBeginLoad: - { - //Need to make sure the selection is cleared before clearing the record map - SetSelectedItem(nullptr, nullptr, true); - m_filterModel->ClearRecordMap(); - } - break; - case eNotify_OnCloseScene: - { - m_filterModel->ShowOnlyLevelMaterials(false, true); - ClearItems(); - m_ui->treeView->SaveState(); - //Need to make sure the selection is cleared before clearing the record map - SetSelectedItem(nullptr, nullptr, true); - m_filterModel->ClearRecordMap(); - } - break; - case eNotify_OnEndNewScene: - case eNotify_OnEndSceneOpen: - { - m_filterModel->ShowOnlyLevelMaterials(false, true); - m_filterModel->StartRecordUpdateJobs(); - if (m_ui->treeView->IsTreeViewSavingReady()) - { - m_ui->treeView->ApplyTreeViewSnapshot(); - } - } - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::SetSelectedItem(_smart_ptr material, const TMaterialBrowserRecords* pMarkedRecords, bool selectInTreeView) -{ - if (m_bIgnoreSelectionChange) - { - return; - } - - m_bIgnoreSelectionChange = true; - if (pMarkedRecords) - { - m_markedRecords = *pMarkedRecords; - } - else - { - m_markedRecords.clear(); - } - - m_pMatMan->SetCurrentFolder(""); - - _smart_ptr selectedMaterial = material; - if (material && material->IsPureChild()) - { - selectedMaterial = material->GetParent(); - } - - // Clear the delayed selection whenever a new material is selected - m_delayedSelection = nullptr; - - // In some cases, such as when SetSelectedItem is called from the material picker or the rollup bar, - // the material has not yet been selected in the tree-view, so that item must be selected here - bool validSelection = false; - if (selectInTreeView) - { - if (!selectedMaterial) - { - // Clear the current selection so that the upcoming call to RefreshSelected() - // doesn't try to refresh the previously selected material which may be invalid - m_ui->treeView->clearSelection(); - m_ui->treeView->setCurrentIndex(QModelIndex()); - } - else if (m_markedRecords.size() > 0) - { - QItemSelection selection; - for (CMaterialBrowserRecord record : m_markedRecords) - { - QModelIndex currentIndex = m_filterModel->GetIndexFromMaterial(record.m_material); - if (currentIndex.isValid()) - { - selection.push_back(QItemSelectionRange(currentIndex)); - validSelection = true; - } - } - m_ui->treeView->selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect); - } - else - { - QModelIndex currentIndex = m_filterModel->GetIndexFromMaterial(selectedMaterial); - if (currentIndex.isValid()) - { - m_ui->treeView->selectionModel()->setCurrentIndex(currentIndex, QItemSelectionModel::ClearAndSelect); - validSelection = true; - - // Now that the parent material is selected in the browser, - // select the appropriate sub-material in the material preview window - if (selectedMaterial == material->GetParent()) - { - for (int i = 0; i < selectedMaterial->GetSubMaterialCount(); ++i) - { - if (material == selectedMaterial->GetSubMaterial(i)) - { - m_selectedSubMaterialIndex = i; - break; - } - } - } - } - else - { - // Hold on to a pointer to this material, listen for the MaterialFinishedProcessing event, - // and attempt to re-select this material if it finishes processing in the background - m_delayedSelection = selectedMaterial; - } - } - } - - RefreshSelected(); - - if (!selectedMaterial) - { - QModelIndex current = m_ui->treeView->currentIndex(); - QString path; - while (current.isValid()) - { - path = '/' + current.data().toString() + path; - current = current.parent(); - } - m_pMatMan->SetCurrentFolder((Path::GetEditingGameDataFolder() + path.toUtf8().data()).c_str()); - } - else - { - if (selectedMaterial->IsMultiSubMaterial() && m_selectedSubMaterialIndex >= 0) - { - selectedMaterial = selectedMaterial->GetSubMaterial(m_selectedSubMaterialIndex); - } - } - - if (m_pListener) - { - // Don't call the listener event if we attempted to select an item in the tree view and failed - // to prevent the material parameter editor from switching to a new material if it wasn't actually selected - if (!selectInTreeView || validSelection) - { - m_pListener->OnBrowserSelectItem(selectedMaterial, false); - } - //Update the selected item if no material is selected in tree view - else if (!selectedMaterial && selectInTreeView) - { - m_pListener->OnBrowserSelectItem(nullptr, false); - } - } - - m_timeOfHighlight = GetTickCount(); - m_pMatMan->SetHighlightedMaterial(selectedMaterial); - if (selectedMaterial) - { - m_bHighlightMaterial = true; - } - - std::vector<_smart_ptr > markedMaterials; - if (pMarkedRecords) - { - for (size_t i = 0; i < pMarkedRecords->size(); ++i) - { - markedMaterials.push_back((*pMarkedRecords)[i].m_material); - } - } - m_pMatMan->SetMarkedMaterials(markedMaterials); - - m_bIgnoreSelectionChange = false; -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::SelectItem(IDataBaseItem* pItem, [[maybe_unused]] IDataBaseItem* pParentItem) -{ - if (m_bIgnoreSelectionChange) - { - return; - } - - if (!pItem) - { - return; - } - - _smart_ptr material = static_cast(pItem); - SetSelectedItem(material, 0, true); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnDuplicate() -{ - GetIEditor()->GetMaterialManager()->Command_Merge(); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnCut() -{ - CMaterialBrowserRecord record; - bool found = TryGetSelectedRecord(record); - if (found) - { - OnCopy(); - DeleteItem(record); - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnCopyName() -{ - _smart_ptr pMtl = GetCurrentMaterial(); - if (pMtl) - { - CClipboard clipboard(this); - clipboard.PutString(pMtl->GetName(), "Material Name"); - } -} - -void MaterialBrowserWidget::ShowOnlyLevelMaterials(bool levelOnly) -{ - m_filterModel->ShowOnlyLevelMaterials(levelOnly); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnCopy() -{ - _smart_ptr pMtl = GetCurrentMaterial(); - if (pMtl) - { - CClipboard clipboard(this); - XmlNodeRef node = XmlHelpers::CreateXmlNode("Material"); - node->setAttr("Name", pMtl->GetName().toUtf8().data()); - CBaseLibraryItem::SerializeContext ctx(node, false); - ctx.bCopyPaste = true; - pMtl->Serialize(ctx); - clipboard.Put(node); - } -} - -////////////////////////////////////////////////////////////////////////// -bool MaterialBrowserWidget::CanPaste() const -{ - CClipboard clipboard(nullptr); - if (clipboard.IsEmpty()) - { - return false; - } - XmlNodeRef node = clipboard.Get(); - if (!node) - { - return false; - } - - if (strcmp(node->getTag(), "Material") == 0) - { - return true; - } - return false; -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnPaste() -{ - CClipboard clipboard(this); - if (clipboard.IsEmpty()) - { - return; - } - XmlNodeRef node = clipboard.Get(); - if (!node) - { - return; - } - - if (strcmp(node->getTag(), "Material") == 0) - { - if (!m_pMatMan->GetCurrentMaterial()) - { - GetIEditor()->GetMaterialManager()->Command_Create(); - } - - _smart_ptr pMtl = m_pMatMan->GetCurrentMaterial(); - if (pMtl) - { - // This is material node. - CBaseLibraryItem::SerializeContext serCtx(node, true); - serCtx.bCopyPaste = true; - serCtx.bUniqName = true; - pMtl->Serialize(serCtx); - - SelectItem(pMtl, NULL); - pMtl->Save(); - pMtl->Reload(); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnAddNewMaterial() -{ - GetIEditor()->GetMaterialManager()->Command_Create(); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnAddNewMultiMaterial() -{ - GetIEditor()->GetMaterialManager()->Command_CreateMulti(); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnMergeMaterials() -{ - GetIEditor()->GetMaterialManager()->Command_Merge(); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnConvertToMulti() -{ - GetIEditor()->GetMaterialManager()->Command_ConvertToMulti(); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::DeleteItem() -{ - CMaterialBrowserRecord record; - bool found = TryGetSelectedRecord(record); - if (found) - { - DeleteItem(record); - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnResetItem() -{ - if (QMessageBox::question(this, tr("Reset Material"), tr("Reset Material to default?")) == QMessageBox::Yes) - { - _smart_ptr pMtl = GetCurrentMaterial(); - int index; - - pMtl->GetSubMaterialCount() > 0 ? index = pMtl->GetSubMaterialCount() : index = 1; - - if (pMtl) - { - for (int i = 0; i < index; i++) - { - pMtl->GetSubMaterialCount() > 0 ? pMtl->GetSubMaterial(i)->Reload() : pMtl->Reload(); - TickRefreshMaterials(); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::DeleteItem(const CMaterialBrowserRecord& record) -{ - _smart_ptr pMtl = record.m_material; - if (pMtl) - { - if (m_selectedSubMaterialIndex >= 0) - { - pMtl = pMtl->GetSubMaterial(m_selectedSubMaterialIndex); - OnClearSubMtlSlot(pMtl); - } - else - { - GetIEditor()->GetMaterialManager()->Command_Delete(); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnRenameItem() -{ - _smart_ptr pMtl = GetCurrentMaterial(); - if (!pMtl) - { - return; - } - - if (pMtl->IsPureChild()) - { - StringDlg dlg(tr("Enter New Sub-Material Name"), this); - dlg.SetString(pMtl->GetName()); - dlg.SetCheckCallback([this](QString name) -> bool - { - static const int MAX_REASONABLE_MATERIAL_NAME = 128; - if (name.length() >= MAX_REASONABLE_MATERIAL_NAME) - { - QMessageBox::warning(this, tr("Name too long"), tr("Please enter a name less than %1 characters").arg(MAX_REASONABLE_MATERIAL_NAME)); - return false; - } - return true; - }); - - if (dlg.exec() == QDialog::Accepted) - { - pMtl->SetName(dlg.GetString()); - pMtl->Save(); - pMtl->Reload(); - } - } - else - { - if ((pMtl->GetFileAttributes() & SCC_FILE_ATTRIBUTE_MANAGED) && - !(pMtl->GetFileAttributes() & SCC_FILE_ATTRIBUTE_CHECKEDOUT)) - { - if (QMessageBox::Cancel == QMessageBox::information(this, tr("Confirm"), tr("Only checked-out files can be renamed. Check out and mark for delete before rename it?"), QMessageBox::Ok | QMessageBox::Cancel)) - { - return; - } - } - - QFileInfo info(pMtl->GetFilename()); - QString filename = info.fileName(); - if (!CFileUtil::SelectSaveFile("Material Files (*.mtl)", "mtl", info.path(), filename)) - { - return; - } - - QString itemName = m_pMatMan->FilenameToMaterial(Path::GetRelativePath(filename)); - if (itemName.isEmpty()) - { - return; - } - - if (m_pMatMan->FindItemByName(itemName)) - { - Warning("Material with name %s already exist", itemName.toUtf8().data()); - return; - } - - if (pMtl->GetFileAttributes() & SCC_FILE_ATTRIBUTE_MANAGED) - { - if (pMtl->GetFileAttributes() & SCC_FILE_ATTRIBUTE_CHECKEDOUT) - { - if (QMessageBox::Cancel == QMessageBox::information(this, tr("Confirm"), tr("The original file will be marked for delete and the new named file will be marked for integration."), QMessageBox::Ok | QMessageBox::Cancel)) - { - return; - } - } - else - { - CFileUtil::CheckoutFile(pMtl->GetFilename().toUtf8().data(), this); - } - - if (!CFileUtil::RenameFile(pMtl->GetFilename().toUtf8().data(), filename.toUtf8().data())) - { - QMessageBox::critical(this, tr("Error"), tr("Could not rename file in Source Control.")); - } - } - - - // Delete file on disk. - if (!pMtl->GetFilename().isEmpty()) - { - QFile::remove(pMtl->GetFilename()); - } - pMtl->SetName(itemName); - pMtl->Save(); - SetSelectedItem(pMtl, 0, true); - } -} - - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnSetSubMtlCount(const CMaterialBrowserRecord& record) -{ - _smart_ptr pMtl = record.m_material; - if (!pMtl) - { - return; - } - - if (!pMtl->IsMultiSubMaterial()) - { - return; - } - - int num = pMtl->GetSubMaterialCount(); - bool ok = false; - num = QInputDialog::getInt(this, tr("Number of Sub Materials"), QStringLiteral(""), num, 0, MAX_SUB_MATERIALS, 1, &ok); - if (ok) - { - if (num != pMtl->GetSubMaterialCount()) - { - if (m_selectedSubMaterialIndex >= num) - { - m_selectedSubMaterialIndex = num - 1; - } - - CUndo undo("Set SubMtl Count"); - pMtl->SetSubMaterialCount(num); - - for (int i = 0; i < num; i++) - { - if (pMtl->GetSubMaterial(i) == 0) - { - // Allocate pure childs for all empty slots. - QString name; - name = QStringLiteral("SubMtl%1").arg(i + 1); - _smart_ptr pChild = new CMaterial(name, MTL_FLAG_PURE_CHILD); - pMtl->SetSubMaterial(i, pChild); - } - } - } - } -} - - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::DoSourceControlOp(CMaterialBrowserRecord& record, ESourceControlOp scmOp) -{ - if (!GetIEditor()->IsSourceControlAvailable()) - { - return; - } - - _smart_ptr pMtl = record.m_material; - - if (pMtl && pMtl->IsPureChild()) - { - pMtl = pMtl->GetParent(); - } - - if (scmOp == ESCM_IMPORT) // don't save unless you're doing an operation which writes. - { - if (pMtl && pMtl->IsModified()) - { - pMtl->Save(); - } - } - - QString path = pMtl ? pMtl->GetFilename() : QString(); - - if (path.isEmpty()) - { - return; - } - - bool bRes = true; - switch (scmOp) - { - case ESCM_IMPORT: - if (pMtl) - { - QStringList filenames; - int nTextures = pMtl->GetTextureFilenames(filenames); - for (int i = 0; i < nTextures; ++i) - { - CFileUtil::CheckoutFile(filenames[i].toUtf8().data(), this); - } - - bRes = CFileUtil::CheckoutFile(path.toUtf8().data(), this); - } - break; - case ESCM_CHECKOUT: - { - if (pMtl && (pMtl->GetFileAttributes() & SCC_FILE_ATTRIBUTE_BYANOTHER)) - { - AZStd::string otherUser("another user"); - AzToolsFramework::SourceControlFileInfo fileInfo; - if (CFileUtil::GetFileInfoFromSourceControl(pMtl->GetFilename().toUtf8().data(), fileInfo, this)) - { - // Sanity check the source control api reports the file is checked out by another - AZ_Assert(fileInfo.HasFlag(AzToolsFramework::SCF_OtherOpen), "File attributes reporting incorrectly"); - otherUser = fileInfo.m_StatusUser; - } - - if (QMessageBox::question(this, QString(), tr("This file is checked out by %1. Try to continue?").arg(otherUser.c_str())) != QMessageBox::Yes) - { - return; - } - } - bRes = CFileUtil::GetLatestFromSourceControl(path.toUtf8().data(), this); - if (bRes) - { - bRes = CFileUtil::CheckoutFile(path.toUtf8().data(), this); - } - } - break; - case ESCM_UNDO_CHECKOUT: - bRes = CFileUtil::RevertFile(path.toUtf8().data(), this); - break; - case ESCM_GETLATEST: - bRes = CFileUtil::GetLatestFromSourceControl(path.toUtf8().data(), this); - break; - case ESCM_GETLATESTTEXTURES: - if (pMtl) - { - QString message; - QStringList filenames; - int nTextures = pMtl->GetTextureFilenames(filenames); - for (int i = 0; i < nTextures; ++i) - { - bRes = CFileUtil::GetLatestFromSourceControl(filenames[i].toUtf8().data(), this); - message += Path::GetRelativePath(filenames[i], true) + (bRes ? " [OK]" : " [Fail]") + "\n"; - } - QMessageBox::information(this, QString(), message.isEmpty() ? tr("No files are affected") : message); - } - return; - } - - if (!bRes) - { - QMessageBox::critical(this, tr("Error"), tr("Source Control Operation Failed.\r\nCheck if Source Control Provider correctly setup and working directory is correct.")); - return; - } - - // force the cache to be rebuilt next time we repaint - record.InitializeSourceControlAttributes(); - m_filterModel->SetRecord(record); - - if (pMtl) - { - pMtl->Reload(); - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnMakeSubMtlSlot(const CMaterialBrowserRecord& record) -{ - if (m_selectedSubMaterialIndex >= 0) - { - _smart_ptr parentMaterial = record.m_material; - if (parentMaterial && parentMaterial->IsMultiSubMaterial()) - { - const QString str = tr("Making new material will override material currently assigned to the slot %1 of %2\r\nMake new sub material?") - .arg(m_selectedSubMaterialIndex).arg(parentMaterial->GetName()); - if (QMessageBox::question(this, tr("Confirm Override"), str) == QMessageBox::Yes) - { - QString name = tr("SubMtl%1") - .arg(m_selectedSubMaterialIndex + 1); - _smart_ptr pMtl = new CMaterial(name, MTL_FLAG_PURE_CHILD); - parentMaterial->SetSubMaterial(m_selectedSubMaterialIndex, pMtl); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnClearSubMtlSlot(_smart_ptr subMaterial) -{ - if (subMaterial && m_selectedSubMaterialIndex >= 0) - { - _smart_ptr parentMaterial = subMaterial->GetParent(); - if (parentMaterial && parentMaterial->IsMultiSubMaterial()) - { - const QString str = tr("Clear Sub-Material Slot %1 of %2?").arg(m_selectedSubMaterialIndex).arg(parentMaterial->GetName()); - if (QMessageBox::question(this, tr("Clear Sub-Material"), str) == QMessageBox::Yes) - { - CUndo undo("Material Change"); - SetSubMaterial(parentMaterial, m_selectedSubMaterialIndex, 0); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::SetSubMaterial(_smart_ptr parentMaterial, int slot, _smart_ptr subMaterial) -{ - if (parentMaterial && parentMaterial->IsMultiSubMaterial()) - { - // If the last sub-material is being removed, select the 2nd to last sub-material - if (!subMaterial && slot == parentMaterial->GetSubMaterialCount() - 1) - { - m_selectedSubMaterialIndex = slot - 1; - } - parentMaterial->SetSubMaterial(slot, subMaterial); - } -} - - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnDataBaseItemEvent(IDataBaseItem* pItem, EDataBaseItemEvent event) -{ - if (m_bIgnoreSelectionChange) - { - return; - } - - if (!pItem) - { - return; - } - - - switch (event) - { - case EDB_ITEM_EVENT_ADD: - break; - case EDB_ITEM_EVENT_DELETE: - { - if (pItem) - { - //If the deleted item is selected, remove selection - CMaterial* pMtl = static_cast(pItem); - CMaterial* selectedMaterial = GetCurrentMaterial(); - if (selectedMaterial && selectedMaterial->IsPureChild()) - { - selectedMaterial = selectedMaterial->GetParent(); - } - if (pMtl == selectedMaterial) - { - SetSelectedItem(nullptr, nullptr, true); - } - } - } - break; - case EDB_ITEM_EVENT_CHANGED: - { - CMaterial* pMtl = static_cast(pItem); - CMaterial* selectedMaterial = GetCurrentMaterial(); - if (selectedMaterial && selectedMaterial->IsPureChild()) - { - selectedMaterial = selectedMaterial->GetParent(); - } - // If this is a sub material, refresh parent - if (pMtl->IsPureChild()) - { - pMtl = pMtl->GetParent(); - } - - if (pMtl == selectedMaterial) - { - if (pMtl->IsMultiSubMaterial()) - { - m_pLastActiveMultiMaterial = NULL; - } - RefreshSelected(); - } - m_bItemsValid = false; - } - break; - case EDB_ITEM_EVENT_SELECTED: - { - SelectItem(pItem, NULL); - } - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::SetImageListCtrl(CMaterialImageListCtrl* pCtrl) -{ - m_pMaterialImageListCtrl = pCtrl; - if (m_pMaterialImageListCtrl) - { - connect(m_pMaterialImageListCtrl->selectionModel(), &QItemSelectionModel::currentChanged, - this, &MaterialBrowserWidget::OnSubMaterialSelectedInPreviewPane); - - connect(m_pMaterialImageListCtrl, &QAbstractItemView::clicked, - this, &MaterialBrowserWidget::OnSubMaterialSelectedInPreviewPane); - - m_pMaterialImageListCtrl->SetMaterialBrowserWidget(this); - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnSaveToFile(bool bMulti) -{ - _smart_ptr pCurrentMaterial = GetCurrentMaterial(); - if (pCurrentMaterial) - { - QString startPath = GetIEditor()->GetSearchPath(EDITOR_PATH_MATERIALS); - QString filename; - if (!CFileUtil::SelectSaveFile("Material Files (*.mtl)", "mtl", startPath, filename)) - { - return; - } - QFileInfo info(filename); - QString itemName = info.baseName(); - itemName = Path::MakeGamePath(itemName); - - if (m_pMatMan->FindItemByName(itemName)) - { - Warning("Material with name %s already exist", itemName.toUtf8().data()); - return; - } - int flags = pCurrentMaterial->GetFlags(); - if (bMulti) - { - flags |= MTL_FLAG_MULTI_SUBMTL; - } - - pCurrentMaterial->SetFlags(flags); - - if (pCurrentMaterial->IsDummy()) - { - pCurrentMaterial->ClearMatInfo(); - pCurrentMaterial->SetDummy(false); - } - pCurrentMaterial->SetModified(true); - pCurrentMaterial->Save(); - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::RefreshSelected() -{ - CMaterialBrowserRecord record; - bool found = TryGetSelectedRecord(record); - _smart_ptr pMtl = nullptr; - if (!found) - { - ClearImageListControlSelection(); - return; - } - else - { - pMtl = record.m_material; - } - - if (m_pMaterialImageListCtrl) - { - QMaterialImageListModel* materialModel = - qobject_cast(m_pMaterialImageListCtrl->model()); - Q_ASSERT(materialModel); - - materialModel->InvalidateMaterial(pMtl); - if (pMtl) - { - _smart_ptr pMultiMtl = nullptr; - if (pMtl->IsMultiSubMaterial()) - { - // It's possible that the currently selected sub-material index is beyond the range of the current multi-material if, for example, - // the last sub-material was selected but then the source .mtl file was changed to have fewer total sub-materials - if (m_selectedSubMaterialIndex >= pMtl->GetSubMaterialCount()) - { - // If that's the case, select the last sub-material - // If the sub-material count has dropped to 0, setting m_selectedSubMaterialIndex to -1 will cause the parent material to be selected - m_selectedSubMaterialIndex = pMtl->GetSubMaterialCount() - 1; - } - - pMultiMtl = pMtl; - if (m_selectedSubMaterialIndex >= 0) - { - pMtl = pMtl->GetSubMaterial(m_selectedSubMaterialIndex); - } - } - - if (m_pLastActiveMultiMaterial != pMultiMtl || pMultiMtl == nullptr) - { - // A new material was selected, so the previewer needs to be cleared - materialModel->DeleteAllItems(); - // If the new material was not a multi-material, add it to the previewer - if (pMultiMtl == nullptr) - { - materialModel->AddMaterial(pMtl); - } - } - - // If a new multi-material was selected - if (m_pLastActiveMultiMaterial != pMultiMtl && pMultiMtl != nullptr) - { - // Add all of its submaterials to the previewer - for (size_t i = 0; i < pMultiMtl->GetSubMaterialCount(); i++) - { - if (pMultiMtl->GetSubMaterial(i)) - { - materialModel->AddMaterial(pMultiMtl->GetSubMaterial(i), reinterpret_cast(i)); - } - } - m_pMaterialImageListCtrl->selectionModel()->clear(); - - // If a sub-material was selected in the material browser, select it in the previewer - QModelIndex modelIndex; - if (m_selectedSubMaterialIndex >= 0) - { - modelIndex = materialModel->index(m_selectedSubMaterialIndex, 0); - } - m_pMaterialImageListCtrl->selectionModel()->select(modelIndex, QItemSelectionModel::SelectCurrent); - } - - m_pMaterialImageListCtrl->SelectMaterial(pMtl); - m_pLastActiveMultiMaterial = pMultiMtl; - } - else - { - ClearSelection(materialModel); - } - } -} - -void MaterialBrowserWidget::ClearImageListControlSelection() -{ - QMaterialImageListModel* materialModel = - qobject_cast(m_pMaterialImageListCtrl->model()); - Q_ASSERT(materialModel); - - ClearSelection(materialModel); -} - -void MaterialBrowserWidget::ClearSelection(QMaterialImageListModel* materialModel) -{ - materialModel->DeleteAllItems(); - m_pLastActiveMultiMaterial = nullptr; -} - -////////////////////////////////////////////////////////////////////////// - -void MaterialBrowserWidget::AddContextMenuActionsMultiSelect(QMenu& menu) const -{ - int numMaterialsSelected = 0; - for (int i = 0; i < m_markedRecords.size(); ++i) - { - if (m_markedRecords[i].m_material) - { - ++numMaterialsSelected; - } - } - const QString itemsSelected = tr(" (%1 Materials Selected)").arg(numMaterialsSelected); - menu.addAction(itemsSelected)->setEnabled(false); - menu.addSeparator(); - - if (numMaterialsSelected >= 2) // ... and at least two materials - { - menu.addAction(tr("Merge"))->setData(MENU_MERGE); - } - else - { - menu.addAction(tr("Merge (Select two or more)"))->setEnabled(false); - } -} - -void MaterialBrowserWidget::AddContextMenuActionsNoSelection(QMenu& menu) const -{ - QAction* action = menu.addAction(tr("Paste")); - action->setShortcut(QKeySequence::Paste); - action->setData(MENU_PASTE); - action->setEnabled(CanPaste()); - - menu.addSeparator(); - menu.addAction(tr("Add New Material"))->setData(MENU_ADDNEW); - menu.addAction(tr("Add New Multi Material"))->setData(MENU_ADDNEW_MULTI); - if (GetIEditor()->IsSourceControlAvailable()) - { - menu.addSeparator(); - menu.addAction(tr("Source Control"))->setEnabled(false); - menu.addAction(tr("Check Out"))->setData(MENU_SCM_CHECK_OUT); - menu.addAction(tr("Undo Check Out"))->setData(MENU_SCM_UNDO_CHECK_OUT); - menu.addAction(tr("Get Latest Version"))->setData(MENU_SCM_GET_LATEST); - } -} - -void MaterialBrowserWidget::AddContextMenuActionsSingleSelection(QMenu& menu, _smart_ptr material) const -{ - if (material) - { - if (material->IsMultiSubMaterial()) - { - if (m_selectedSubMaterialIndex >= 0) - { - AddContextMenuActionsSubMaterial(menu, material, material->GetSubMaterial(m_selectedSubMaterialIndex)); - } - else - { - AddContextMenuActionsMultiMaterial(menu); - AddContextMenuActionsCommon(menu, material); - } - } - else if (material->IsPureChild()) - { - AddContextMenuActionsSubMaterial(menu, material->GetParent(), material); - } - else - { - AddContextMenuActionsSingleMaterial(menu); - AddContextMenuActionsCommon(menu, material); - } - } -} - -void MaterialBrowserWidget::AddContextMenuActionsSubMaterial(QMenu& menu, _smart_ptr parentMaterial, _smart_ptr subMaterial) const -{ - bool enabled = true; - - if (parentMaterial) - { - uint32 nFileAttr = parentMaterial->GetFileAttributes(); - if (nFileAttr & SCC_FILE_ATTRIBUTE_READONLY) - { - enabled = false; - } - } - - QAction* action = menu.addAction(tr("Reset sub-material to default")); - action->setData(MENU_SUBMTL_MAKE); - action->setEnabled(enabled); - - menu.addSeparator(); - - action = menu.addAction(tr("Cut")); - action->setShortcut(QKeySequence::Cut); - action->setData(MENU_CUT); - action->setEnabled(enabled); - - action = menu.addAction(tr("Copy")); - action->setShortcut(QKeySequence::Copy); - action->setData(MENU_COPY); - - action = menu.addAction(tr("Paste")); - action->setShortcut(QKeySequence::Paste); - action->setData(MENU_PASTE); - action->setEnabled(CanPaste() && enabled); - - action = menu.addAction(tr("Rename\tF2")); - action->setData(MENU_RENAME); - action->setEnabled(enabled); - - action = menu.addAction(tr("Delete")); - action->setData(MENU_SUBMTL_CLEAR); - action->setEnabled(enabled); -} - -void MaterialBrowserWidget::AddContextMenuActionsMultiMaterial(QMenu& menu) const -{ - menu.addAction(tr("Set Number of Sub-Materials"))->setData(MENU_NUM_SUBMTL); - menu.addSeparator(); -} - -void MaterialBrowserWidget::AddContextMenuActionsSingleMaterial(QMenu& menu) const -{ - menu.addAction(tr("Convert To Multi Material"))->setData(MENU_CONVERT_TO_MULTI); - menu.addSeparator(); -} - -void MaterialBrowserWidget::AddContextMenuActionsCommon(QMenu& menu, _smart_ptr material) const -{ - uint32 fileAttributes = material->GetFileAttributes(); - - bool modificationsEnabled = true; - if (fileAttributes & SCC_FILE_ATTRIBUTE_READONLY) - { - modificationsEnabled = false; - } - - QAction* action = menu.addAction(tr("Cut")); - action->setShortcut(QKeySequence::Cut); - action->setData(MENU_CUT); - action = menu.addAction(tr("Copy")); - action->setShortcut(QKeySequence::Copy); - action->setData(MENU_COPY); - action = menu.addAction(tr("Paste")); - action->setShortcut(QKeySequence::Paste); - action->setData(MENU_PASTE); - action->setEnabled(CanPaste() && modificationsEnabled); - menu.addAction(tr("Copy Path to Clipboard"))->setData(MENU_COPY_NAME); - if (fileAttributes & SCC_FILE_ATTRIBUTE_INPAK) - { - menu.addAction(tr("Extract"))->setData(MENU_EXTRACT); - } - else - { - menu.addAction(tr("Explore"))->setData(MENU_EXPLORE); - } - menu.addSeparator(); - action = menu.addAction(tr("Duplicate")); - action->setShortcut(tr("Ctrl+D")); - action->setData(MENU_DUPLICATE); - menu.addAction(tr("Rename\tF2"))->setData(MENU_RENAME); - action = menu.addAction(tr("Delete")); - action->setShortcut(QKeySequence::Delete); - action->setData(MENU_DELETE); - menu.addSeparator(); - menu.addAction(tr("Assign to Selected Objects"))->setData(MENU_ASSIGNTOSELECTION); - menu.addAction(tr("Select Assigned Objects"))->setData(MENU_SELECTASSIGNEDOBJECTS); - menu.addSeparator(); - - menu.addAction(tr("Add New Material"))->setData(MENU_ADDNEW); - menu.addAction(tr("Add New Multi Material"))->setData(MENU_ADDNEW_MULTI); - menu.addAction(tr("Merge (Select two or more)"))->setEnabled(false); - - AddContextMenuActionsSourceControl(menu, material, fileAttributes); -} - -void MaterialBrowserWidget::AddContextMenuActionsSourceControl(QMenu& menu, _smart_ptr material, uint32 fileAttributes) const -{ - if (GetIEditor()->IsSourceControlAvailable()) - { - menu.addSeparator(); - - if (fileAttributes & SCC_FILE_ATTRIBUTE_INPAK) - { - menu.addAction(tr(" Material In Pak (Read Only)"))->setEnabled(false); - } - else - { - menu.addAction(tr(" Source Control"))->setEnabled(false); - if (!(fileAttributes & SCC_FILE_ATTRIBUTE_MANAGED)) - { - menu.addAction(tr("Add To Source Control"))->setData(MENU_SCM_ADD); - } - } - QAction* action = nullptr; - if (fileAttributes & SCC_FILE_ATTRIBUTE_MANAGED) - { - action = menu.addAction(tr("Check Out")); - action->setData(MENU_SCM_CHECK_OUT); - action->setEnabled(fileAttributes & SCC_FILE_ATTRIBUTE_READONLY || fileAttributes & SCC_FILE_ATTRIBUTE_INPAK); - action = menu.addAction(tr("Undo Check Out")); - action->setData(MENU_SCM_UNDO_CHECK_OUT); - action->setEnabled(fileAttributes & SCC_FILE_ATTRIBUTE_CHECKEDOUT); - menu.addAction(tr("Get Latest Version"))->setData(MENU_SCM_GET_LATEST); - } - - if (material) - { - QStringList filenames; - int nTextures = material->GetTextureFilenames(filenames); - action = menu.addAction(tr("Get Textures")); - action->setData(MENU_SCM_GET_LATEST_TEXTURES); - action->setEnabled(nTextures > 0); - } - } -} - -void MaterialBrowserWidget::ShowContextMenu(const CMaterialBrowserRecord& record, const QPoint& point) -{ - _smart_ptr material = record.m_material; - - // Create pop up menu. - QMenu menu; - if (m_markedRecords.size() >= 2) // it makes sense when we have at least two items selected - { - AddContextMenuActionsMultiSelect(menu); - } - else if (!material) // click on root, background or folder - { - AddContextMenuActionsNoSelection(menu); - } - else - { - // When right-clicking a single item in the material browser, select the parent material that was clicked, rather than the currently selected sub-material - // The context menu for sub-materials will be handled by the image list control rather than the material browser widget - m_selectedSubMaterialIndex = -1; - SetSelectedItem(material, nullptr, true); - AddContextMenuActionsSingleSelection(menu, material); - } - QAction* action = menu.exec(m_ui->treeView->mapToGlobal(point)); - const int cmd = action ? action->data().toInt() : 0; - - OnContextMenuAction(cmd, material); -} - -void MaterialBrowserWidget::OnContextMenuAction(int command, _smart_ptr material) -{ - CMaterialBrowserRecord record; - TryGetSelectedRecord(record); - switch (command) - { - case MENU_UNDEFINED: - return; // do nothing - case MENU_CUT: - OnCut(); - break; - case MENU_COPY: - OnCopy(); - break; - case MENU_COPY_NAME: - OnCopyName(); - break; - case MENU_PASTE: - OnPaste(); - break; - case MENU_EXPLORE: - { - if (material && material->IsPureChild()) - { - material = material->GetParent(); - } - - if (material) - { - QString fullPath = material->GetFilename(); - AzQtComponents::ShowFileOnDesktop(fullPath); - } - } - break; - case MENU_EXTRACT: - { - if (material && material->IsPureChild()) - { - material = material->GetParent(); - } - - if (material) - { - QString fullPath = material->GetFilename(); - if (CFileUtil::ExtractFile(fullPath, true, fullPath.toUtf8().data())) - { - AzQtComponents::ShowFileOnDesktop(fullPath); - } - } - } - break; - case MENU_DUPLICATE: - OnDuplicate(); - break; - case MENU_RENAME: - OnRenameItem(); - break; - case MENU_DELETE: - DeleteItem(record); - break; - case MENU_RESET: - OnResetItem(); - break; - case MENU_ASSIGNTOSELECTION: - { - CUndo undo("Assign Material To Selection"); - GetIEditor()->GetMaterialManager()->Command_AssignToSelection(); - break; - } - case MENU_SELECTASSIGNEDOBJECTS: - { - CUndo undo("Select Objects With Current Material"); - GetIEditor()->GetMaterialManager()->Command_SelectAssignedObjects(); - break; - } - case MENU_NUM_SUBMTL: - OnSetSubMtlCount(record); - break; - case MENU_ADDNEW: - OnAddNewMaterial(); - break; - case MENU_ADDNEW_MULTI: - OnAddNewMultiMaterial(); - break; - case MENU_CONVERT_TO_MULTI: - OnConvertToMulti(); - break; - case MENU_MERGE: - OnMergeMaterials(); - break; - - case MENU_SUBMTL_MAKE: - OnMakeSubMtlSlot(record); - break; - case MENU_SUBMTL_CLEAR: - OnClearSubMtlSlot(material); - break; - - case MENU_SCM_ADD: - DoSourceControlOp(record, ESCM_IMPORT); - break; - case MENU_SCM_CHECK_OUT: - DoSourceControlOp(record, ESCM_CHECKOUT); - break; - case MENU_SCM_UNDO_CHECK_OUT: - DoSourceControlOp(record, ESCM_UNDO_CHECKOUT); - break; - case MENU_SCM_GET_LATEST: - DoSourceControlOp(record, ESCM_GETLATEST); - break; - case MENU_SCM_GET_LATEST_TEXTURES: - DoSourceControlOp(record, ESCM_GETLATESTTEXTURES); - break; - - case MENU_SAVE_TO_FILE: - OnSaveToFile(false); - break; - case MENU_SAVE_TO_FILE_MULTI: - OnSaveToFile(true); - break; - //case MENU_MAKE_SUBMTL: OnAddNewMultiMaterial(); break; - } -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::PopulateItems() -{ - if (m_bIgnoreSelectionChange) - { - return; - } - - if (m_bItemsValid) - { - return; - } - - m_bItemsValid = true; - m_bIgnoreSelectionChange = true; - - IDataBaseItem* pSelection = m_pMatMan->GetSelectedItem(); - IDataBaseItem* pSelectionParent = m_pMatMan->GetSelectedParentItem(); - - m_bIgnoreSelectionChange = false; - - if (pSelection) - { - SelectItem(pSelection, pSelectionParent); - if (m_bHighlightMaterial) - { - m_bHighlightMaterial = false; - m_pMatMan->SetHighlightedMaterial(0); - } - } -} - -void MaterialBrowserWidget::StartRecordUpdateJobs() -{ - m_filterModel->StartRecordUpdateJobs(); -} - -////////////////////////////////////////////////////////////////////////// -uint32 MaterialBrowserWidget::MaterialNameToCrc32(const QString& str) -{ - return CCrc32::ComputeLowercase(str.toUtf8()); -} - -////////////////////////////////////////////////////////////////////////// -bool MaterialBrowserWidget::TryGetSelectedRecord(CMaterialBrowserRecord& record) -{ - QVariant variant = m_filterModel->data(m_ui->treeView->currentIndex(), Qt::UserRole); - if (variant.isValid()) - { - record = variant.value(); - return true; - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -_smart_ptr MaterialBrowserWidget::GetCurrentMaterial() -{ - CMaterialBrowserRecord record; - bool found = TryGetSelectedRecord(record); - if (found && record.m_material) - { - if (record.m_material->IsMultiSubMaterial() && m_selectedSubMaterialIndex >= 0) - { - return record.m_material->GetSubMaterial(m_selectedSubMaterialIndex); - } - else - { - return record.m_material; - } - } - - return m_pMatMan->GetCurrentMaterial(); -} - -////////////////////////////////////////////////////////////////////////// -AZStd::string MaterialBrowserWidget::GetSelectedMaterialID() -{ - CMaterialBrowserRecord record; - bool found = TryGetSelectedRecord(record); - if (found) - { - return record.GetRelativeFilePath(); - } - return AZStd::string(); -} - -////////////////////////////////////////////////////////////////////////// -void MaterialBrowserWidget::OnSelectionChanged() -{ - m_selectedSubMaterialIndex = -1; - TMaterialBrowserRecords markedRecords; - - CMaterialBrowserRecord record; - bool found = TryGetSelectedRecord(record); - for (const QModelIndex& row : m_ui->treeView->selectionModel()->selectedRows()) - { - QVariant userRole = row.data(Qt::UserRole); - if (userRole.isValid()) - { - CMaterialBrowserRecord currentRecord = userRole.value(); - markedRecords.push_back(currentRecord); - } - } - - if (!found && !markedRecords.empty()) - { - record = markedRecords.front(); - found = true; - } - if (found) - { - // Since the call to SetSelectedItem is coming from an OnSelectionChanged event, the appropriate - // element of the tree view has already been selected. Pass in false for the selectInTreeView argument - // to prevent SetSelectedItem from trying to re-select the material in the browser - SetSelectedItem(record.m_material, &markedRecords, false); - } -} - -void MaterialBrowserWidget::OnRefreshSelection() -{ - // force RefreshSelected to repopulate by setting m_pLastActiveMultiMaterial to null - // so it thinks we selected a new material. - m_pLastActiveMultiMaterial = nullptr; - - //If no material is selected, clear preview. - if (!GetCurrentMaterial()) - { - if (m_pMaterialImageListCtrl) - { - QMaterialImageListModel* materialModel = - qobject_cast(m_pMaterialImageListCtrl->model()); - Q_ASSERT(materialModel); - materialModel->DeleteAllItems(); - } - } - - RefreshSelected(); - - // Force update the material dialog - if (m_pListener) - { - m_pListener->OnBrowserSelectItem(GetCurrentMaterial(), true); - } -} - -void MaterialBrowserWidget::OnMaterialAdded() -{ - if (m_delayedSelection) - { - SetSelectedItem(m_delayedSelection, nullptr, true); - - // Force update the material dialog - if (m_pListener) - { - m_pListener->OnBrowserSelectItem(GetCurrentMaterial(), true); - } - } -} - -void MaterialBrowserWidget::OnSubMaterialSelectedInPreviewPane(const QModelIndex& current) -{ - if (!m_pMaterialImageListCtrl) - { - return; - } - - QMaterialImageListModel* materialModel = - qobject_cast(m_pMaterialImageListCtrl->model()); - Q_ASSERT(materialModel); - - int nSlot = (INT_PTR)materialModel->UserDataFromIndex(current); - if (nSlot < 0) - { - return; - } - - CMaterialBrowserRecord record; - bool found = TryGetSelectedRecord(record); - if (!found || !record.m_material) - { - return; - } - - if (!record.m_material->IsMultiSubMaterial()) - { - return; // must be multi sub material. - } - if (nSlot >= record.m_material->GetSubMaterialCount()) - { - return; - } - - if (nSlot == m_selectedSubMaterialIndex) - { - return; - } - - m_selectedSubMaterialIndex = nSlot; - - SetSelectedItem(record.m_material, nullptr, false); -} - -void MaterialBrowserWidget::SaveCurrentMaterial() -{ - // Saving might open a modal dialog asking to overwrite, therefore don't run this from DTOR, might crash - - _smart_ptr pCurrentMtl = GetCurrentMaterial(); - if (pCurrentMtl && pCurrentMtl->IsModified()) - { - pCurrentMtl->Save(); - } -} - -void MaterialBrowserWidget::expandAllNotMatchingIndexes(const QModelIndex& parent) -{ - if (!parent.isValid()) - { - m_ui->treeView->collapseAll(); - } - - const int rowCount = m_ui->treeView->model()->rowCount(parent); - for (int row = 0; row < rowCount; ++row) - { - const QModelIndex index = m_ui->treeView->model()->index(row, 0, parent); - const QString text = index.data().toString(); - bool contains = true; - m_ui->treeView->setExpanded(index, !contains); - if (!contains) - { - expandAllNotMatchingIndexes(index); - } - } -} - -void MaterialBrowserWidget::MaterialAddFinished() -{ - emit materialAdded(); -} - -void MaterialBrowserWidget::MaterialFinishedProcessing(_smart_ptr material, const QPersistentModelIndex& filterModelIndex) -{ - // If the currently selected material finished processing - if (filterModelIndex.isValid() && filterModelIndex == m_ui->treeView->currentIndex()) - { - // Stash the delayed selection so that it is not cleared just because the currently selected material finished processing - _smart_ptr tempDelayedSelection = m_delayedSelection; - - // Re-select the material to update the material dialogue - // but ignore the tree-view selection since the current index is already the correct one for this material - SetSelectedItem(material, nullptr, false); - - // Force update the material dialog - if (m_pListener) - { - m_pListener->OnBrowserSelectItem(GetCurrentMaterial(), true); - } - - if (material != m_delayedSelection) - { - // If the current selection that just finished processing was not the delayed selection, restore the delayed selection - m_delayedSelection = tempDelayedSelection; - } - } - // If there was a failed attempt to select the material before it finished processing - else if (m_delayedSelection && m_delayedSelection == material) - { - // Re-select the material to update the material dialogue - // and also select the material in the tree-view - SetSelectedItem(material, nullptr, true); - - // Force update the material dialog - if (m_pListener) - { - m_pListener->OnBrowserSelectItem(GetCurrentMaterial(), true); - } - } -} - -void MaterialBrowserWidget::MaterialRecordUpdateFinished() -{ - //The event is sent by a AZJob working thread, need to emit a signal here for qt to catch later. - //It can make sure all the qt functions need to be called at this point are only executed in the qt thread. - emit refreshSelection(); -} - - -#include diff --git a/Code/Sandbox/Editor/Material/MaterialBrowser.h b/Code/Sandbox/Editor/Material/MaterialBrowser.h deleted file mode 100644 index d02045bacd..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialBrowser.h +++ /dev/null @@ -1,248 +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_MATERIAL_MATERIALBROWSER_H -#define CRYINCLUDE_EDITOR_MATERIAL_MATERIALBROWSER_H -#pragma once - - -#if !defined(Q_MOC_RUN) -#include "Include/IDataBaseManager.h" -#include "Material/Material.h" -#include "Material/MaterialBrowserFilterModel.h" - -#include -#include -#include -#include - -#include -#endif - -class CMaterial; - -class MaterialBrowserWidget; -class CMaterialImageListCtrl; -class QMaterialImageListModel; - -class QTreeView; -class QAction; - -struct IDataBaseItem; -class CMaterialBrowserRecord; -typedef std::vector TMaterialBrowserRecords; - -namespace AzToolsFramework -{ - namespace AssetBrowser - { - class AssetBrowserModel; - class AssetBrowserFilterModel; - class AssetTypeFilter; - } -} - -enum ESccFileAttributes; - -namespace Ui -{ - class MaterialBrowser; -} - - -////////////////////////////////////////////////////////////////////////// -struct IMaterialBrowserListener -{ - virtual void OnBrowserSelectItem(IDataBaseItem* pItem, bool bForce) = 0; -}; - -////////////////////////////////////////////////////////////////////////// -// MaterialBrowserWidget -////////////////////////////////////////////////////////////////////////// -class MaterialBrowserFilterModel; - -class MaterialBrowserWidget - : public QWidget - , public IDataBaseManagerListener - , public IEditorNotifyListener - , public MaterialBrowserWidgetBus::Handler -{ - Q_OBJECT - -public: - enum EViewType - { - VIEW_LEVEL = 0, - VIEW_ALL = 1, - }; - - enum EFilter - { - eFilter_Materials = 0x01, - eFilter_Textures = 0x02, - eFilter_Materials_And_Textures = 0x03, - eFilter_Submaterials = 0x04 - }; - - MaterialBrowserWidget(QWidget* parent); - ~MaterialBrowserWidget(); - - void SetListener(IMaterialBrowserListener* pListener) { m_pListener = pListener; } - - EViewType GetViewType() const { return m_viewType; }; - - void ClearItems(); - - void SelectItem(IDataBaseItem* pItem, IDataBaseItem* pParentItem); - void DeleteItem(); - - void PopulateItems(); - void StartRecordUpdateJobs(); - - bool ShowCheckedOutRecursive(TMaterialBrowserRecords* pRecords); - - void ShowOnlyLevelMaterials(bool levelOnly); - - void OnCopy(); - void OnCopyName(); - void OnPaste(); - void OnCut(); - void OnDuplicate(); - void OnAddNewMaterial(); - void OnAddNewMultiMaterial(); - void OnConvertToMulti(); - void OnMergeMaterials(); - -public slots: - void OnSelectionChanged(); - void OnSubMaterialSelectedInPreviewPane(const QModelIndex& current); - void SaveCurrentMaterial(); - void OnRefreshSelection(); - void OnMaterialAdded(); - -signals: - void refreshSelection(); - void materialAdded(); - -public: - void OnUpdateShowCheckedOut(); - bool CanPaste() const; - - void SetImageListCtrl(CMaterialImageListCtrl* pCtrl); - - ////////////////////////////////////////////////////////////////////////// - // IDataBaseManagerListener implementation. - ////////////////////////////////////////////////////////////////////////// - virtual void OnDataBaseItemEvent(IDataBaseItem* pItem, EDataBaseItemEvent event); - ////////////////////////////////////////////////////////////////////////// - - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event); - void AddContextMenuActionsSingleSelection(QMenu &menu, _smart_ptr material) const; - void OnContextMenuAction(int command, _smart_ptr material); - - // MaterialBrowserWidgetBus event handlers - void MaterialAddFinished() override; - void MaterialFinishedProcessing(_smart_ptr material, const QPersistentModelIndex &filterModelIndex) override; - void MaterialRecordUpdateFinished() override; - -protected: - // Item definition. - enum ESourceControlOp - { - ESCM_IMPORT, - ESCM_CHECKOUT, - ESCM_UNDO_CHECKOUT, - ESCM_GETLATEST, - ESCM_GETLATESTTEXTURES, - }; - - void DeleteItem(const CMaterialBrowserRecord &record); - void SetSelectedItem(_smart_ptr material, const TMaterialBrowserRecords* pMarkedRecords, bool selectInTreeView); - void OnAddSubMtl(); - void OnSelectAssignedObjects(); - void OnAssignMaterialToSelection(); - void OnRenameItem(); - void OnResetItem(); - void OnSetSubMtlCount(const CMaterialBrowserRecord &record); - - void DoSourceControlOp(CMaterialBrowserRecord &record, ESourceControlOp); - - void OnMakeSubMtlSlot(const CMaterialBrowserRecord &record); - void OnClearSubMtlSlot(_smart_ptr subMaterial); - void SetSubMaterial(_smart_ptr parentMaterial, int slot, _smart_ptr subMaterial); - - void OnSaveToFile(bool bMulti); - - void RefreshSelected(); - - void TickRefreshMaterials(); - void TryLoadRecordMaterial(CMaterialBrowserRecord &record); - - void ShowContextMenu(const CMaterialBrowserRecord &record, const QPoint& point); - _smart_ptr GetCurrentMaterial(); - - uint32 MaterialNameToCrc32(const QString& str); - - bool TryGetSelectedRecord(CMaterialBrowserRecord &record); - AZStd::string GetSelectedMaterialID(); - -private: - void expandAllNotMatchingIndexes(const QModelIndex& parent = QModelIndex()); - void ClearImageListControlSelection(); - void ClearSelection(QMaterialImageListModel* materialModel); - QMenu *InitializeSearchMenu(); - - void AddContextMenuActionsMultiSelect(QMenu &menu) const; - void AddContextMenuActionsNoSelection(QMenu &menu) const; - void AddContextMenuActionsSubMaterial(QMenu &menu, _smart_ptr parentMaterial, _smart_ptr subMaterial) const; - void AddContextMenuActionsMultiMaterial(QMenu &menu) const; - void AddContextMenuActionsSingleMaterial(QMenu &menu) const; - void AddContextMenuActionsCommon(QMenu &menu, _smart_ptr material) const; - void AddContextMenuActionsSourceControl(QMenu &menu, _smart_ptr material, uint32 fileAttributes) const; - - QScopedPointer m_ui; - - AzToolsFramework::AssetBrowser::AssetBrowserModel* m_assetBrowserModel; - QSharedPointer m_filterModel; - int m_selectedSubMaterialIndex = -1; - - bool m_bIgnoreSelectionChange; - bool m_bItemsValid; - - CMaterialManager* m_pMatMan; - IMaterialBrowserListener* m_pListener; - CMaterialImageListCtrl* m_pMaterialImageListCtrl; - - EViewType m_viewType; - bool m_bNeedReload; - - bool m_bHighlightMaterial; - uint32 m_timeOfHighlight; - - TMaterialBrowserRecords m_markedRecords; - - _smart_ptr m_pLastActiveMultiMaterial; - _smart_ptr m_delayedSelection; - - bool m_bShowOnlyCheckedOut; - - QAction* m_cutAction; - QAction* m_copyAction; - QAction* m_pasteAction; - QAction* m_duplicateAction; - QAction* m_deleteAction; - QAction* m_renameItemAction; - QAction* m_addNewMaterialAction; -}; - -#endif // CRYINCLUDE_EDITOR_MATERIAL_MATERIALBROWSER_H diff --git a/Code/Sandbox/Editor/Material/MaterialBrowser.ui b/Code/Sandbox/Editor/Material/MaterialBrowser.ui deleted file mode 100644 index 44e4e135ef..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialBrowser.ui +++ /dev/null @@ -1,87 +0,0 @@ - - - MaterialBrowser - - - - 0 - 0 - 250 - 400 - - - - Form - - - - 0 - - - 2 - - - 0 - - - 0 - - - - - - - - 0 - 0 - - - - - 147 - 22 - - - - - - - - - - - 0 - 0 - - - - Qt::CustomContextMenu - - - QAbstractItemView::ExtendedSelection - - - false - - - - - - - - AzToolsFramework::AssetBrowser::SearchWidget - QWidget -
AzToolsFramework/AssetBrowser/Search/SearchWidget.h
- 1 -
- - AzToolsFramework::AssetBrowser::AssetBrowserTreeView - QTreeView -
AzToolsFramework/AssetBrowser/Views/AssetBrowserTreeView.h
-
-
- - - - -
diff --git a/Code/Sandbox/Editor/Material/MaterialBrowserFilterModel.cpp b/Code/Sandbox/Editor/Material/MaterialBrowserFilterModel.cpp deleted file mode 100644 index 9f145c4daf..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialBrowserFilterModel.cpp +++ /dev/null @@ -1,652 +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 "MaterialBrowserFilterModel.h" - -// AzFramework -#include - -// AzToolsFramework -#include -#include -#include -#include - -// Editor -#include "MaterialBrowserSearchFilters.h" -#include "MaterialManager.h" - - -namespace -{ - // how often to re-query source control status of an item after querying it, in seconds. - // note that using a source control operation on an item invalidates the cache and will immediately - // refresh its status regardless of this value, so it can be pretty high. - qint64 g_timeRefreshSCCStatus = 60; -} - -#define IDC_MATERIAL_TREECTRL 3 - -////////////////////////////////////////////////////////////////////////// -#define ITEM_IMAGE_SHARED_MATERIAL 0 -#define ITEM_IMAGE_SHARED_MATERIAL_SELECTED 1 -#define ITEM_IMAGE_FOLDER 2 -#define ITEM_IMAGE_FOLDER_OPEN 3 -#define ITEM_IMAGE_MATERIAL 4 -#define ITEM_IMAGE_MATERIAL_SELECTED 5 -#define ITEM_IMAGE_MULTI_MATERIAL 6 -#define ITEM_IMAGE_MULTI_MATERIAL_SELECTED 7 - - -#define ITEM_IMAGE_OVERLAY_CGF 8 -#define ITEM_IMAGE_OVERLAY_INPAK 9 -#define ITEM_IMAGE_OVERLAY_READONLY 10 -#define ITEM_IMAGE_OVERLAY_ONDISK 11 -#define ITEM_IMAGE_OVERLAY_LOCKED 12 -#define ITEM_IMAGE_OVERLAY_CHECKEDOUT 13 -#define ITEM_IMAGE_OVERLAY_NO_CHECKOUT 14 -////////////////////////////////////////////////////////////////////////// - -AZ::Data::AssetId GetMaterialProductAssetIdFromAssetBrowserEntry(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* assetEntry) -{ - using namespace AzToolsFramework::AssetBrowser; - - if (assetEntry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Source || - assetEntry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Product) - { - AZStd::vector products; - assetEntry->GetChildrenRecursively(products); - - // Cache the material asset type because this function is called for every submaterial when searching. - // AssetType is a POD struct so it should be fine to leave it as a static that gets destroyed during library unload/program termination. - static AZ::Data::AssetType materialAssetType = AZ::Data::AssetType::CreateNull(); - if (materialAssetType.IsNull()) - { - EBusFindAssetTypeByName materialAssetTypeResult("Material"); - AZ::AssetTypeInfoBus::BroadcastResult(materialAssetTypeResult, &AZ::AssetTypeInfo::GetAssetType); - AZ_Assert(materialAssetTypeResult.Found(), "Could not find asset type for material asset"); - materialAssetType = materialAssetTypeResult.GetAssetType(); - } - - for (const auto* product : products) - { - if (product->GetAssetType() == materialAssetType) - { - return product->GetAssetId(); - } - } - } - return AZ::Data::AssetId(); -} - -MaterialBrowserFilterModel::MaterialBrowserFilterModel(QObject* parent) - : AzToolsFramework::AssetBrowser::AssetBrowserFilterModel(parent) -{ - using namespace AzToolsFramework::AssetBrowser; - using namespace AzToolsFramework::MaterialBrowser; - - MaterialBrowserSourceControlBus::Handler::BusConnect(); - AssetBrowserModelNotificationBus::Handler::BusConnect(); - MaterialBrowserRequestBus::Handler::BusConnect(); - AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/material_00.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/material_01.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/material_02.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/material_03.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/material_04.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/material_05.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/material_06.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/material_07.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/filestatus_00.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/filestatus_01.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/filestatus_02.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/filestatus_03.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/filestatus_04.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/filestatus_05.png")); - m_imageList.push_back(QPixmap(":/MaterialBrowser/images/filestatus_06.png")); - - - // Create an asset type filter for materials - AssetTypeFilter* assetTypeFilter = new AssetTypeFilter(); - assetTypeFilter->SetAssetType("Material"); - assetTypeFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down); //this will make sure folders that contain materials are displayed - m_assetTypeFilter = FilterConstType(assetTypeFilter); - - // Create search filters. SetSearchFilter stores these filters so that they are deleted when this object is deleted. - m_subMaterialSearchFilter = new SubMaterialSearchFilter(this); - m_levelMaterialSearchFilter = new LevelMaterialSearchFilter(this); - - InitializeRecordUpdateJob(); -} - -MaterialBrowserFilterModel::~MaterialBrowserFilterModel() -{ - SAFE_DELETE(m_jobCancelGroup); - SAFE_DELETE(m_jobContext); - SAFE_DELETE(m_jobManager); - - AzToolsFramework::AssetBrowser::AssetBrowserModelNotificationBus::Handler::BusDisconnect(); - MaterialBrowserSourceControlBus::Handler::BusDisconnect(); - AzToolsFramework::MaterialBrowser::MaterialBrowserRequestBus::Handler::BusDisconnect(); - AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); -} - -void MaterialBrowserFilterModel::UpdateRecord(const QModelIndex& filterModelIndex) -{ - using namespace AzToolsFramework::AssetBrowser; - - if (filterModelIndex.isValid()) - { - QModelIndex modelIndex = mapToSource(filterModelIndex); - - AssetBrowserEntry* assetEntry = static_cast(modelIndex.internalPointer()); - - if (assetEntry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Source || - assetEntry->GetEntryType() == AssetBrowserEntry::AssetEntryType::Product) - { - AZStd::vector products; - assetEntry->GetChildrenRecursively(products); - - for (const auto* product : products) - { - if (!m_assetTypeFilter->Match(product)) - { - continue; - } - MaterialBrowserRecordAssetBrowserData assetBrowserData; - assetBrowserData.assetId = product->GetAssetId(); - assetBrowserData.relativeFilePath = product->GetRelativePath(); - assetBrowserData.fullSourcePath = product->GetFullPath(); - assetBrowserData.modelIndex = modelIndex; - assetBrowserData.filterModelIndex = filterModelIndex; - UpdateRecord(assetBrowserData); - } - } - } -} - -void MaterialBrowserFilterModel::UpdateRecord(const MaterialBrowserRecordAssetBrowserData& assetBrowserData) -{ - CMaterialBrowserRecord record; - record.SetAssetBrowserData(assetBrowserData); - record.m_material = GetIEditor()->GetMaterialManager()->LoadMaterial(record.GetRelativeFilePath().c_str()); - SetRecord(record); -} - -void MaterialBrowserFilterModel::UpdateSourceControlFileInfoCallback(const AZ::Data::AssetId& assetId, const AzToolsFramework::SourceControlFileInfo& info) -{ - CMaterialBrowserRecord record; - bool found = m_materialRecordMap.find(assetId, &record); - if (found) - { - // Update the cached source control attributes for the record - record.m_lastCachedSCCAttributes = info; - record.m_lastCachedFileAttributes = static_cast(CFileUtil::GetAttributes(record.GetFullSourcePath().c_str(), false)); - record.m_lastCheckedSCCAttributes = QDateTime::currentDateTime(); - - // Update the record - m_materialRecordMap.erase(assetId); - m_materialRecordMap.insert(AZStd::pair(record.GetAssetId(), record)); - - QueueDataChangedEvent(record.GetFilterModelIndex()); - } -} - -void MaterialBrowserFilterModel::UpdateSourceControlLastCheckedTime(const AZ::Data::AssetId& assetId, const QDateTime& dateTime) -{ - CMaterialBrowserRecord record; - bool found = m_materialRecordMap.find(assetId, &record); - if (found) - { - // Update the record - record.m_lastCheckedSCCAttributes = dateTime; - m_materialRecordMap.erase(assetId); - m_materialRecordMap.insert(AZStd::pair(record.GetAssetId(), record)); - } -} - -QVariant MaterialBrowserFilterModel::data(const QModelIndex& index, int role /* = Qt::DisplayRole*/) const -{ - // Should return data from an AssetBrowserEntry, or get material specific info from that data - if (index.isValid()) - { - // Use the base AssetBrowserFilterModel::data function for display role - if (role != AzToolsFramework::AssetBrowser::AssetBrowserModel::Roles::EntryRole) - { - QModelIndex modelIndex = mapToSource(index); - AzToolsFramework::AssetBrowser::AssetBrowserEntry* assetEntry = static_cast(modelIndex.internalPointer()); - - AZ::Data::AssetId assetId = GetMaterialProductAssetIdFromAssetBrowserEntry(assetEntry); - if (assetId.IsValid()) - { - CMaterialBrowserRecord record; - bool found = m_materialRecordMap.find(assetId, &record); - - if (role == Qt::UserRole) - { - if (found) - { - return QVariant::fromValue(record); - } - else - { - return QVariant(); - } - } - } - } - } - // If the role is Qt::DisplayRole, the item a folder, or the material has not been parsed yet, fall back on the default data result from the underlying AssetBrowserModel - return AzToolsFramework::AssetBrowser::AssetBrowserFilterModel::data(index, role); -} - -void MaterialBrowserFilterModel::GetRelativeFilePaths(AZStd::vector& files) const -{ - GetRelativeFilePathsRecursive(files, this); -} - -void MaterialBrowserFilterModel::GetRelativeFilePathsRecursive(AZStd::vector& files, - const MaterialBrowserFilterModel* model, const QModelIndex& parent) const -{ - using namespace AzToolsFramework::AssetBrowser; - - for (int r = 0; r < model->rowCount(parent); ++r) - { - QModelIndex index = model->index(r, 0, parent); - QModelIndex modelIndex = model->mapToSource(index); - - if (model->hasChildren(index)) - { - GetRelativeFilePathsRecursive(files, model, index); - } - else - { - AssetBrowserEntry* assetEntry = static_cast(modelIndex.internalPointer()); - - AZStd::vector products; - assetEntry->GetChildrenRecursively(products); - - for (const auto* product : products) - { - if (!m_assetTypeFilter->Match(product)) - { - continue; - } - MaterialBrowserRecordAssetBrowserData item; - item.assetId = product->GetAssetId(); - item.fullSourcePath = product->GetFullPath(); - item.relativeFilePath = product->GetRelativePath(); - item.modelIndex = modelIndex; - item.filterModelIndex = index; - files.push_back(item); - } - } - } -} - -QModelIndex MaterialBrowserFilterModel::GetIndexFromMaterial(_smart_ptr material) const -{ - CMaterialBrowserRecord record; - bool found = TryGetRecordFromMaterial(material, record); - if (found) - { - return record.GetFilterModelIndex(); - } - return QModelIndex(); -} - -QModelIndex MaterialBrowserFilterModel::GetFilterModelIndex(const AZ::Data::AssetId& assetId) const -{ - QModelIndex filterModelIndex; - if (TryGetFilterModelIndexRecursive(filterModelIndex, assetId, this)) - { - return filterModelIndex; - } - - return QModelIndex(); -} - -bool MaterialBrowserFilterModel::TryGetFilterModelIndexRecursive(QModelIndex& filterModelIndex, - const AZ::Data::AssetId& assetId, const MaterialBrowserFilterModel* model, const QModelIndex& parent) const -{ - using namespace AzToolsFramework::AssetBrowser; - - // Walk through the filter model to find the product entry with the corresponding assetId - for (int r = 0; r < model->rowCount(parent); ++r) - { - QModelIndex index = model->index(r, 0, parent); - QModelIndex modelIndex = model->mapToSource(index); - - if (model->hasChildren(index)) - { - if (TryGetFilterModelIndexRecursive(filterModelIndex, assetId, model, index)) - { - return true; - } - } - else - { - // Check to see if the current entry is the one we're looking for - AssetBrowserEntry* assetEntry = static_cast(modelIndex.internalPointer()); - - AZStd::vector products; - assetEntry->GetChildrenRecursively(products); - - for (const auto* product : products) - { - if (assetId == product->GetAssetId()) - { - filterModelIndex = index; - return true; - } - } - } - } - - return false; -} - -void MaterialBrowserFilterModel::EntryAdded(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) -{ - // If the entry is a product material - if (entry->GetEntryType() == AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Product && m_assetTypeFilter->Match(entry)) - { - // capture the data here, so that entry cannot disappear before we actually get to the job. - MaterialBrowserRecordAssetBrowserData assetBrowserData; - assetBrowserData.assetId = GetMaterialProductAssetIdFromAssetBrowserEntry(entry); - assetBrowserData.relativeFilePath = entry->GetRelativePath(); - assetBrowserData.fullSourcePath = entry->GetFullPath(); - assetBrowserData.filterModelIndex = GetFilterModelIndex(assetBrowserData.assetId); - - // Create a job to add/update the entry in the underlying map - AZ::Job* updateEntryJob = AZ::CreateJobFunction([this, assetBrowserData]() - { - CMaterialBrowserRecord record; - record.SetAssetBrowserData(assetBrowserData); - record.m_material = GetIEditor()->GetMaterialManager()->LoadMaterialWithFullSourcePath(record.GetRelativeFilePath().c_str(), record.GetFullSourcePath().c_str()); - SetRecord(record); - MaterialBrowserWidgetBus::Broadcast(&MaterialBrowserWidgetEvents::MaterialAddFinished); - }, true, m_jobContext); - - // Start the job immediately - AZ::Job* currentJob = m_jobContext->GetJobManager().GetCurrentJob(); - if (currentJob) - { - // Suspend the current job until the new job completes so that - // if a new material is created by the user it's ready to use sooner - currentJob->StartAsChild(updateEntryJob); - currentJob->WaitForChildren(); - } - else - { - updateEntryJob->Start(); - } - } -} - - -void MaterialBrowserFilterModel::OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) -{ - CMaterialBrowserRecord record; - bool found = m_materialRecordMap.find(assetId, &record); - if (found) - { - record.m_material->Reload(); - //Send out event to notify UI update if it's currently selected - MaterialBrowserWidgetBus::Broadcast(&MaterialBrowserWidgetEvents::MaterialFinishedProcessing, record.m_material, record.GetFilterModelIndex()); - } -} - -bool MaterialBrowserFilterModel::HasRecord(const AZ::Data::AssetId& assetId) -{ - return m_materialRecordMap.find(assetId); -} - -bool MaterialBrowserFilterModel::IsMultiMaterial(const AZ::Data::AssetId& assetId) -{ - CMaterialBrowserRecord record; - bool found = m_materialRecordMap.find(assetId, &record); - if (found) - { - if (record.m_material && record.m_material->IsMultiSubMaterial()) - { - return true; - } - } - return false; -} - -bool MaterialBrowserFilterModel::TryGetRecordFromMaterial(_smart_ptr material, CMaterialBrowserRecord& record) const -{ - if (material) - { - // Get the relative path for the material - bool pathFound = false; - AZStd::string relativePath; - AzToolsFramework::AssetSystemRequestBus::BroadcastResult(pathFound, &AzToolsFramework::AssetSystem::AssetSystemRequest::GetRelativeProductPathFromFullSourceOrProductPath, material->GetFilename().toUtf8().data(), relativePath); - AZ_Assert(pathFound, "Failed to get engine relative path from %s", material->GetFilename().toUtf8().data()); - - // Get the assetId from the relative path - AZ::Data::AssetId assetId; - - AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, relativePath.c_str(), GetIEditor()->GetMaterialManager()->GetMaterialAssetType(), false); - - return TryGetRecordFromAssetId(assetId, record); - } - - return false; -} - -bool MaterialBrowserFilterModel::TryGetRecordFromAssetId(const AZ::Data::AssetId& assetId, CMaterialBrowserRecord& record) const -{ - bool recordFound = m_materialRecordMap.find(assetId, &record); - return recordFound; -} - -void MaterialBrowserFilterModel::SetRecord(const CMaterialBrowserRecord& record) -{ - m_materialRecordMap.erase(record.GetAssetId()); - m_materialRecordMap.insert({ record.GetAssetId(), record }); - - QueueDataChangedEvent(record.GetFilterModelIndex()); -} - -void MaterialBrowserFilterModel::SetSearchFilter(const AzToolsFramework::AssetBrowser::SearchWidget* searchWidget) -{ - /* - * The filter matches the following rule: - * A. If the entry is a material - * 1. The material's name matches the search text - * 2. The sub material's name matches the search text - * B. If the entry is a folder: - * 1. The folder's name matches the search text - * 2. The folder contains a material matching A - * 3. The folder contains a folder matching B.1 & B.2 - */ - - using namespace AzToolsFramework::AssetBrowser; - - m_searchWidget = searchWidget; - - // Create a search filter where a search text either matches entry/entry parent's name or sub material name - CompositeFilter* nameFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::OR); - QSharedPointer searchWidgetFilter = m_searchWidget->GetFilter(); - // The default setting for search widget filter is Down - // Since now we only need to match for the entry itself in this filter, set back to None - searchWidgetFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::None); - nameFilter->AddFilter(FilterConstType(m_subMaterialSearchFilter)); - nameFilter->AddFilter(FilterConstType(searchWidgetFilter)); - - EntryTypeFilter* productsFilter = new EntryTypeFilter(); - productsFilter->SetEntryType(AssetBrowserEntry::AssetEntryType::Product); - InverseFilter* noProductsFilter = new InverseFilter(); - noProductsFilter->SetFilter(FilterConstType(productsFilter)); - - // Create a filter where the entry needs to match the previous name filter and it needs to be material itself or it contains material. - CompositeFilter* isMaterialAndMatchesSearchFilter = new CompositeFilter(CompositeFilter::LogicOperatorType::AND); - isMaterialAndMatchesSearchFilter->AddFilter(FilterConstType(nameFilter)); - isMaterialAndMatchesSearchFilter->AddFilter(FilterConstType(m_assetTypeFilter)); - isMaterialAndMatchesSearchFilter->AddFilter(FilterConstType(noProductsFilter)); - isMaterialAndMatchesSearchFilter->AddFilter(FilterConstType(m_levelMaterialSearchFilter)); - // Make sure any folder contains the matching result is included - isMaterialAndMatchesSearchFilter->SetFilterPropagation(AssetBrowserEntryFilter::PropagateDirection::Down); - - // Set the filter for the MaterialBrowserFilterModel - SetFilter(FilterConstType(isMaterialAndMatchesSearchFilter)); -} - -void MaterialBrowserFilterModel::ShowOnlyLevelMaterials(bool levelOnly, bool invalidateFilterNow) -{ - m_levelMaterialSearchFilter->ShowOnlyLevelMaterials(levelOnly); - if (levelOnly) - { - m_levelMaterialSearchFilter->CacheLoadedMaterials(); - } - - if (invalidateFilterNow) - { - // we need to invalid the filter immediately, for example this is used when we are changing level, otherwise - // the current filter is used when getting file paths for all of the materials as part of StartRecordUpdateJobs. - invalidateFilter(); - } - else - { - filterUpdatedSlot(); - } -} - -void MaterialBrowserFilterModel::SearchFilterUpdated() -{ - m_subMaterialSearchFilter->SetFilterString(m_searchWidget->textFilter()); - filterUpdatedSlot(); -} - -void MaterialBrowserFilterModel::QueueDataChangedEvent(const QPersistentModelIndex& filterModelIndex) -{ - // Queue a data changed event to be executed on the main thread - AZStd::function emitDataChanged = - [this, filterModelIndex]() - { - if (filterModelIndex.isValid()) - { - Q_EMIT dataChanged(filterModelIndex, filterModelIndex); - } - }; - - AZ::TickBus::QueueFunction(emitDataChanged); -} - -void MaterialBrowserFilterModel::InitializeRecordUpdateJob() -{ - AZ::JobManagerDesc desc; - AZ::JobManagerThreadDesc threadDesc; - for (size_t i = 0; i < AZStd::thread::hardware_concurrency(); ++i) - { - desc.m_workerThreads.push_back(threadDesc); - } - - // Check to ensure these have not already been initialized. - AZ_Error("Material Browser", !m_jobManager && !m_jobCancelGroup && !m_jobContext, "MaterialBrowserFilterModel::InitializeRecordUpdateJob is being called again after it has already been initialized"); - m_jobManager = aznew AZ::JobManager(desc); - m_jobCancelGroup = aznew AZ::JobCancelGroup(); - m_jobContext = aznew AZ::JobContext(*m_jobManager, *m_jobCancelGroup); -} - -void MaterialBrowserFilterModel::StartRecordUpdateJobs() -{ - // Generate a list of file paths, assetId's, and asset browser model indices - // This must be done on the main thread, otherwise it can lead to a crash when the tree view UI is being initialized - AZStd::vector files; - GetRelativeFilePaths(files); - - // Kick off the background process that will iterate over the list of file paths and update the material record map - m_mainUpdateRecordJob = aznew MaterialBrowserUpdateJobCreator(this, files, m_jobContext); - m_mainUpdateRecordJob->Start(); -} - -void MaterialBrowserFilterModel::CancelRecordUpdateJobs() -{ - m_jobContext->GetCancelGroup()->Cancel(); - m_jobContext->GetCancelGroup()->Reset(); -} - -void MaterialBrowserFilterModel::ClearRecordMap() -{ - CancelRecordUpdateJobs(); - m_materialRecordMap.clear(); -} - -MaterialBrowserUpdateJobCreator::MaterialBrowserUpdateJobCreator(MaterialBrowserFilterModel* model, AZStd::vector& files, AZ::JobContext* context /*= NULL*/) - : Job(true, context) - , m_files(files) - , m_filterModel(model) -{ -} - -void MaterialBrowserUpdateJobCreator::Process() -{ - // Split the files to be processed evenly among threads - int numJobs = GetContext()->GetJobManager().GetNumWorkerThreads(); - int materialsPerJob = (m_files.size() / numJobs) + 1; - - for (auto it = m_files.begin(); it <= m_files.end(); it += materialsPerJob) - { - // Create a subset of the list of material files to be processed by another job - auto start = it; - auto end = it + materialsPerJob; - if (end > m_files.end()) - { - end = m_files.end(); - } - AZStd::vector subset(start, end); - - if (subset.size() > 0) - { - AZ::Job* materialBrowserUpdateJob = aznew MaterialBrowserUpdateJob(m_filterModel, subset, GetContext()); - StartAsChild(materialBrowserUpdateJob); - } - } - - WaitForChildren(); - - MaterialBrowserWidgetBus::Broadcast(&MaterialBrowserWidgetEvents::MaterialRecordUpdateFinished); -} - -MaterialBrowserUpdateJob::MaterialBrowserUpdateJob(MaterialBrowserFilterModel* model, AZStd::vector& files, AZ::JobContext* context /*= NULL*/) - : Job(true, context) - , m_filterModel(model) - , m_files(files) -{ -} - -void MaterialBrowserUpdateJob::Process() -{ - for (size_t i = 0; i < m_files.size(); ++i) - { - // Early out when the job is cancelled - if (IsCancelled()) - { - return; - } - CMaterialBrowserRecord record; - record.SetAssetBrowserData(m_files[i]); - - // Get the writable status of the file, but don't update source control status until it is actually needed - record.m_lastCachedFileAttributes = static_cast(CFileUtil::GetAttributes(record.GetFullSourcePath().c_str(), false)); - - record.m_material = GetIEditor()->GetMaterialManager()->LoadMaterialWithFullSourcePath(record.GetRelativeFilePath().c_str(), record.GetFullSourcePath().c_str()); - m_filterModel->SetRecord(record); - } -} diff --git a/Code/Sandbox/Editor/Material/MaterialBrowserFilterModel.h b/Code/Sandbox/Editor/Material/MaterialBrowserFilterModel.h deleted file mode 100644 index afb7f8a7ce..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialBrowserFilterModel.h +++ /dev/null @@ -1,240 +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 -#include -#include -#include -#include - - -#include -#include - -namespace AZ -{ - class Job; - class JobManager; - class JobCancelGroup; - class JobContext; -} - -class SubMaterialSearchFilter; -class LevelMaterialSearchFilter; - -////////////////////////////////////////////////////////////////////////// -// Item class for browser. -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -struct MaterialBrowserRecordAssetBrowserData -{ - AZ::Data::AssetId assetId; - AZStd::string relativeFilePath; - AZStd::string fullSourcePath; - QPersistentModelIndex modelIndex; - QPersistentModelIndex filterModelIndex; -}; - -class CMaterialBrowserRecord -{ -public: - CMaterialBrowserRecord() - { - InitializeSourceControlAttributes(); - } - - CMaterialBrowserRecord(const CMaterialBrowserRecord &rhs) - : m_material(rhs.m_material) - , m_lastCachedSCCAttributes(rhs.m_lastCachedSCCAttributes) - , m_lastCachedFileAttributes(rhs.m_lastCachedFileAttributes) - , m_lastCheckedSCCAttributes(rhs.m_lastCheckedSCCAttributes) - , m_assetBrowserData(rhs.m_assetBrowserData) - { - } - - AZ::Data::AssetId GetAssetId() const { return m_assetBrowserData.assetId; } - AZStd::string GetRelativeFilePath() const { return m_assetBrowserData.relativeFilePath; } - AZStd::string GetFullSourcePath() const { return m_assetBrowserData.fullSourcePath; } - QPersistentModelIndex GetModelIndex() const { return m_assetBrowserData.modelIndex; } - QPersistentModelIndex GetFilterModelIndex() const { return m_assetBrowserData.filterModelIndex; } - void SetAssetBrowserData(const MaterialBrowserRecordAssetBrowserData &assetBrowserData) { m_assetBrowserData = assetBrowserData; } - void InitializeSourceControlAttributes() - { - // Force an update by setting the last update time to 1 / 1 / 1 - m_lastCachedSCCAttributes = AzToolsFramework::SourceControlFileInfo(); - m_lastCachedFileAttributes = SCC_FILE_ATTRIBUTE_INVALID; - m_lastCheckedSCCAttributes = QDate(1, 1, 1).startOfDay(); - } -public: - _smart_ptr m_material = nullptr; - AzToolsFramework::SourceControlFileInfo m_lastCachedSCCAttributes; - ESccFileAttributes m_lastCachedFileAttributes; - QDateTime m_lastCheckedSCCAttributes; - -private: - MaterialBrowserRecordAssetBrowserData m_assetBrowserData; -}; -Q_DECLARE_METATYPE(CMaterialBrowserRecord) - - -//! MaterialBrowserSourceControlEvents -//! This bus informs the material browser filter model -//! when an ASYNC source control command has completed -class MaterialBrowserSourceControlEvents - : public AZ::EBusTraits -{ -public: - typedef AZStd::recursive_mutex MutexType; - - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; // there's only one listener - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; // theres only one listener - virtual ~MaterialBrowserSourceControlEvents() {} - - //! Signals the callback for the GetFileInfo source control op - virtual void UpdateSourceControlFileInfoCallback(const AZ::Data::AssetId &assetId, const AzToolsFramework::SourceControlFileInfo& fileInfo) = 0; - //! Updates the timestamp for when the source control status was last checked - virtual void UpdateSourceControlLastCheckedTime(const AZ::Data::AssetId &assetId, const QDateTime &dateTime) = 0; -}; - -using MaterialBrowserSourceControlBus = AZ::EBus; - -//! MaterialBrowserWidgetEvents -//! This bus is used to send events to the material browser widget -class MaterialBrowserWidgetEvents - : public AZ::EBusTraits -{ -public: - typedef AZStd::recursive_mutex MutexType; - - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; // there's only one listener - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; // theres only one listener - virtual ~MaterialBrowserWidgetEvents() {} - - //! Indicates that a material has finished being processed by the asset processor - virtual void MaterialFinishedProcessing(_smart_ptr material, const QPersistentModelIndex &filterModelIndex) = 0; - - //! Indicates that a material has finished being added to the material browser - virtual void MaterialAddFinished() = 0; - - //! Indicates that the material record update for initially populating the material browser has finished - virtual void MaterialRecordUpdateFinished() = 0; -}; - -using MaterialBrowserWidgetBus = AZ::EBus; - -/** -* Get the product material assetId for a given AssetBrowserEntry -* If there is no valid product material, the material has not been processed, or there are multiple product materials -* and thus there is not an individual material that can be assumed based on the source, an invalid assetId is returned -* @param assetEntry An asset entry that may be a source or a product -* @return The assetId of the product material. -*/ -AZ::Data::AssetId GetMaterialProductAssetIdFromAssetBrowserEntry(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* assetEntry); - -class MaterialBrowserFilterModel - : public AzToolsFramework::AssetBrowser::AssetBrowserFilterModel - , public MaterialBrowserSourceControlBus::Handler - , public AzToolsFramework::AssetBrowser::AssetBrowserModelNotificationBus::Handler - , public AzToolsFramework::MaterialBrowser::MaterialBrowserRequestBus::Handler - , private AzFramework::AssetCatalogEventBus::Handler -{ -public: - AZ_CLASS_ALLOCATOR(MaterialBrowserFilterModel, AZ::SystemAllocator, 0); - MaterialBrowserFilterModel(QObject* parent); - ~MaterialBrowserFilterModel(); - void UpdateRecord(const QModelIndex& filterModelIndex); - void UpdateRecord(const MaterialBrowserRecordAssetBrowserData &assetBrowserData); - void UpdateSourceControlFileInfoCallback(const AZ::Data::AssetId &assetId, const AzToolsFramework::SourceControlFileInfo& info) override; - void UpdateSourceControlLastCheckedTime(const AZ::Data::AssetId &assetId, const QDateTime &dateTime) override; - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - bool TryGetRecordFromMaterial(_smart_ptr material, CMaterialBrowserRecord& record) const; - bool TryGetRecordFromAssetId(const AZ::Data::AssetId &assetId, CMaterialBrowserRecord& record) const; - void SetRecord(const CMaterialBrowserRecord& record); - void SetSearchFilter(const AzToolsFramework::AssetBrowser::SearchWidget* searchWidget); - void StartRecordUpdateJobs(); - void CancelRecordUpdateJobs(); - void ClearRecordMap(); - void GetRelativeFilePaths(AZStd::vector &files) const; - QModelIndex GetIndexFromMaterial(_smart_ptr material) const; - QModelIndex GetFilterModelIndex(const AZ::Data::AssetId &assetId) const; - - // AssetBrowserModelNotificationBus event handlers - void EntryAdded(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) override; - - void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override; - // MaterialBrowserRequestBus - bool HasRecord(const AZ::Data::AssetId& assetId) override; - bool IsMultiMaterial(const AZ::Data::AssetId& assetId) override; - - void ShowOnlyLevelMaterials(bool levelOnly, bool invalidateFilterNow = false); - - public Q_SLOTS: - void SearchFilterUpdated(); - -private: - void GetRelativeFilePathsRecursive(AZStd::vector &files, const MaterialBrowserFilterModel* model, const QModelIndex &parent = QModelIndex()) const; - bool TryGetFilterModelIndexRecursive(QModelIndex &filterModelIndex, const AZ::Data::AssetId &assetId, const MaterialBrowserFilterModel* model, const QModelIndex &parent = QModelIndex()) const; - void QueueDataChangedEvent(const QPersistentModelIndex &filterModelIndex); - AZStd::concurrent_unordered_map m_materialRecordMap; - QVector m_imageList; - AzToolsFramework::AssetBrowser::FilterConstType m_assetTypeFilter; - SubMaterialSearchFilter* m_subMaterialSearchFilter; - LevelMaterialSearchFilter* m_levelMaterialSearchFilter; - const AzToolsFramework::AssetBrowser::SearchWidget* m_searchWidget; - - void InitializeRecordUpdateJob(); - AZ::JobManager* m_jobManager = nullptr; - AZ::JobCancelGroup* m_jobCancelGroup = nullptr; - AZ::JobContext* m_jobContext = nullptr; - AZ::Job* m_mainUpdateRecordJob = nullptr; -}; - -/** -* Job that walks through a MaterialBrowserFilterModel to generate a list of files, -* then divides the list amongst child jobs for processing -*/ -class MaterialBrowserUpdateJobCreator - : public AZ::Job -{ -public: - AZ_CLASS_ALLOCATOR(MaterialBrowserUpdateJobCreator, AZ::ThreadPoolAllocator, 0); - - MaterialBrowserUpdateJobCreator(MaterialBrowserFilterModel* model, AZStd::vector& files, AZ::JobContext* context = nullptr); - void Process() override; -private: - MaterialBrowserFilterModel* m_filterModel; - AZStd::vector m_files; -}; - -/** -* Job that walks through a list of material files, loads them, and then populates -* the MaterialBrowserFilterModel's map of material data -*/ -class MaterialBrowserUpdateJob - : public AZ::Job -{ -public: - AZ_CLASS_ALLOCATOR(MaterialBrowserUpdateJob, AZ::ThreadPoolAllocator, 0); - - MaterialBrowserUpdateJob(MaterialBrowserFilterModel* model, AZStd::vector &files, AZ::JobContext* context = nullptr); - void Process() override; -private: - MaterialBrowserFilterModel* m_filterModel; - AZStd::vector m_files; -}; - diff --git a/Code/Sandbox/Editor/Material/MaterialBrowserSearchFilters.cpp b/Code/Sandbox/Editor/Material/MaterialBrowserSearchFilters.cpp deleted file mode 100644 index cf2d3449d1..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialBrowserSearchFilters.cpp +++ /dev/null @@ -1,140 +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 "MaterialBrowserSearchFilters.h" - -// Editor -#include "MaterialBrowserFilterModel.h" -#include "Material.h" - - -SubMaterialSearchFilter::SubMaterialSearchFilter(const MaterialBrowserFilterModel* filterModel) - : m_filterModel(filterModel) -{ - AzToolsFramework::AssetBrowser::AssetBrowserEntryFilter::SetFilterPropagation(AzToolsFramework::AssetBrowser::AssetBrowserEntryFilter::PropagateDirection::Down); -} - -void SubMaterialSearchFilter::SetFilterString(const QString& filterString) -{ - m_filterString = filterString; -} - -QString SubMaterialSearchFilter::GetNameInternal() const -{ - return "SubMaterialSearchFilter"; -} - -bool SubMaterialSearchFilter::MatchInternal(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const -{ - // All entries match if there is no search string - if (m_filterString.isEmpty()) - { - return true; - } - - if (m_filterModel) - { - // Get the product material for the given asset browser entry - AZ::Data::AssetId assetId = GetMaterialProductAssetIdFromAssetBrowserEntry(entry); - if (assetId.IsValid()) - { - CMaterialBrowserRecord record; - bool found = m_filterModel->TryGetRecordFromAssetId(assetId, record); - if (found) - { - // If there is a valid product material, check to see if any of its sub-materials match the search string - if (record.m_material) - { - for (int i = 0; i < record.m_material->GetSubMaterialCount(); ++i) - { - CMaterial* subMaterial = record.m_material->GetSubMaterial(i); - if (subMaterial) - { - // If any of the product sub-materials matches the string, return true for this entry - if (subMaterial->GetName().contains(m_filterString, Qt::CaseInsensitive)) - { - return true; - } - } - } - } - } - } - } - return false; -} - -LevelMaterialSearchFilter::LevelMaterialSearchFilter(const MaterialBrowserFilterModel* filterModel) - : m_filterModel(filterModel) -{ - AzToolsFramework::AssetBrowser::AssetBrowserEntryFilter::SetFilterPropagation(AzToolsFramework::AssetBrowser::AssetBrowserEntryFilter::PropagateDirection::Down); -} - -QString LevelMaterialSearchFilter::GetNameInternal() const -{ - return "LoadedMaterialSearchFilter"; -} - -void LevelMaterialSearchFilter::CacheLoadedMaterials() -{ - m_localMap.clear(); - - AZStd::vector foundRenderNodes; - unsigned int numFoundObjects = 0; - - numFoundObjects = GetIEditor()->Get3DEngine()->GetObjectsByFlags(0); - foundRenderNodes.resize(numFoundObjects, nullptr); - GetIEditor()->Get3DEngine()->GetObjectsByFlags(0, foundRenderNodes.data()); - - AZStd::vector<_smart_ptr> materials; - materials.reserve(foundRenderNodes.size()); - for (IRenderNode* renderNode : foundRenderNodes) - { - renderNode->GetMaterials(materials); - } - - for (size_t i = 0; i < materials.size(); ++i) - { - if (materials[i]) - { - m_localMap[materials[i]->GetName()] = materials[i]; - } - } -} - -bool LevelMaterialSearchFilter::MatchInternal(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const -{ - // All entries match if show level materials isn't selected - if (!m_onlyShowLevelMaterials) - { - return true; - } - - // Get the product material for the given asset browser entry - AZ::Data::AssetId assetId = GetMaterialProductAssetIdFromAssetBrowserEntry(entry); - if (assetId.IsValid() && m_filterModel) - { - CMaterialBrowserRecord record; - bool found = m_filterModel->TryGetRecordFromAssetId(assetId, record); - if (found && record.m_material) - { - // If there is a valid product material, check to see if it is used by the level - return m_localMap.find(record.m_material->GetName()) != m_localMap.end(); - } - } - - return false; -} - -#include diff --git a/Code/Sandbox/Editor/Material/MaterialBrowserSearchFilters.h b/Code/Sandbox/Editor/Material/MaterialBrowserSearchFilters.h deleted file mode 100644 index 4326e66218..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialBrowserSearchFilters.h +++ /dev/null @@ -1,64 +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 -#endif - -class MaterialBrowserFilterModel; - -//! Filter that checks the name of each sub-material in a material to see if it contains the filter string -class SubMaterialSearchFilter - : public AzToolsFramework::AssetBrowser::AssetBrowserEntryFilter -{ - Q_OBJECT -public: - SubMaterialSearchFilter(const MaterialBrowserFilterModel* filterModel); - ~SubMaterialSearchFilter() override = default; - - void SetFilterString(const QString& filterString); - -protected: - QString GetNameInternal() const override; - bool MatchInternal(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; - -private: - bool TextMatchesFilter(const QString &text) const; - QString m_filterString = ""; - const MaterialBrowserFilterModel* m_filterModel = nullptr; -}; - -class LevelMaterialSearchFilter - : public AzToolsFramework::AssetBrowser::AssetBrowserEntryFilter -{ - Q_OBJECT -public: - LevelMaterialSearchFilter(const MaterialBrowserFilterModel* filterModel); - ~LevelMaterialSearchFilter() override = default; - - void ShowOnlyLevelMaterials(bool onlyLevel) { m_onlyShowLevelMaterials = onlyLevel; } - - void CacheLoadedMaterials(); - -protected: - QString GetNameInternal() const override; - bool MatchInternal(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry) const override; - -private: - bool m_onlyShowLevelMaterials = false; - const MaterialBrowserFilterModel* m_filterModel = nullptr; - using MaterialMap = QHash >; - MaterialMap m_localMap; -}; diff --git a/Code/Sandbox/Editor/Material/MaterialDialog.qrc b/Code/Sandbox/Editor/Material/MaterialDialog.qrc deleted file mode 100644 index c99e5b052a..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialDialog.qrc +++ /dev/null @@ -1,23 +0,0 @@ - - - images/material_browser_00.png - images/material_browser_01.png - images/material_browser_02.png - images/material_browser_03.png - images/material_00.png - images/material_01.png - images/material_02.png - images/material_03.png - images/material_04.png - images/material_05.png - images/material_06.png - images/material_07.png - images/filestatus_00.png - images/filestatus_01.png - images/filestatus_02.png - images/filestatus_03.png - images/filestatus_04.png - images/filestatus_05.png - images/filestatus_06.png - - diff --git a/Code/Sandbox/Editor/Material/MaterialHelpers.cpp b/Code/Sandbox/Editor/Material/MaterialHelpers.cpp deleted file mode 100644 index 8f9311a27a..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialHelpers.cpp +++ /dev/null @@ -1,372 +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 "MaterialHelpers.h" - -namespace MaterialHelpers -{ - ////////////////////////////////////////////////////////////////////////// - static void ParsePublicParamsScript(const char* sUIScript, IVariable* pVar) - { - string uiscript = sUIScript; - string element[3]; - int p1 = 0; - string itemToken = uiscript.Tokenize(";", p1); - while (!itemToken.empty()) - { - int nElements = 0; - int p2 = 0; - string token = itemToken.Tokenize(" \t\r\n=", p2); - while (!token.empty()) - { - element[nElements++] = token; - if (nElements == 2) - { - element[nElements] = itemToken.substr(p2); - element[nElements].Trim(" =\t\""); - break; - } - token = itemToken.Tokenize(" \t\r\n=", p2); - } - - float minLimit, maxLimit; - pVar->GetLimits(minLimit, maxLimit); - - if (azstricmp(element[1], "UIWidget") == 0) - { - if (azstricmp(element[2], "Color") == 0) - { - pVar->SetDataType(IVariable::DT_COLOR); - } - } - else if (azstricmp(element[1], "UIHelp") == 0) - { - string help = element[2]; - help.replace("\\n", "\n"); - pVar->SetDescription(help); - } - else if (azstricmp(element[1], "UIName") == 0) - { - pVar->SetHumanName(element[2].c_str()); - } - else if (azstricmp(element[1], "UIMin") == 0) - { - pVar->SetLimits(atof(element[2]), maxLimit); - } - else if (azstricmp(element[1], "UIMax") == 0) - { - pVar->SetLimits(minLimit, atof(element[2])); - } - else if (azstricmp(element[1], "UIStep") == 0) - { - } - - itemToken = uiscript.Tokenize(";", p1); - } - } - - ////////////////////////////////////////////////////////////////////////// - static void AddRealNameToDescription(IVariable* pIVar, const SShaderParam* pParam) - { - // In order to help the user discover the true names of parameters, info they need using certain script functions, - // we embed the real parameter name in the description. - QString description = pIVar->GetDescription(); - if (!description.isEmpty()) - { - description += "\n"; - } - description += "(Script Param Name = "; - description += pParam->m_Name.c_str(); - description += ")"; - pIVar->SetDescription(description); - } - - ////////////////////////////////////////////////////////////////////////// - CVarBlock* GetPublicVars(SInputShaderResources& pShaderResources) - { - if (pShaderResources.m_ShaderParams.empty()) - { - return 0; - } - - CVarBlock* pPublicVars = new CVarBlock; - for (int i = 0; i < pShaderResources.m_ShaderParams.size(); i++) - { - IVariable* pIVar = NULL; - SShaderParam* pParam = &pShaderResources.m_ShaderParams[i]; - - switch (pParam->m_Type) - { - case eType_BYTE: - pIVar = new CVariable(pParam->m_Value.m_Byte); - break; - case eType_SHORT: - pIVar = new CVariable(pParam->m_Value.m_Short); - break; - case eType_INT: - pIVar = new CVariable(pParam->m_Value.m_Int); - break; - case eType_FLOAT: - pIVar = new CVariable(pParam->m_Value.m_Float); - break; - /* case eType_STRING: - pIVar = new CVariable(pParam->m_Value.m_String); - break; */ - case eType_FCOLOR: - pIVar = new CVariable(Vec3(pParam->m_Value.m_Color[0], pParam->m_Value.m_Color[1], pParam->m_Value.m_Color[2])); - pIVar->SetDataType(IVariable::DT_COLOR); - break; - case eType_FCOLORA: - pIVar = new CVariable(Vec4(pParam->m_Value.m_Color[0], pParam->m_Value.m_Color[1], pParam->m_Value.m_Color[2], pParam->m_Value.m_Color[3])); - pIVar->SetDataType(IVariable::DT_COLORA); - break; - case eType_VECTOR: - pIVar = new CVariable(Vec3(pParam->m_Value.m_Vector[0], pParam->m_Value.m_Vector[1], pParam->m_Value.m_Vector[2])); - break; - default: - break; - } - - if (pIVar) - { - pIVar->SetName(pParam->m_Name.c_str()); - pPublicVars->AddVariable(pIVar); - - if (pParam->m_Script.size()) - { - ParsePublicParamsScript(pParam->m_Script.c_str(), pIVar); - } - - AddRealNameToDescription(pIVar, pParam); - } - } - - return pPublicVars; - } - - void SetPublicVars(CVarBlock* pPublicVars, SInputShaderResources& pInputShaderResources) - { - assert(pPublicVars); - - if (pInputShaderResources.m_ShaderParams.empty()) - { - return; - } - - int numVars = pPublicVars->GetNumVariables(); - - for (int i = 0; i < numVars; i++) - { - if (i >= numVars) - { - break; - } - - IVariable* pVar = pPublicVars->GetVariable(i); - SShaderParam* pParam = NULL; - for (int j = 0; j < pInputShaderResources.m_ShaderParams.size(); j++) - { - if (QString::compare(pVar->GetName(), pInputShaderResources.m_ShaderParams[j].m_Name.c_str()) == 0) - { - pParam = &pInputShaderResources.m_ShaderParams[j]; - break; - } - } - if (!pParam) - { - continue; - } - - switch (pParam->m_Type) - { - case eType_BYTE: - if (pVar->GetType() == IVariable::INT) - { - int val = 0; - pVar->Get(val); - pParam->m_Value.m_Byte = val; - } - break; - case eType_SHORT: - if (pVar->GetType() == IVariable::INT) - { - int val = 0; - pVar->Get(val); - pParam->m_Value.m_Short = val; - } - break; - case eType_INT: - if (pVar->GetType() == IVariable::INT) - { - int val = 0; - pVar->Get(val); - pParam->m_Value.m_Int = val; - } - break; - case eType_FLOAT: - if (pVar->GetType() == IVariable::FLOAT) - { - float val = 0; - pVar->Get(val); - pParam->m_Value.m_Float = val; - } - break; - /* - case eType_STRING: - if (pVar->GetType() == IVariable::STRING) - { - CString str; - int val = 0; - pVar->Get(val); - pParam->m_Value.m_Byte = val; - } - break; - */ - case eType_FCOLOR: - case eType_FCOLORA: - if (pVar->GetType() == IVariable::VECTOR4 && (pVar->GetDataType() == IVariable::DT_COLOR || pVar->GetDataType() == IVariable::DT_COLORA)) - { - Vec4 val(0, 0, 0, 0); - pVar->Get(val); - pParam->m_Value.m_Color[0] = val.x; - pParam->m_Value.m_Color[1] = val.y; - pParam->m_Value.m_Color[2] = val.z; - pParam->m_Value.m_Color[3] = val.w; - } - else if (pVar->GetType() == IVariable::VECTOR && (pVar->GetDataType() == IVariable::DT_COLOR || pVar->GetDataType() == IVariable::DT_COLORA)) - { - Vec3 val(0, 0, 0); - pVar->Get(val); - pParam->m_Value.m_Color[0] = val.x; - pParam->m_Value.m_Color[1] = val.y; - pParam->m_Value.m_Color[2] = val.z; - } - break; - case eType_VECTOR: - if (pVar->GetType() == IVariable::VECTOR) - { - Vec3 val(0, 0, 0); - pVar->Get(val); - pParam->m_Value.m_Vector[0] = val.x; - pParam->m_Value.m_Vector[1] = val.y; - pParam->m_Value.m_Vector[2] = val.z; - } - break; - default: - break; - } - } - } - - void SetPublicVars(CVarBlock* pPublicVars, SInputShaderResources& pInputShaderResources, IRenderShaderResources* pRenderShaderResources, IShader* pShader) - { - SetPublicVars(pPublicVars, pInputShaderResources); - - // Set shader params. - if (pRenderShaderResources) - { - pRenderShaderResources->SetShaderParams(&pInputShaderResources, pShader); - } - } - - ////////////////////////////////////////////////////////////////////////// - CVarBlock* GetShaderGenParamsVars(IShader* pShader, uint64 nShaderGenMask) - { - IShader* pTemplShader = pShader; - if (!pTemplShader) - { - return 0; - } - - SShaderGen* pShaderGen = pTemplShader->GetGenerationParams(); - if (!pShaderGen) - { - return 0; - } - - CVarBlock* pBlock = new CVarBlock; - for (int i = 0; i < pShaderGen->m_BitMask.size(); i++) - { - SShaderGenBit* pGenBit = pShaderGen->m_BitMask[i]; - if (pGenBit->m_Flags & SHGF_HIDDEN) - { - continue; - } - if (!pGenBit->m_ParamProp.empty()) - { - CVariable* pVar = new CVariable; - pBlock->AddVariable(pVar); - pVar->SetName(pGenBit->m_ParamProp.c_str()); - *pVar = (pGenBit->m_Mask & nShaderGenMask) != 0; - pVar->SetDescription(pGenBit->m_ParamDesc.c_str()); - } - } - - /* - // make sure if no valid generation parameters to not create new tab - if (!pBlock->GetVarsCount()) - { - SAFE_DELETE(pBlock); - return 0; - } - */ - - return pBlock; - } - - ////////////////////////////////////////////////////////////////////////// - uint64 SetShaderGenParamsVars(IShader* pShader, CVarBlock* pBlock) - { - IShader* pTemplShader = pShader; - if (!pTemplShader) - { - return 0; - } - - SShaderGen* pShaderGen = pTemplShader->GetGenerationParams(); - if (!pShaderGen) - { - return 0; - } - - uint64 nGenMask = 0; - - for (int i = 0; i < pShaderGen->m_BitMask.size(); i++) - { - SShaderGenBit* pGenBit = pShaderGen->m_BitMask[i]; - if (pGenBit->m_Flags & SHGF_HIDDEN) - { - continue; - } - - if (!pGenBit->m_ParamProp.empty()) - { - IVariable* pVar = pBlock->FindVariable(pGenBit->m_ParamProp.c_str()); - if (!pVar) - { - continue; - } - bool bFlagOn = false; - pVar->Get(bFlagOn); - if (bFlagOn) - { - nGenMask |= pGenBit->m_Mask; - } - } - } - - return nGenMask; - } -} diff --git a/Code/Sandbox/Editor/Material/MaterialHelpers.h b/Code/Sandbox/Editor/Material/MaterialHelpers.h deleted file mode 100644 index 0f0228db7a..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialHelpers.h +++ /dev/null @@ -1,67 +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 - -#include "Material.h" - -namespace MaterialHelpers -{ - ////////////////////////////////////////////////////////////////////////// - //! Get public parameters of material in variable block. - CVarBlock* GetPublicVars(SInputShaderResources& pShaderResources); - - //! Sets variable block of public shader parameters. - //! VarBlock must be in same format as returned by GetPublicVars(). - void SetPublicVars(CVarBlock* pPublicVars, SInputShaderResources& pInputShaderResources); - void SetPublicVars(CVarBlock* pPublicVars, SInputShaderResources& pInputShaderResources, IRenderShaderResources* pRenderShaderResources, IShader* pShader); - - ////////////////////////////////////////////////////////////////////////// - CVarBlock* GetShaderGenParamsVars(IShader* pShader, uint64 nShaderGenMask); - uint64 SetShaderGenParamsVars(IShader* pShader, CVarBlock* pBlock); - - ////////////////////////////////////////////////////////////////////////// - // [Shader System TO DO] change the usage of these functions to retrieve by slot name - inline EEfResTextures FindTexSlot(const char* texName) { return GetIEditor()->Get3DEngine()->GetMaterialHelpers().FindTexSlot(texName); } - inline const char* FindTexName(EEfResTextures texSlot) { return GetIEditor()->Get3DEngine()->GetMaterialHelpers().FindTexName(texSlot); } - inline const char* LookupTexName(EEfResTextures texSlot) { return GetIEditor()->Get3DEngine()->GetMaterialHelpers().LookupTexName(texSlot); } - inline const char* LookupTexDesc(EEfResTextures texSlot) { return GetIEditor()->Get3DEngine()->GetMaterialHelpers().LookupTexDesc(texSlot); } - - //-------------------------------------------------------------------------- - // Adjustable means that the slot is not virtual, i.e. using a sub-channel from another - // slot (for example - smoothness that uses the normal's alpha) - inline bool IsAdjustableTexSlot(EEfResTextures texSlot) { return GetIEditor()->Get3DEngine()->GetMaterialHelpers().IsAdjustableTexSlot(texSlot); } - - ////////////////////////////////////////////////////////////////////////// - inline void SetTexModFromXml(SEfTexModificator& pShaderResources, const XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetTexModFromXml(pShaderResources, node); } - inline void SetXmlFromTexMod(const SEfTexModificator& pShaderResources, XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetXmlFromTexMod(pShaderResources, node); } - - ////////////////////////////////////////////////////////////////////////// - inline void SetTexturesFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetTexturesFromXml(pShaderResources, node); } - inline void SetXmlFromTextures( SInputShaderResources& pShaderResources, XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetXmlFromTextures(pShaderResources, node); } - - ////////////////////////////////////////////////////////////////////////// - inline void SetVertexDeformFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetVertexDeformFromXml(pShaderResources, node); } - inline void SetXmlFromVertexDeform(const SInputShaderResources& pShaderResources, XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetXmlFromVertexDeform(pShaderResources, node); } - - ////////////////////////////////////////////////////////////////////////// - inline void SetLightingFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetLightingFromXml(pShaderResources, node); } - inline void SetXmlFromLighting(const SInputShaderResources& pShaderResources, XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetXmlFromLighting(pShaderResources, node); } - - ////////////////////////////////////////////////////////////////////////// - inline void SetShaderParamsFromXml(SInputShaderResources& pShaderResources, const XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetShaderParamsFromXml(pShaderResources, node); } - inline void SetXmlFromShaderParams(const SInputShaderResources& pShaderResources, XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().SetXmlFromShaderParams(pShaderResources, node); } - - ////////////////////////////////////////////////////////////////////////// - inline void MigrateXmlLegacyData(SInputShaderResources& pShaderResources, const XmlNodeRef& node) { GetIEditor()->Get3DEngine()->GetMaterialHelpers().MigrateXmlLegacyData(pShaderResources, node); } -} diff --git a/Code/Sandbox/Editor/Material/MaterialImageListCtrl.cpp b/Code/Sandbox/Editor/Material/MaterialImageListCtrl.cpp deleted file mode 100644 index 6ebc85c1bc..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialImageListCtrl.cpp +++ /dev/null @@ -1,834 +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 "MaterialImageListCtrl.h" - -// Qt -#include - -// Editor -#include "Material.h" -#include "MaterialManager.h" -#include "MaterialPreviewModelView.h" -#include "MaterialBrowser.h" -#include "Util/Image.h" - -#define ME_BG_TEXTURE "Materials/Stripes.dds" - - -#define MATERIAL_EDITOR_SPHERE_MODEL_FILE "Objects/MtlSphere.cgf" -#define MATERIAL_EDITOR_SPHERE_CAMERA_RADIUS 1.6f -#define MATERIAL_EDITOR_SPHERE_CAMERA_FROM_DIRECTION Vec3(0.1f, -1.0f, -0.1f) - -#define MATERIAL_EDITOR_BOX_MODEL_FILE "Objects/MtlBox.cgf" -#define MATERIAL_EDITOR_BOX_CAMERA_RADIUS 2.0f -#define MATERIAL_EDITOR_BOX_CAMERA_FROM_DIRECTION Vec3(0.75f, -0.75f, -0.5f) - -#define MATERIAL_EDITOR_TEAPOT_MODEL_FILE "Objects/MtlTeapot.cgf" -#define MATERIAL_EDITOR_TEAPOT_CAMERA_RADIUS 1.6f -#define MATERIAL_EDITOR_TEAPOT_CAMERA_FROM_DIRECTION Vec3(0.1f, -0.75f, -0.25f) - -#define MATERIAL_EDITOR_PLANE_MODEL_FILE "Objects/MtlPlane.cgf" -#define MATERIAL_EDITOR_PLANE_CAMERA_RADIUS 1.6f -#define MATERIAL_EDITOR_PLANE_CAMERA_FROM_DIRECTION Vec3(-0.5f, 0.5f, -0.5f) - -#define MATERIAL_EDITOR_SWATCH_MODEL_FILE "Objects/MtlSwatch.cgf" -#define MATERIAL_EDITOR_SWATCH_CAMERA_RADIUS 1.0f -#define MATERIAL_EDITOR_SWATCH_CAMERA_FROM_DIRECTION Vec3(0.0f, 0.0f, -1.0f) - - -_smart_ptr ResolveTerrainLayerPreviewMaterial(_smart_ptr material, _smart_ptr pMatPreview) -{ - if (!QString::compare(material->GetShaderName(), "Terrain.Layer")) - { - XmlNodeRef node = XmlHelpers::CreateXmlNode("Material"); - CBaseLibraryItem::SerializeContext ctx(node, false); - material->Serialize(ctx); - - if (!pMatPreview) - { - int flags = 0; - if (node->getAttr("MtlFlags", flags)) - { - flags |= MTL_FLAG_UIMATERIAL; - node->setAttr("MtlFlags", flags); - } - pMatPreview = GetIEditor()->GetMaterialManager()->CreateMaterial("_NewPreview_", node); - } - else - { - CBaseLibraryItem::SerializeContext ctx2(node, true); - pMatPreview->Serialize(ctx2); - } - pMatPreview->SetShaderName("Illum"); - pMatPreview->Update(); - return pMatPreview; - } - else - { - return material; - } -} - -struct QMaterialImageListModel::Item -{ - QImage image; - void* pUserData; - QPoint position; - QSize size; - _smart_ptr pMaterial; - QStringList vVisibleTextures; -}; - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::OnCreate() -{ - // m_largePreviewCtrl is used to draw the 3D preview for the selected material - m_largePreviewCtrl.reset(new MaterialPreviewModelView(this)); - m_largePreviewCtrl->hide(); - // m_renderCtrl is used to draw all the sub-materials - m_renderCtrl.reset(new MaterialPreviewModelView(this, false /* disable idle updates since this is only used to create the preview list images */)); - m_renderCtrl->UnSetFlag(CPreviewModelView::PreviewModelViewFlag::SHOW_GRID); - m_renderCtrl->UnSetFlag(CPreviewModelView::PreviewModelViewFlag::SHOW_GRID_AXIS); - - if (gEnv->pSystem) - { - gEnv->pSystem->GetISystemEventDispatcher()->RegisterListener(this); - } - - // m_resizeTimer is used to stall updateGeometries being called via resizeEvents until RESIZE_TIMEOUT ms after resizing - // This prevents an Editor freeze caused by constant resizing of the Material Editor when viewing - // a high sub-material count material (LY-58389) - m_resizeTimer = new QTimer(this); - connect(m_resizeTimer, &QTimer::timeout, this, &CMaterialImageListCtrl::ResizeTimeout); -} - -void CMaterialImageListCtrl::resizeEvent([[maybe_unused]] QResizeEvent* event) -{ - m_resizeTimer->stop(); - m_resizeTimer->start(RESIZE_TIMEOUT); -} - -void CMaterialImageListCtrl::ResizeTimeout() -{ - m_resizeTimer->stop(); - updateGeometries(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::OnDestroy() -{ - if (gEnv->pSystem) - { - gEnv->pSystem->GetISystemEventDispatcher()->RemoveListener(this); - } -} - -////////////////////////////////////////////////////////////////////////// -CMaterialImageListCtrl::CMaterialImageListCtrl(QWidget* parent) - : CImageListCtrl(parent) -{ - OnCreate(); -} - -////////////////////////////////////////////////////////////////////////// -CMaterialImageListCtrl::~CMaterialImageListCtrl() -{ - OnDestroy(); -} - -////////////////////////////////////////////////////////////////////////// -QModelIndex QMaterialImageListModel::AddMaterial(CMaterial* pMaterial, void* pUserData) -{ - Item* pItem = new Item; - pItem->pMaterial = pMaterial; - pItem->pUserData = pUserData; - pMaterial->GetAnyTextureFilenames(pItem->vVisibleTextures); - - const int row = m_items.count(); - beginInsertRows(QModelIndex(), row, row); - m_items.insert(row, pItem); - endInsertRows(); - - return index(row, 0); -} - -////////////////////////////////////////////////////////////////////////// -void QMaterialImageListModel::SetMaterial(int nItemIndex, CMaterial* pMaterial, void* pUserData) -{ - assert(nItemIndex <= (int)m_items.size()); - Item* pItem = m_items.at(nItemIndex); - - pItem->vVisibleTextures.clear(); - pItem->pMaterial = pMaterial; - pItem->pUserData = pUserData; - pMaterial->GetAnyTextureFilenames(pItem->vVisibleTextures); - pItem->image = QImage(); - - QModelIndex idx = index(nItemIndex, 0); - emit dataChanged(idx, idx, QVector() << Qt::DisplayRole << Qt::DecorationRole); -} - -////////////////////////////////////////////////////////////////////////// -QModelIndex QMaterialImageListModel::FindMaterial(CMaterial* const pMaterial) -{ - for (int i = 0; i < m_items.count(); i++) - { - Item* item = m_items[i]; - if (pMaterial == item->pMaterial) - { - return index(i, 0); - } - } - return QModelIndex(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::SelectMaterial(CMaterial* pMaterial) -{ - // Force the material to load the highest resolution textures - pMaterial->GetMatInfo()->DisableTextureStreaming(); - - selectionModel()->clearSelection(); - - QMaterialImageListModel* materialModel = qobject_cast(model()); - Q_ASSERT(materialModel); - - QModelIndex index = materialModel->FindMaterial(pMaterial); - if (index.isValid()) - { - selectionModel()->select(index, QItemSelectionModel::SelectCurrent); - m_largePreviewMaterial = pMaterial; - } - else - { - // If the parent material was selected, set the first sub-material as the large preview's material so it has something to render - if (pMaterial->GetSubMaterialCount() > 0) - { - m_largePreviewMaterial = pMaterial->GetSubMaterial(0); - } - } - - GenerateAllImages(); -} - -////////////////////////////////////////////////////////////////////////// -void QMaterialImageListModel::InvalidateMaterial(CMaterial* pMaterial) -{ - QModelIndex idx = FindMaterial(pMaterial); - Item* pItem = ItemFromIndex(idx); - if ((pItem) && (m_renderCtrl)) - { - if (pMaterial) - { - // Ensure the full resolution textures are loaded for the material editor - pMaterial->GetMatInfo()->DisableTextureStreaming(); - } - - pItem->vVisibleTextures.clear(); - pMaterial->GetAnyTextureFilenames(pItem->vVisibleTextures); - pItem->image = QImage(); - GenerateImage(pItem); - - emit dataChanged(idx, idx, QVector() << Qt::DecorationRole); - } -} - -////////////////////////////////////////////////////////////////////////// -void QMaterialImageListModel::DeleteAllItems() -{ - if (m_renderCtrl) - { - m_renderCtrl->SetMaterial(nullptr); - } - beginResetModel(); - qDeleteAll(m_items); - m_items.clear(); - endResetModel(); -} - -////////////////////////////////////////////////////////////////////////// -void QMaterialImageListModel::GenerateImage(Item* pItem) -{ - // Make a bitmap from image. - Q_ASSERT(pItem); - if (!m_renderCtrl || !pItem->size.isValid()) - { - return; - } - if (pItem->image.size() == pItem->size) - { - return; - } - - Item* pMtlItem = pItem; - - CImageEx image; - - bool bPreview = false; - if (pMtlItem->pMaterial) - { - if (!(pMtlItem->pMaterial->GetFlags() & MTL_FLAG_NOPREVIEW)) - { - if (!m_renderCtrl->GetStaticModel()) - { - AZ_Warning("Material Editor", false, "Preview renderer has no object loaded!"); - return; - } - - // keep m_renderCtrl off screen, but visible - m_renderCtrl->setGeometry(QRect(-QPoint(pItem->size.width(), pItem->size.height()), pItem->size)); - - _smart_ptr matPreview = ResolveTerrainLayerPreviewMaterial(pItem->pMaterial, m_pMatPreview); - - m_renderCtrl->SetMaterial(matPreview->GetMatInfo()); - m_renderCtrl->GetImageOffscreen(image, pMtlItem->size); - } - bPreview = true; - } - - if (!bPreview) - { - image.Allocate(pItem->size.width(), pItem->size.height()); - image.Clear(); - } - - pItem->image = QImage(image.GetWidth(), image.GetHeight(), QImage::Format_RGB32); - memcpy(pItem->image.bits(), image.GetData(), image.GetSize()); -} - - -#define MENU_USE_DEFAULT 1 -#define MENU_USE_BOX 2 -#define MENU_USE_PLANE 3 -#define MENU_USE_SPHERE 4 -#define MENU_USE_TEAPOT 5 -#define MENU_BG_BLACK 6 -#define MENU_BG_GRAY 7 -#define MENU_BG_WHITE 8 -#define MENU_BG_TEXTURE 9 -#define MENU_USE_BACKLIGHT 10 - - - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::contextMenuEvent(QContextMenuEvent* event) -{ - QAction* action; - QMenu menu; - - action = menu.addAction(tr("Use Default Object")); - action->setData(ModelDefault); - action->setCheckable(true); - action->setChecked(m_modelType == ModelType::Default); - - action = menu.addAction(tr("Use Plane")); - action->setData(ModelPlane); - action->setCheckable(true); - action->setChecked(m_modelType == ModelType::Plane); - - action = menu.addAction(tr("Use Box")); - action->setData(ModelBox); - action->setCheckable(true); - action->setChecked(m_modelType == ModelType::Box); - - action = menu.addAction(tr("Use Sphere")); - action->setData(ModelSphere); - action->setCheckable(true); - action->setChecked(m_modelType == ModelType::Sphere); - - action = menu.addAction(tr("Use Teapot")); - action->setData(ModelTeapot); - action->setCheckable(true); - action->setChecked(m_modelType == ModelType::Teapot); - - menu.addSeparator(); - - // If there is a currently selected material - if (m_materialBrowserWidget && m_largePreviewMaterial) - { - // Add context menu actions that are common to both the material browser and the preview swatches - m_materialBrowserWidget->AddContextMenuActionsSingleSelection(menu, m_largePreviewMaterial); - } - - action = menu.exec(mapToGlobal(event->pos())); - if (!action) - { - return; - } - - int cmd = action->data().toInt(); - switch (cmd) - { - case ModelDefault: - m_modelType = ModelType::Default; - LoadModel(); - break; - case ModelPlane: - m_modelType = ModelType::Plane; - LoadModel(); - break; - case ModelBox: - m_modelType = ModelType::Box; - LoadModel(); - break; - case ModelSphere: - m_modelType = ModelType::Sphere; - LoadModel(); - break; - case ModelTeapot: - m_modelType = ModelType::Teapot; - LoadModel(); - break; - default: - // If there is a currently selected material - if (m_materialBrowserWidget && m_largePreviewMaterial) - { - // Handle context menu actions that are common to both the material browser and the preview swatches - m_materialBrowserWidget->OnContextMenuAction(cmd, m_largePreviewMaterial); - } - break; - } - - QMaterialImageListModel* materialModel = - qobject_cast(model()); - Q_ASSERT(materialModel); - - materialModel->GenerateImages(); - update(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::LoadModel() -{ - switch (m_modelType) - { - case ModelType::Default: - case ModelType::Sphere: - m_largePreviewCtrl->LoadModelFile(MATERIAL_EDITOR_SPHERE_MODEL_FILE); - m_largePreviewCtrl->SetCameraLookAt(MATERIAL_EDITOR_SPHERE_CAMERA_RADIUS, MATERIAL_EDITOR_SPHERE_CAMERA_FROM_DIRECTION); - break; - case ModelType::Box: - m_largePreviewCtrl->LoadModelFile(MATERIAL_EDITOR_BOX_MODEL_FILE); - m_largePreviewCtrl->SetCameraLookAt(MATERIAL_EDITOR_BOX_CAMERA_RADIUS, MATERIAL_EDITOR_BOX_CAMERA_FROM_DIRECTION); - break; - case ModelType::Teapot: - m_largePreviewCtrl->LoadModelFile(MATERIAL_EDITOR_TEAPOT_MODEL_FILE); - m_largePreviewCtrl->SetCameraLookAt(MATERIAL_EDITOR_TEAPOT_CAMERA_RADIUS, MATERIAL_EDITOR_TEAPOT_CAMERA_FROM_DIRECTION); - break; - case ModelType::Plane: - m_largePreviewCtrl->LoadModelFile(MATERIAL_EDITOR_PLANE_MODEL_FILE); - m_largePreviewCtrl->SetCameraLookAt(MATERIAL_EDITOR_PLANE_CAMERA_RADIUS, MATERIAL_EDITOR_PLANE_CAMERA_FROM_DIRECTION); - break; - } - - GenerateAllImages(); -} - - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::updateGeometries() -{ - ClearItemGeometries(); - m_updatingGeometries = true; - - if (!model()) - { - return; - } - - const int rowCount = model()->rowCount(); - if (!rowCount) - { - m_largePreviewCtrl->hide(); - m_largePreviewMaterial = nullptr; - return; - } - m_largePreviewCtrl->setParent(nullptr); - m_largePreviewCtrl->setParent(this); - m_largePreviewCtrl->show(); - - const int bwidth = BorderSize().width(); - const int bheight = BorderSize().height(); - m_largePreviewCtrl->move(bwidth, bheight); - - QRect rc = viewport()->contentsRect() - .adjusted(bwidth, bheight, -bwidth, -bheight); - - int cy = rc.height(); - - // Preview item is big. - if (model()->rowCount() > 0) - { - QSize size(cy, rc.height()); - m_largePreviewCtrl->SetSize(size); - m_largePreviewCtrl->resize(size); - rc.setLeft(rc.left() + cy + bwidth * 2); - m_largePreviewCtrl->show(); - } - - int cx = rc.width() - bwidth; - - int itemSize = cy; - - // Adjust all other bitmaps as tight as possible. - int numItems = model()->rowCount(); - int div = 0; - for (div = 1; div < 1000 && itemSize > 0; div++) - { - int nX = cx / (itemSize + 2); - if (nX >= numItems) - { - break; - } - if (nX > 0) - { - int nY = numItems / nX + 1; - if (nY * (itemSize + 2) < cy) - { - //itemSize = itemSize -= 2; - break; - } - } - itemSize = itemSize -= 2; - } - if (itemSize < 0) - { - itemSize = 0; - } - - QPoint pos(rc.topLeft()); - const QSize size(itemSize, itemSize); - m_renderCtrl->SetSize(size); - for (int row = 0; row < numItems; ++row) - { - QModelIndex index = model()->index(row, 0); - SetItemGeometry(index, QRect(pos, size)); - model()->setData(index, pos, QMaterialImageListModel::PositionRole); - model()->setData(index, size, Qt::SizeHintRole); - pos.rx() += itemSize + 2; - if (pos.rx() + itemSize >= rc.right()) - { - pos.rx() = rc.left(); - pos.ry() += itemSize + 2; - } - } - - m_updatingGeometries = false; - update(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::setModel(QAbstractItemModel* model) -{ - QMaterialImageListModel* materialModel = qobject_cast(model); - if (materialModel) - { - materialModel->SetPreviewModelCtrl(m_renderCtrl.data()); - } - - CImageListCtrl::setModel(model); - - auto delegate = qobject_cast(itemDelegate()); - // in case the delegate misses a pixmap we can generate it (done only once not at every painting) - connect(delegate, SIGNAL(invalidPixmapGenerated(const QModelIndex&)), materialModel, SLOT(GenerateImage(const QModelIndex&))); - connect(model, &QAbstractItemModel::dataChanged, this, &CMaterialImageListCtrl::ModelDataChanged); -} - -void CMaterialImageListCtrl::ModelDataChanged(const QModelIndex& index) -{ - // Prevent the hundreads of resize calls done in a row - // to trigger a new image computation that we already have - if (m_updatingGeometries) - { - return; - } - - GenerateImage(index); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::showEvent(QShowEvent* event) -{ - CImageListCtrl::showEvent(event); - - if (!m_largePreviewCtrl->GetStaticModel()) - { - LoadModel(); - } - if (!m_renderCtrl->GetStaticModel()) - { - m_renderCtrl->LoadModelFile(MATERIAL_EDITOR_SWATCH_MODEL_FILE); - m_renderCtrl->SetCameraLookAt(MATERIAL_EDITOR_SWATCH_CAMERA_RADIUS, MATERIAL_EDITOR_SWATCH_CAMERA_FROM_DIRECTION); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialImageListCtrl::OnSystemEvent(ESystemEvent event, UINT_PTR wparam, [[maybe_unused]] UINT_PTR lparam) -{ - switch (event) - { - // Toggle visibility of this control whenever the main editor window has a change of focus. - case ESYSTEM_EVENT_CHANGE_FOCUS: - { - setAttribute(Qt::WA_WState_Visible, (wparam != 0)); - break; - } - } - ; -} - -void CMaterialImageListCtrl::UpdateLargePreview() -{ - if (m_largePreviewMaterial) - { - m_largePreviewCtrl->SetMaterial(ResolveTerrainLayerPreviewMaterial(m_largePreviewMaterial, m_tempTerrainMaterial)->GetMatInfo()); - m_largePreviewCtrl->show(); - m_largePreviewCtrl->update(); - } -} - -void CMaterialImageListCtrl::GenerateImage(const QModelIndex& index) -{ - QMaterialImageListModel* materialModel = - qobject_cast(model()); - Q_ASSERT(materialModel); - if (m_largePreviewMaterial == materialModel->MaterialFromIndex(index)) - { - UpdateLargePreview(); - } - - materialModel->SetPreviewModelCtrl(m_renderCtrl.data()); - materialModel->GenerateImage(index); - update(); -} - -void CMaterialImageListCtrl::GenerateAllImages() -{ - QMaterialImageListModel* materialModel = - qobject_cast(model()); - Q_ASSERT(materialModel); - - UpdateLargePreview(); - - materialModel->SetPreviewModelCtrl(m_renderCtrl.data()); - materialModel->GenerateImages(); - update(); -} - -////////////////////////////////////////////////////////////////////////// -QMaterialImageListModel::QMaterialImageListModel(QObject* parent) - : QAbstractListModel(parent) - , m_renderCtrl(nullptr) -{ - BusConnect(AZ_CRC("dds", 0x780234cb)); -} - -////////////////////////////////////////////////////////////////////////// -QMaterialImageListModel::~QMaterialImageListModel() -{ - BusDisconnect(); - - qDeleteAll(m_items); -} - -////////////////////////////////////////////////////////////////////////// -MaterialPreviewModelView* QMaterialImageListModel::PreviewModelCtrl() const -{ - return m_renderCtrl; -} - -////////////////////////////////////////////////////////////////////////// -void QMaterialImageListModel::SetPreviewModelCtrl(MaterialPreviewModelView* ctrl) -{ - if (m_renderCtrl) - { - disconnect(m_renderCtrl, &MaterialPreviewModelView::destroyed, - this, &QMaterialImageListModel::ClearPreviewModelCtrl); - } - - m_renderCtrl = ctrl; - - if (m_renderCtrl) - { - connect(m_renderCtrl, &MaterialPreviewModelView::destroyed, - this, &QMaterialImageListModel::ClearPreviewModelCtrl); - } -} - -////////////////////////////////////////////////////////////////////////// -void QMaterialImageListModel::ClearPreviewModelCtrl() -{ - m_renderCtrl = nullptr; -} - -////////////////////////////////////////////////////////////////////////// -int QMaterialImageListModel::rowCount(const QModelIndex& parent) const -{ - if (parent.isValid()) - { - return 0; - } - - return m_items.count(); -} - -////////////////////////////////////////////////////////////////////////// -QVariant QMaterialImageListModel::data(const QModelIndex& index, int role) const -{ - if (!index.isValid()) - { - return QVariant(); - } - - Item* pItem = m_items.at(index.row()); - Q_ASSERT(pItem); - - switch (role) - { - case Qt::DisplayRole: - return pItem->pMaterial->GetShortName(); - - case Qt::DecorationRole: - return QPixmap::fromImage(pItem->image); - - case PositionRole: - return pItem->position; - - case Qt::SizeHintRole: - return pItem->size; - - default: - break; - } - - return QVariant(); -} - -////////////////////////////////////////////////////////////////////////// -bool QMaterialImageListModel::setData(const QModelIndex& index, const QVariant& value, int role) -{ - if (!index.isValid()) - { - return false; - } - - Item* pItem = ItemFromIndex(index); - if (!pItem) - { - return false; - } - - if (Qt::SizeHintRole == role) - { - pItem->size = value.toSize(); - emit dataChanged(index, index, QVector() << Qt::DecorationRole << Qt::SizeHintRole); - return true; - } - - if (PositionRole == role) - { - pItem->position = value.toPoint(); - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -Qt::ItemFlags QMaterialImageListModel::flags(const QModelIndex& index) const -{ - return QAbstractListModel::flags(index); -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* QMaterialImageListModel::MaterialFromIndex(QModelIndex index) const -{ - Item* pItem = ItemFromIndex(index); - if (!pItem) - { - return nullptr; - } - - return pItem->pMaterial; -} - -////////////////////////////////////////////////////////////////////////// -void* QMaterialImageListModel::UserDataFromIndex(QModelIndex index) const -{ - Item* pItem = ItemFromIndex(index); - if (!pItem) - { - return nullptr; - } - - return pItem->pUserData; -} - -////////////////////////////////////////////////////////////////////////// -void QMaterialImageListModel::GenerateImages() -{ - if ((!m_renderCtrl) || (m_items.isEmpty())) - { - return; - } - - for (Item* materialImageListItem : m_items) - { - GenerateImage(materialImageListItem); - } -} - -void QMaterialImageListModel::GenerateImage(const QModelIndex& index) -{ - if ((!m_renderCtrl) || (m_items.isEmpty())) - { - return; - } - - GenerateImage(ItemFromIndex(index)); -} - -////////////////////////////////////////////////////////////////////////// -QMaterialImageListModel::Item* QMaterialImageListModel::ItemFromIndex(QModelIndex index) const -{ - if (!index.isValid()) - { - return nullptr; - } - - return m_items.at(index.row()); -} - -////////////////////////////////////////////////////////////////////////// -void QMaterialImageListModel::OnFileChanged(AZStd::string assetPath) -{ - const int rowCount = m_items.count(); - - // update all previews who's texture(s) changed - for (int row = 0; row < rowCount; ++row) - { - Item* pItem = m_items.at(row); - - QStringList::const_iterator textureIt = std::find(pItem->vVisibleTextures.begin(), pItem->vVisibleTextures.end(), assetPath.c_str()); - if (textureIt != pItem->vVisibleTextures.end()) - { - pItem->image = QImage(); - QModelIndex idx = index(row, 0); - emit dataChanged(idx, idx, QVector() << Qt::DecorationRole); - } - } -} - -#include diff --git a/Code/Sandbox/Editor/Material/MaterialImageListCtrl.h b/Code/Sandbox/Editor/Material/MaterialImageListCtrl.h deleted file mode 100644 index fe9742fb53..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialImageListCtrl.h +++ /dev/null @@ -1,164 +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_MATERIAL_MATERIALIMAGELISTCTRL_H -#define CRYINCLUDE_EDITOR_MATERIAL_MATERIALIMAGELISTCTRL_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "Controls/ImageListCtrl.h" -#include -#include "Material.h" -#include "IRenderer.h" // IAsyncTextureCompileListener -#include "IResourceCompilerHelper.h" -#include - -#include -#include -#endif - -class MaterialPreviewModelView; -class MaterialBrowserWidget; - -////////////////////////////////////////////////////////////////////////// -class CMaterialImageListCtrl - : public CImageListCtrl - , public ISystemEventListener -{ - Q_OBJECT -public: - - enum class ModelType - { - Default, - Box, - Sphere, - Teapot, - Plane - }; - - enum MenuAction - { - ModelDefault = 0, - ModelPlane, - ModelBox, - ModelSphere, - ModelTeapot, - // Context menu actions that are common to both the material browser and the preview swatches - // are handled by the same switch statement, so they need to be unique. This sets the starting point for the common actions - MaterialBrowserWidgetActionsStart - }; - - CMaterialImageListCtrl(QWidget* parent = nullptr); - ~CMaterialImageListCtrl(); - - void setModel(QAbstractItemModel* model) override; - - void EnableAutoRefresh(bool autoRefreshState, unsigned int refreshInterval); - void SelectMaterial(CMaterial* pMaterial); - void LoadModel(); - void SetMaterialBrowserWidget(MaterialBrowserWidget* materialBrowserWidget){ m_materialBrowserWidget = materialBrowserWidget; } - // ISystemEventListener - // Due to the material editor working on a ProcessEvents -> Timer based system, rather than the OnIdle update event loops - // that the other editor windows use, make sure that when the editor loses focus that the Material Editor itself loses focus. - // This will pause updates/renderings in the material editor when it does not have focus. - // This prevents certain materials from re-creating themselves and eventually overflowing a few resource buffers. - // The main window cleans up those resources during its main update, which is bypassed when the window does not have focus. - virtual void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam); - // ~ISystemEventListener - - // Override resizeEvent and use this const to rate limit it such that it only fires RESIZE_TIMEOUT ms after resizing stops - static const int RESIZE_TIMEOUT = 100; - void resizeEvent(QResizeEvent* event) override; - -public slots: - void ModelDataChanged(const QModelIndex& index); - void ResizeTimeout(); -protected: - void OnCreate(); - void OnDestroy(); - - void contextMenuEvent(QContextMenuEvent* event) override; - void showEvent(QShowEvent* event) override; - void updateGeometries() override; - -private: - void GenerateImage(const QModelIndex& index); - void GenerateAllImages(); - void UpdateLargePreview(); - - QScopedPointer m_largePreviewCtrl; // Used to draw the main 3D preview viewport for the selected sub-material - _smart_ptr m_largePreviewMaterial; - _smart_ptr m_tempTerrainMaterial; - QScopedPointer m_renderCtrl; // Used to draw the swatches for all the sub-materials - int m_nColor; - bool m_updatingGeometries = false; - ModelType m_modelType = ModelType::Default; - MaterialBrowserWidget* m_materialBrowserWidget; - QTimer* m_resizeTimer; // Used to stall a resizeEvent from firing until RESIZE_TIMEOUT ms have passed since resizing stopped -}; - -class QMaterialImageListModel - : public QAbstractListModel - , public AzFramework::LegacyAssetEventBus::Handler -{ - struct Item; - Q_OBJECT - -public: - enum CustomRoles - { - PositionRole = Qt::UserRole - }; - - QMaterialImageListModel(QObject* parent = nullptr); - ~QMaterialImageListModel(); - - int rowCount(const QModelIndex& parent = QModelIndex()) const override; - QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override; - bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override; - Qt::ItemFlags flags(const QModelIndex& index) const override; - - QModelIndex AddMaterial(CMaterial* pMaterial, void* pUserData = nullptr); - void SetMaterial(int nItemIndex, CMaterial* pMaterial, void* pUserData = nullptr); - QModelIndex FindMaterial(CMaterial* pMaterial); - void InvalidateMaterial(CMaterial* pMaterial); - void DeleteAllItems(); - - MaterialPreviewModelView* PreviewModelCtrl() const; - void SetPreviewModelCtrl(MaterialPreviewModelView* ctrl); - - CMaterial* MaterialFromIndex(QModelIndex index) const; - void* UserDataFromIndex(QModelIndex index) const; - -public slots: - void GenerateImages(); - void GenerateImage(const QModelIndex& index); - -protected: - void GenerateImage(Item* pItem); - Item* ItemFromIndex(QModelIndex index) const; - -private slots: - void ClearPreviewModelCtrl(); - -private: - void OnFileChanged(AZStd::string assetPath) override; - -private: - _smart_ptr m_pMatPreview; - QPointer m_renderCtrl; - QVector m_items; -}; - -#endif // CRYINCLUDE_EDITOR_MATERIAL_MATERIALIMAGELISTCTRL_H diff --git a/Code/Sandbox/Editor/Material/MaterialLibrary.cpp b/Code/Sandbox/Editor/Material/MaterialLibrary.cpp deleted file mode 100644 index 351eee5c63..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialLibrary.cpp +++ /dev/null @@ -1,151 +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 "MaterialLibrary.h" - -// Editor -#include "BaseLibraryItem.h" - - -////////////////////////////////////////////////////////////////////////// -// CMaterialLibrary implementation. -////////////////////////////////////////////////////////////////////////// -bool CMaterialLibrary::Save() -{ - return SaveLibrary("MaterialLibrary"); -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterialLibrary::Load(const QString& filename) -{ - if (filename.isEmpty()) - { - return false; - } - SetFilename(filename); - XmlNodeRef root = XmlHelpers::LoadXmlFromFile(filename.toUtf8().data()); - if (!root) - { - return false; - } - - Serialize(root, true); - return true; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialLibrary::Serialize([[maybe_unused]] XmlNodeRef& root, [[maybe_unused]] bool bLoading) -{ - /* - if (bLoading) - { - // Loading. - CString name = GetName(); - root->getAttr( "Name",name ); - SetName( name ); - for (int i = 0; i < root->getChildCount(); i++) - { - XmlNodeRef itemNode = root->getChild(i); - CMaterial *material = new CMaterial(itemNode->getAttr("Name")); - AddItem( material ); - CBaseLibraryItem::SerializeContext ctx( itemNode,bLoading ); - material->Serialize( ctx ); - } - SetModified(false); - } - else - { - // Saving. - root->setAttr( "Name",GetName() ); - root->setAttr( "SandboxVersion",(const char*)GetIEditor()->GetFileVersion().ToFullString() ); - // Serialize prototypes. - for (int i = 0; i < GetItemCount(); i++) - { - CMaterial *pMtl = (CMaterial*)GetItem(i); - // Save materials with parents under thier parent xml node. - if (pMtl->GetParent()) - continue; - - XmlNodeRef itemNode = root->newChild( "Material" ); - CBaseLibraryItem::SerializeContext ctx( itemNode,bLoading ); - GetItem(i)->Serialize( ctx ); - } - } - */ -} - -////////////////////////////////////////////////////////////////////////// -////////////////////////////////////////////////////////////////////////// -void CMaterialLibrary::AddItem(IDataBaseItem* item, bool bRegister) -{ - CBaseLibraryItem* pLibItem = (CBaseLibraryItem*)item; - // Check if item is already assigned to this library. - if (pLibItem->GetLibrary() != this) - { - pLibItem->SetLibrary(this); - if (bRegister) - { - m_pManager->RegisterItem(pLibItem); - } - m_items.push_back(pLibItem); - } -} - -////////////////////////////////////////////////////////////////////////// -IDataBaseItem* CMaterialLibrary::GetItem(int index) -{ - assert(index >= 0 && index < m_items.size()); - return m_items[index]; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialLibrary::RemoveItem(IDataBaseItem* item) -{ - for (int i = 0; i < m_items.size(); i++) - { - if (m_items[i] == item) - { - m_items.erase(m_items.begin() + i); - SetModified(); - break; - } - } -} - -////////////////////////////////////////////////////////////////////////// -IDataBaseItem* CMaterialLibrary::FindItem(const QString& name) -{ - for (int i = 0; i < m_items.size(); i++) - { - if (QString::compare(m_items[i]->GetName(), name, Qt::CaseInsensitive) == 0) - { - return m_items[i]; - } - } - return NULL; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialLibrary::RemoveAllItems() -{ - AddRef(); - for (int i = 0; i < m_items.size(); i++) - { - // Clear library item. - m_items[i]->SetLibrary(NULL); - } - m_items.clear(); - Release(); -} diff --git a/Code/Sandbox/Editor/Material/MaterialLibrary.h b/Code/Sandbox/Editor/Material/MaterialLibrary.h deleted file mode 100644 index 5a80500e94..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialLibrary.h +++ /dev/null @@ -1,47 +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_MATERIAL_MATERIALLIBRARY_H -#define CRYINCLUDE_EDITOR_MATERIAL_MATERIALLIBRARY_H -#pragma once - -#include "BaseLibrary.h" - -/** Library of prototypes. -*/ -class CRYEDIT_API CMaterialLibrary - : public CBaseLibrary -{ -public: - CMaterialLibrary(IBaseLibraryManager* pManager) - : CBaseLibrary(pManager) {}; - virtual bool Save(); - virtual bool Load(const QString& filename); - virtual void Serialize(XmlNodeRef& node, bool bLoading); - - ////////////////////////////////////////////////////////////////////////// - // CBaseLibrary override. - ////////////////////////////////////////////////////////////////////////// - void AddItem(IDataBaseItem* item, bool bRegister = true); - int GetItemCount() const { return m_items.size(); } - IDataBaseItem* GetItem(int index); - void RemoveItem(IDataBaseItem* item); - void RemoveAllItems(); - IDataBaseItem* FindItem(const QString& name); -private: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::vector m_items; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // CRYINCLUDE_EDITOR_MATERIAL_MATERIALLIBRARY_H diff --git a/Code/Sandbox/Editor/Material/MaterialManager.cpp b/Code/Sandbox/Editor/Material/MaterialManager.cpp deleted file mode 100644 index 51460ff34a..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialManager.cpp +++ /dev/null @@ -1,2095 +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 "MaterialManager.h" - -// Qt -#include - -// AzCore -#include - -// AzFramework -#include - -// AzToolsFramework -#include -#include -#include - -// Editor -#include "MainWindow.h" -#include "MaterialLibrary.h" -#include "MaterialSender.h" -#include "MaterialUtils.h" -#include "ModelViewport.h" -#include "ISourceControl.h" -#include "UsedResources.h" -#include "Viewport.h" -#include "Commands/CommandManager.h" -#include "Include/IObjectManager.h" -#include "Objects/BaseObject.h" -#include "Objects/SelectionGroup.h" - - -static const char* MATERIALS_LIBS_PATH = "Materials/"; -static unsigned int s_highlightUpdateCounter = 0; - -// Convert a material name into a material identifier (no extension, no gamename, etc) so that it can be compared -// in the hash. -static QString UnifyMaterialName(const QString& source) -{ - char tempBuffer[AZ_MAX_PATH_LEN]; - azstrncpy(tempBuffer, AZ_ARRAY_SIZE(tempBuffer), source.toUtf8().data(), AZ_ARRAY_SIZE(tempBuffer) - 1); - MaterialUtils::UnifyMaterialName(tempBuffer); - return QString(tempBuffer); -} - -struct SHighlightMode -{ - float m_colorHue; - float m_period; - bool m_continuous; -}; - -static SHighlightMode g_highlightModes[] = { - { 0.70f, 0.8f, true }, // purple - { 0.25f, 0.75f, false }, // green - { 0.0, 0.75f, true } // red -}; - -class CMaterialHighlighter -{ -public: - void Start(CMaterial* pMaterial, int modeFlag); - void Stop(CMaterial* pMaterial, int modeFlag); - void GetHighlightColor(ColorF* color, float* intensity, int flags); - - void ClearMaterials() { m_materials.clear(); }; - void RestoreMaterials(); - void Update(); -private: - struct SHighlightOptions - { - int m_modeFlags; - }; - - typedef std::map Materials; - Materials m_materials; -}; - -AZStd::string DccMaterialToSourcePath(const AZStd::string& relativeDccMaterialPath) -{ - AZStd::string fullSourcePath; - bool sourcePathFound = false; - - // Get source path using relative .dccmtl path - AzToolsFramework::AssetSystemRequestBus::BroadcastResult(sourcePathFound, &AzToolsFramework::AssetSystemRequestBus::Events::GetFullSourcePathFromRelativeProductPath, relativeDccMaterialPath, fullSourcePath); - - if (sourcePathFound) - { - // Set source path extension to ".mtl" - AzFramework::StringFunc::Path::ReplaceExtension(fullSourcePath, MATERIAL_FILE_EXT); - } - return fullSourcePath; -} - - -void CMaterialHighlighter::Start(CMaterial* pMaterial, int modeFlag) -{ - Materials::iterator it = m_materials.find(pMaterial); - if (it == m_materials.end()) - { - SHighlightOptions& options = m_materials[pMaterial]; - options.m_modeFlags = modeFlag; - } - else - { - SHighlightOptions& options = it->second; - options.m_modeFlags |= modeFlag; - } -} - -void CMaterialHighlighter::Stop(CMaterial* pMaterial, int modeFlag) -{ - if (pMaterial) - { - pMaterial->SetHighlightFlags(0); - } - - Materials::iterator it = m_materials.find(pMaterial); - if (it == m_materials.end()) - { - return; - } - - SHighlightOptions& options = it->second; - MAKE_SURE((options.m_modeFlags & modeFlag) != 0, return ); - - options.m_modeFlags &= ~modeFlag; - if (options.m_modeFlags == 0) - { - m_materials.erase(it); - } -} - -void CMaterialHighlighter::RestoreMaterials() -{ - for (Materials::iterator it = m_materials.begin(); it != m_materials.end(); ++it) - { - if (it->first) - { - it->first->SetHighlightFlags(0); - } - } -} - -void CMaterialHighlighter::Update() -{ - unsigned int counter = s_highlightUpdateCounter; - - Materials::iterator it; - for (it = m_materials.begin(); it != m_materials.end(); ++it) - { - // Only update each material every 4 frames - if (counter++ % 4 == 0) - { - it->first->SetHighlightFlags(it->second.m_modeFlags); - } - } - - s_highlightUpdateCounter = (s_highlightUpdateCounter + 1) % 4; -} - -void CMaterialHighlighter::GetHighlightColor(ColorF* color, float* intensity, int flags) -{ - MAKE_SURE(color != 0, return ); - MAKE_SURE(intensity != 0, return ); - - *intensity = 0.0f; - - if (flags == 0) - { - return; - } - - int flagIndex = 0; - while (flags) - { - if ((flags & 1) != 0) - { - break; - } - flags = flags >> 1; - ++flagIndex; - } - - MAKE_SURE(flagIndex < sizeof(g_highlightModes) / sizeof(g_highlightModes[0]), return ); - - const SHighlightMode& mode = g_highlightModes[flagIndex]; - float t = GetTickCount() / 1000.0f; - float h = mode.m_colorHue; - float s = 1.0f; - float v = 1.0f; - - color->fromHSV(h + sinf(t * g_PI2 * 5.0f) * 0.025f, s, v); - color->a = 1.0f; - - if (mode.m_continuous) - { - *intensity = fabsf(sinf(t * g_PI2 / mode.m_period)); - } - else - { - *intensity = max(0.0f, sinf(t * g_PI2 / mode.m_period)); - } -} - - -////////////////////////////////////////////////////////////////////////// -// CMaterialManager implementation. -////////////////////////////////////////////////////////////////////////// -CMaterialManager::CMaterialManager(CRegistrationContext& regCtx) - : m_pHighlighter(new CMaterialHighlighter) - , m_highlightMask(eHighlight_All) - , m_currentFolder("") - , m_joinThreads(false) -{ - m_bUniqGuidMap = false; - m_bUniqNameMap = true; - - m_bEditorUiReady = false; - m_bSourceControlErrorReported = false; - m_sourceControlFunctionQueued = false; - m_pLevelLibrary = (CBaseLibrary*)AddLibrary("Level", true); - - m_MatSender = new CMaterialSender(true); - - EBusFindAssetTypeByName materialResult("Material"); //from MaterialAssetTypeInfo.cpp, case insensitive - AZ::AssetTypeInfoBus::BroadcastResult(materialResult, &AZ::AssetTypeInfo::GetAssetType); - m_materialAssetType = materialResult.GetAssetType(); - - EBusFindAssetTypeByName dccMaterialResult("DccMaterial"); //from MaterialAssetTypeInfo.cpp, case insensitive - AZ::AssetTypeInfoBus::BroadcastResult(dccMaterialResult, &AZ::AssetTypeInfo::GetAssetType); - m_dccMaterialAssetType = dccMaterialResult.GetAssetType(); - - RegisterCommands(regCtx); - AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect(); - AzToolsFramework::AssetBrowser::AssetBrowserModelNotificationBus::Handler::BusConnect(); - AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); -} - -////////////////////////////////////////////////////////////////////////// -CMaterialManager::~CMaterialManager() -{ - AzToolsFramework::AssetBrowser::AssetBrowserModelNotificationBus::Handler::BusDisconnect(); - AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); - AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); - - delete m_pHighlighter; - m_pHighlighter = 0; - - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetMaterialManager()->SetListener(NULL); - } - - if (m_MatSender) - { - delete m_MatSender; - m_MatSender = 0; - } - - // Terminate thread that saves dcc materials. - m_joinThreads = true; - if (m_bEditorUiReady) - { - m_dccMaterialSaveSemaphore.release(); - m_dccMaterialSaveThread.join(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Set3DEngine() -{ - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetMaterialManager()->SetListener(this); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::ClearAll() -{ - SetCurrentMaterial(NULL); - CBaseLibraryManager::ClearAll(); - - m_pLevelLibrary = (CBaseLibrary*)AddLibrary("Level", true); -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::CreateMaterial(const QString& sMaterialName,const XmlNodeRef& node, int nMtlFlags, [[maybe_unused]] unsigned long nLoadingFlags) -{ - CMaterial* pMaterial = new CMaterial(sMaterialName, nMtlFlags); - - if (node) - { - CBaseLibraryItem::SerializeContext serCtx(node, true); - serCtx.bUniqName = true; - pMaterial->Serialize(serCtx); - } - if (!pMaterial->IsPureChild() && !(pMaterial->GetFlags() & MTL_FLAG_UIMATERIAL)) - { - RegisterItem(pMaterial); - } - - return pMaterial; -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::CreateMaterial(const char* sMaterialName,const XmlNodeRef& node, int nMtlFlags, unsigned long nLoadingFlags) -{ - return CreateMaterial(QString(sMaterialName), node, nMtlFlags, nLoadingFlags); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Export(XmlNodeRef& node) -{ - XmlNodeRef libs = node->newChild("MaterialsLibrary"); - for (int i = 0; i < GetLibraryCount(); i++) - { - IDataBaseLibrary* pLib = GetLibrary(i); - // Level libraries are saved in in level. - XmlNodeRef libNode = libs->newChild("Library"); - - // Export library. - libNode->setAttr("Name", pLib->GetName().toUtf8().data()); - } -} - -////////////////////////////////////////////////////////////////////////// -int CMaterialManager::ExportLib(CMaterialLibrary* pLib, XmlNodeRef& libNode) -{ - int num = 0; - // Export library. - libNode->setAttr("Name", pLib->GetName().toUtf8().data()); - libNode->setAttr("File", pLib->GetFilename().toUtf8().data()); - char version[50]; - GetIEditor()->GetFileVersion().ToString(version, AZ_ARRAY_SIZE(version)); - libNode->setAttr("SandboxVersion", version); - - // Serialize prototypes. - for (int j = 0; j < pLib->GetItemCount(); j++) - { - CMaterial* pMtl = (CMaterial*)pLib->GetItem(j); - - // Only export real used materials. - if (pMtl->IsDummy() || !pMtl->IsUsed() || pMtl->IsPureChild()) - { - continue; - } - - XmlNodeRef itemNode = libNode->newChild("Material"); - itemNode->setAttr("Name", pMtl->GetName().toUtf8().data()); - num++; - } - return num; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::SetSelectedItem(IDataBaseItem* pItem) -{ - m_pSelectedItem = (CBaseLibraryItem*)pItem; - SetCurrentMaterial((CMaterial*)pItem); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::SetCurrentMaterial(CMaterial* pMtl) -{ - if (m_pCurrentMaterial) - { - // Changing current material. save old one. - if (m_pCurrentMaterial->IsModified()) - { - m_pCurrentMaterial->Save(); - } - } - - m_pCurrentMaterial = pMtl; - if (m_pCurrentMaterial) - { - m_pCurrentMaterial->OnMakeCurrent(); - m_pCurrentEngineMaterial = m_pCurrentMaterial->GetMatInfo(); - } - else - { - m_pCurrentEngineMaterial = 0; - } - - m_pSelectedItem = pMtl; - m_pSelectedParent = pMtl ? pMtl->GetParent() : NULL; - - NotifyItemEvent(m_pCurrentMaterial, EDB_ITEM_EVENT_SELECTED); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::SetCurrentFolder(const QString& folder) -{ - m_currentFolder = folder; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::SetMarkedMaterials(const std::vector<_smart_ptr >& markedMaterials) -{ - m_markedMaterials = markedMaterials; -} - -void CMaterialManager::OnLoadShader(CMaterial* pMaterial) -{ - RemoveFromHighlighting(pMaterial, eHighlight_All); - AddForHighlighting(pMaterial); -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::GetCurrentMaterial() const -{ - return m_pCurrentMaterial; -} - -////////////////////////////////////////////////////////////////////////// -CBaseLibraryItem* CMaterialManager::MakeNewItem() -{ - CMaterial* pMaterial = new CMaterial("", 0); - return pMaterial; -} -////////////////////////////////////////////////////////////////////////// -CBaseLibrary* CMaterialManager::MakeNewLibrary() -{ - return new CMaterialLibrary(this); -} -////////////////////////////////////////////////////////////////////////// -QString CMaterialManager::GetRootNodeName() -{ - return "MaterialsLibs"; -} -////////////////////////////////////////////////////////////////////////// -QString CMaterialManager::GetLibsPath() -{ - if (m_libsPath.isEmpty()) - { - m_libsPath = MATERIALS_LIBS_PATH; - } - return m_libsPath; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::ReportDuplicateItem(CBaseLibraryItem* pItem, CBaseLibraryItem* pOldItem) -{ - QString sLibName; - if (pOldItem->GetLibrary()) - { - sLibName = pOldItem->GetLibrary()->GetName(); - } - CErrorRecord err; - err.pItem = (CMaterial*)pOldItem; - err.error = QObject::tr("Material %1 with the duplicate name to the loaded material %2 ignored").arg(pItem->GetName(), pOldItem->GetName()); - GetIEditor()->GetErrorReport()->ReportError(err); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Serialize([[maybe_unused]] XmlNodeRef& node, bool bLoading) -{ - //CBaseLibraryManager::Serialize( node,bLoading ); - if (bLoading) - { - } - else - { - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - CBaseLibraryManager::OnEditorNotifyEvent(event); - switch (event) - { - case eNotify_OnInit: - InitMatSender(); - break; - case eNotify_OnIdleUpdate: - m_pHighlighter->Update(); - break; - case eNotify_OnBeginGameMode: - m_pHighlighter->RestoreMaterials(); - break; - case eNotify_OnEndGameMode: - ReloadDirtyMaterials(); - break; - case eNotify_OnBeginNewScene: - SetCurrentMaterial(0); - break; - case eNotify_OnBeginSceneOpen: - SetCurrentMaterial(0); - break; - case eNotify_OnMissionChange: - SetCurrentMaterial(0); - break; - case eNotify_OnCloseScene: - SetCurrentMaterial(0); - m_pHighlighter->ClearMaterials(); - break; - case eNotify_OnQuit: - SetCurrentMaterial(0); - if (gEnv->p3DEngine) - { - gEnv->p3DEngine->GetMaterialManager()->SetListener(NULL); - } - break; - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::ReloadDirtyMaterials() -{ - if (!GetIEditor()->Get3DEngine()) - { - return; - } - - IMaterialManager* runtimeMaterialManager = GetIEditor()->Get3DEngine()->GetMaterialManager(); - - uint32 mtlCount = 0; - - runtimeMaterialManager->GetLoadedMaterials(NULL, mtlCount); - - if (mtlCount > 0) - { - AZStd::vector<_smart_ptr> allMaterials; - - allMaterials.reserve(mtlCount); - - [[maybe_unused]] uint32 mtlCountPrev = mtlCount; - runtimeMaterialManager->GetLoadedMaterials(&allMaterials, mtlCount); - AZ_Assert(mtlCountPrev == mtlCount && mtlCount == allMaterials.size(), "It appears GetLoadedMaterials was not used correctly."); - - for (size_t i = 0; i < mtlCount; ++i) - { - _smart_ptr pMtl = allMaterials[i]; - if (pMtl && pMtl->IsDirty()) - { - runtimeMaterialManager->ReloadMaterial(pMtl); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::LoadMaterial(const QString& sMaterialName, bool bMakeIfNotFound) -{ - LOADING_TIME_PROFILE_SECTION(GetISystem()); - - QString sMaterialNameClear = UnifyMaterialName(sMaterialName); - QString fullSourcePath = MaterialToFilename(sMaterialNameClear); - QString relativePath = PathUtil::ReplaceExtension(sMaterialNameClear.toUtf8().data(), MATERIAL_FILE_EXT).c_str(); - - return LoadMaterialInternal(sMaterialNameClear, fullSourcePath, relativePath, bMakeIfNotFound); -} - -////////////////////////////////////////////////////////////////////////// -XmlNodeRef CMaterialManager::LoadXmlNode(const QString &fullSourcePath, const QString &relativeFilePath) -{ - XmlNodeRef materialNode = GetISystem()->LoadXmlFromFile(fullSourcePath.toUtf8().data()); - if (!materialNode) - { - // try again with the product file in case its present - materialNode = GetISystem()->LoadXmlFromFile(relativeFilePath.toUtf8().data()); - } - return materialNode; -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::LoadMaterialWithFullSourcePath(const QString& relativeFilePath, const QString& fullSourcePath, bool makeIfNotFound /*= true*/) -{ - QString materialNameClear = UnifyMaterialName(relativeFilePath); - return LoadMaterialInternal(materialNameClear, fullSourcePath, relativeFilePath, makeIfNotFound); -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::LoadMaterialInternal(const QString &materialNameClear, const QString &fullSourcePath, const QString &relativeFilePath, bool makeIfNotFound) -{ - // Note: We are loading from source files here, not from compiled assets, so there is no need to query the asset system for compilation status, etc. - - // Load material with this name if not yet loaded. - CMaterial* pMaterial = (CMaterial*)FindItemByName(materialNameClear); - if (pMaterial) - { - // If this is a dummy material that was created before for not found mtl file - // try reload the mtl file again to get valid material data. - if (pMaterial->IsDummy()) - { - XmlNodeRef mtlNode = GetISystem()->LoadXmlFromFile(fullSourcePath.toUtf8().data()); - if (mtlNode) - { - DeleteMaterial(pMaterial); - pMaterial = CreateMaterial(materialNameClear, mtlNode); - } - } - return pMaterial; - } - - XmlNodeRef mtlNode = LoadXmlNode(fullSourcePath, relativeFilePath); - - if (mtlNode) - { - pMaterial = CreateMaterial(materialNameClear, mtlNode); - } - else - { - if (makeIfNotFound) - { - pMaterial = new CMaterial(materialNameClear); - pMaterial->SetDummy(true); - RegisterItem(pMaterial); - - CErrorRecord err; - err.error = QObject::tr("Material %1 not found").arg(materialNameClear); - GetIEditor()->GetErrorReport()->ReportError(err); - } - } - - return pMaterial; -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::LoadMaterial(const char* sMaterialName, bool bMakeIfNotFound) -{ - return LoadMaterial(QString(sMaterialName), bMakeIfNotFound); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::AddSourceFileOpeners(const char* fullSourceFileName, [[maybe_unused]] const AZ::Uuid& sourceUUID, AzToolsFramework::AssetBrowser::SourceFileOpenerList& openers) -{ - using namespace AzToolsFramework; - using namespace AzToolsFramework::AssetBrowser; - - // disable if other project is active - if (AzFramework::Render::RenderSystemRequestBus::HasHandlers()) - { - return; - } - - if (AZStd::wildcard_match("*.mtl", fullSourceFileName)) - { - // we can handle these! - auto materialCallback = [this](const char* fullSourceFileNameInCall, const AZ::Uuid& sourceUUIDInCall) - { - const SourceAssetBrowserEntry* fullDetails = SourceAssetBrowserEntry::GetSourceByUuid(sourceUUIDInCall); - if (fullDetails) - { - CMaterial* materialFile = LoadMaterialWithFullSourcePath(QString::fromUtf8(fullDetails->GetRelativePath().c_str()), QString::fromUtf8(fullSourceFileNameInCall), false); - if (materialFile) - { - OpenViewPane("Material Editor"); - SetCurrentMaterial(materialFile); // the material browser pane should be able to deal with this. - } - } - }; - - openers.push_back({ "O3DE_MaterialEditor", "Open In Material Editor...", QIcon(), materialCallback }); - } -} - -////////////////////////////////////////////////////////////////////////// -static bool MaterialRequiresSurfaceType(CMaterial* pMaterial) -{ - // Do not enforce Surface Type... - - // ...over editor UI materials - if ((pMaterial->GetFlags() & MTL_FLAG_UIMATERIAL) != 0) - { - return false; - } - - // ...over SKY - if (pMaterial->GetShaderName() == "DistanceCloud" || - pMaterial->GetShaderName() == "Sky" || - pMaterial->GetShaderName() == "SkyHDR") - { - return false; - } - // ...over terrain materials - if (pMaterial->GetShaderName() == "Terrain.Layer") - { - return false; - } - // ...over vegetation - if (pMaterial->GetShaderName() == "Vegetation") - { - return false; - } - - // ...over decals - bool requiresSurfaceType = true; - CVarBlock* pShaderGenParams = pMaterial->GetShaderGenParamsVars(); - if (pShaderGenParams) - { - if (IVariable* pVar = pShaderGenParams->FindVariable("Decal")) - { - int value = 0; - pVar->Get(value); - if (value) - { - requiresSurfaceType = false; - } - } - // The function GetShaderGenParamsVars allocates a new CVarBlock object, so let's clean it up here - delete pShaderGenParams; - } - return requiresSurfaceType; -} - -////////////////////////////////////////////////////////////////////////// -int CMaterialManager::GetHighlightFlags(CMaterial* pMaterial) const -{ - if (pMaterial == NULL) - { - return 0; - } - - if ((pMaterial->GetFlags() & MTL_FLAG_NODRAW) != 0) - { - return 0; - } - - int result = 0; - - if (pMaterial == m_pHighlightMaterial) - { - result |= eHighlight_Pick; - } - - const QString& surfaceTypeName = pMaterial->GetSurfaceTypeName(); - if (surfaceTypeName.isEmpty() && MaterialRequiresSurfaceType(pMaterial)) - { - result |= eHighlight_NoSurfaceType; - } - - if (GetIEditor()->Get3DEngine()) - { - if (ISurfaceTypeManager* pSurfaceManager = GetIEditor()->Get3DEngine()->GetMaterialManager()->GetSurfaceTypeManager()) - { - const ISurfaceType* pSurfaceType = pSurfaceManager->GetSurfaceTypeByName(surfaceTypeName.toUtf8().data()); - if (pSurfaceType && pSurfaceType->GetBreakability() != 0) - { - result |= eHighlight_Breakable; - } - } - } - - return result; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::AddForHighlighting(CMaterial* pMaterial) -{ - if (pMaterial == NULL) - { - return; - } - - int highlightFlags = (GetHighlightFlags(pMaterial) & m_highlightMask); - if (highlightFlags != 0) - { - m_pHighlighter->Start(pMaterial, highlightFlags); - } - - int count = pMaterial->GetSubMaterialCount(); - for (int i = 0; i < count; ++i) - { - CMaterial* pChild = pMaterial->GetSubMaterial(i); - if (!pChild) - { - continue; - } - - AddForHighlighting(pChild); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::RemoveFromHighlighting(CMaterial* pMaterial, int mask) -{ - if (pMaterial == NULL) - { - return; - } - - m_pHighlighter->Stop(pMaterial, mask); - - int count = pMaterial->GetSubMaterialCount(); - for (int i = 0; i < count; ++i) - { - CMaterial* pChild = pMaterial->GetSubMaterial(i); - if (!pChild) - { - continue; - } - - RemoveFromHighlighting(pChild, mask); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::UpdateHighlightedMaterials() -{ - IDataBaseItemEnumerator* pEnum = CBaseLibraryManager::GetItemEnumerator(); - if (!pEnum) - { - return; - } - - CMaterial* pMaterial = (CMaterial*)pEnum->GetFirst(); - while (pMaterial) - { - RemoveFromHighlighting(pMaterial, eHighlight_All); - AddForHighlighting(pMaterial); - pMaterial = (CMaterial*)pEnum->GetNext(); - } - - pEnum->Release(); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::OnRequestMaterial(_smart_ptr pMatInfo) -{ - const char* pcName = pMatInfo->GetName(); - CMaterial* pMaterial = (CMaterial*) pMatInfo->GetUserData(); - - if (!pMaterial && pcName && *pcName) - { - pMaterial = LoadMaterial(pcName, false); - } - - if (pMaterial) - { - _smart_ptr pNewMatInfo = pMaterial->GetMatInfo(true); - assert(pNewMatInfo == pMatInfo); - //Only register if the material is not registered - if (!pMaterial->IsRegistered()) - { - RegisterItem(pMaterial); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::OnCreateMaterial(_smart_ptr pMatInfo) -{ - CMaterial* existingMaterial = static_cast(FindItemByName(UnifyMaterialName(pMatInfo->GetName()))); - bool materialAlreadyExists = existingMaterial != nullptr; - - // If its not a sub-material or a UI material - if (!(pMatInfo->GetFlags() & MTL_FLAG_PURE_CHILD) && !(pMatInfo->GetFlags() & MTL_FLAG_UIMATERIAL)) - { - // Create a new editor material if it doesn't exist - if (!materialAlreadyExists) - { - CMaterial* pMaterial = new CMaterial(pMatInfo->GetName()); - pMaterial->SetFromMatInfo(pMatInfo); - RegisterItem(pMaterial); - - AddForHighlighting(pMaterial); - } - else - { - // If the material already exists, re-set its values from the engine material that was just re-loaded - existingMaterial->SetFromMatInfo(pMatInfo); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::OnDeleteMaterial(_smart_ptr pMaterial) -{ - CMaterial* pMtl = (CMaterial*)pMaterial->GetUserData(); - if (pMtl) - { - RemoveFromHighlighting(pMtl, eHighlight_All); - DeleteMaterial(pMtl); - } -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterialManager::IsCurrentMaterial(_smart_ptr pMaterial) const -{ - if (!pMaterial) - { - return false; - } - - CMaterial* pMtl = static_cast(pMaterial->GetUserData()); - bool currentMaterial = (pMtl == m_pCurrentMaterial); - - if (pMtl->GetParent()) - { - currentMaterial |= (pMtl->GetParent() == m_pCurrentMaterial); - } - - for (size_t subMatIdx = 0; subMatIdx < pMtl->GetMatInfo()->GetSubMtlCount(); ++subMatIdx) - { - if (static_cast(pMtl->GetMatInfo()->GetSubMtl(subMatIdx)->GetUserData()) == m_pCurrentMaterial) - { - currentMaterial = true; - break; - } - } - - return currentMaterial; -} - - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::FromIMaterial(_smart_ptr engineMaterial) -{ - if (!engineMaterial) - { - return nullptr; - } - CMaterial* editorMaterial = (CMaterial*)engineMaterial->GetUserData(); - if (!editorMaterial) - { - // If the user data isn't set, check for an existing material with the same name - editorMaterial = static_cast(FindItemByName(UnifyMaterialName(engineMaterial->GetName()))); - } - return editorMaterial; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::SaveAllLibs() -{ -} - -////////////////////////////////////////////////////////////////////////// -QString CMaterialManager::FilenameToMaterial(const QString& filename) -{ - // Convert a full or relative path to a normalized name that can be used in a hash (so lowercase, relative path, correct slashes, remove extension) - // note that it may already be an asset path, if so, don't add the overhead of calling into the AP and convert it. - // if it starts with an alias (@) or if its an absolute file path, we need to convert it. Otherwise we really don't... - QString name = filename; - if (name.startsWith(QChar('@')) || AZ::IO::PathView(name.toUtf8().data()).IsAbsolute()) - { - name = Path::FullPathToGamePath(filename); // convert any full path to a relative path instead. - } - QByteArray n = name.toUtf8(); - MaterialUtils::UnifyMaterialName(n.data()); // Utility function used by all other parts of the code to unify slashes, lowercase, and remove extension - - return QString::fromUtf8(n); -} - -////////////////////////////////////////////////////////////////////////// -QString CMaterialManager::MaterialToFilename(const QString& sMaterialName) -{ - QString materialWithExtension = Path::ReplaceExtension(sMaterialName, MATERIAL_FILE_EXT); - QString fileName = Path::GamePathToFullPath(materialWithExtension); - const int mtlExtensionLength = strlen(MATERIAL_FILE_EXT); - if (fileName.right(mtlExtensionLength).toLower() != MATERIAL_FILE_EXT) - { - // we got something back which is not a mtl, fall back heuristic: - AZStd::string pathName(fileName.toUtf8().data()); - AZStd::string fileNameOfMaterial; - AzFramework::StringFunc::Path::StripFullName(pathName); // remove the filename of the path to the FBX file so now it just contains the folder of the fbx file. - AzFramework::StringFunc::Path::GetFullFileName(materialWithExtension.toUtf8().data(), fileNameOfMaterial); // remove the path part of the material so it only contains the file name - AZStd::string finalName; - AzFramework::StringFunc::Path::Join(pathName.c_str(), fileNameOfMaterial.c_str(), finalName); - fileName = finalName.c_str(); - } - return fileName; -} - -////////////////////////////////////////////////////////////////////////// -const AZ::Data::AssetType& CMaterialManager::GetMaterialAssetType() -{ - return m_materialAssetType; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::DeleteMaterial(CMaterial* pMtl) -{ - assert(pMtl); - _smart_ptr _ref(pMtl); - if (pMtl == GetCurrentMaterial()) - { - SetCurrentMaterial(NULL); - } - - DeleteItem(pMtl); - - // Delete it from all sub materials. - for (int i = 0; i < m_pLevelLibrary->GetItemCount(); i++) - { - CMaterial* pMultiMtl = (CMaterial*)m_pLevelLibrary->GetItem(i); - if (pMultiMtl->IsMultiSubMaterial()) - { - for (int slot = 0; slot < pMultiMtl->GetSubMaterialCount(); slot++) - { - if (pMultiMtl->GetSubMaterial(slot) == pMultiMtl) - { - // Clear this sub material slot. - pMultiMtl->SetSubMaterial(slot, 0); - } - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::RemoveMaterialFromDisk(const char * fileName) -{ - using namespace AzToolsFramework; - if (fileName) - { - SourceControlCommandBus::Broadcast(&SourceControlCommandBus::Events::RequestDelete, fileName, - [](bool success, const SourceControlFileInfo& info) - { - //If the file is not managed by source control, delete it locally - if (!success && !info.IsManaged()) - { - QFile::remove(info.m_filePath.c_str()); - } - } - ); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::RegisterCommands(CRegistrationContext& regCtx) -{ - CommandManagerHelper::RegisterCommand(regCtx.pCommandManager, "material", "duplicate", "", "", AZStd::bind(&CMaterialManager::Command_Duplicate, this)); - CommandManagerHelper::RegisterCommand(regCtx.pCommandManager, "material", "merge", "", "", AZStd::bind(&CMaterialManager::Command_Merge, this)); - CommandManagerHelper::RegisterCommand(regCtx.pCommandManager, "material", "delete", "", "", AZStd::bind(&CMaterialManager::Command_Delete, this)); - CommandManagerHelper::RegisterCommand(regCtx.pCommandManager, "material", "assign_to_selection", "", "", AZStd::bind(&CMaterialManager::Command_AssignToSelection, this)); - CommandManagerHelper::RegisterCommand(regCtx.pCommandManager, "material", "select_assigned_objects", "", "", AZStd::bind(&CMaterialManager::Command_SelectAssignedObjects, this)); - CommandManagerHelper::RegisterCommand(regCtx.pCommandManager, "material", "select_from_object", "", "", AZStd::bind(&CMaterialManager::Command_SelectFromObject, this)); -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterialManager::SelectSaveMaterial(QString& itemName, QString& fullSourcePath, const char* defaultStartPath) -{ - QString startPath; - if (defaultStartPath && defaultStartPath[0] != '\0') - { - startPath = defaultStartPath; - } - else - { - startPath = GetIEditor()->GetSearchPath(EDITOR_PATH_MATERIALS); - } - - if (!CFileUtil::SelectSaveFile("Material Files (*.mtl)", "mtl", startPath, fullSourcePath)) - { - return false; - } - - itemName = FilenameToMaterial(fullSourcePath); - if (itemName.isEmpty()) - { - return false; - } - - return true; -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::SelectNewMaterial(int nMtlFlags, [[maybe_unused]] const char* sStartPath) -{ - QString path = m_pCurrentMaterial ? Path::GetPath(m_pCurrentMaterial->GetFilename()) : m_currentFolder; - QString itemName; - QString fullPath; - if (!SelectSaveMaterial(itemName, fullPath, path.toUtf8().data())) - { - return 0; - } - - if (FindItemByName(itemName)) - { - Warning("Material with name %s already exist", itemName.toUtf8().data()); - return 0; - } - - _smart_ptr mtl = CreateMaterial(itemName, XmlNodeRef(), nMtlFlags); - mtl->Update(); - bool skipReadOnly = true; - mtl->Save(skipReadOnly, fullPath); - SetCurrentMaterial(mtl); - return mtl; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_Create() -{ - SelectNewMaterial(0); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_CreateMulti() -{ - SelectNewMaterial(MTL_FLAG_MULTI_SUBMTL); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_ConvertToMulti() -{ - CMaterial* pMaterial = GetCurrentMaterial(); - - if (pMaterial && pMaterial->GetSubMaterialCount() == 0) - { - CMaterial* pSubMat = new CMaterial(*pMaterial); - pSubMat->SetName(pSubMat->GetShortName()); - pSubMat->SetFlags(pSubMat->GetFlags() | MTL_FLAG_PURE_CHILD); - - pMaterial->SetFlags(MTL_FLAG_MULTI_SUBMTL); - pMaterial->SetSubMaterialCount(1); - pMaterial->SetSubMaterial(0, pSubMat); - - pMaterial->Save(); - pMaterial->Reload(); - SetSelectedItem(pSubMat); - } - else - { - Warning(pMaterial ? "azlmbr.legacy.material.convert_to_multi called on invalid material setup" : "azlmbr.legacy.material.convert_to_multi called while no material selected"); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_Duplicate() -{ - CMaterial* pSrcMtl = GetCurrentMaterial(); - - if (!pSrcMtl) - { - CErrorRecord err; - err.error = "azlmbr.legacy.material.duplicate called while no materials selected"; - GetIEditor()->GetErrorReport()->ReportError(err); - return; - } - - if (GetIEditor()->IsSourceControlAvailable()) - { - uint32 attrib = pSrcMtl->GetFileAttributes(); - - if ((attrib & SCC_FILE_ATTRIBUTE_INPAK) && (attrib & SCC_FILE_ATTRIBUTE_MANAGED) && !(attrib & SCC_FILE_ATTRIBUTE_NORMAL)) - { - // Get latest for making folders with right case - CFileUtil::GetLatestFromSourceControl(pSrcMtl->GetFilename().toUtf8().data()); - } - } - - if (pSrcMtl != 0 && !pSrcMtl->IsPureChild()) - { - QString newUniqueRelativePath = MakeUniqueItemName(pSrcMtl->GetName()); - - // Create a new material. - _smart_ptr pMtl = DuplicateMaterial(newUniqueRelativePath.toUtf8().data(), pSrcMtl); - if (pMtl) - { - // Get the new filename from the relative path - AZStd::string newFileName; - AzFramework::StringFunc::Path::GetFileName(newUniqueRelativePath.toUtf8().data(), newFileName); - - // Get the full path to the original material, so we know which folder to put the new material in - AZStd::string newFullFilePath = pSrcMtl->GetFilename().toUtf8().data(); - - // Replace the original material filename with the filename from the new relative path + the material file extension to get the new full file path - AzFramework::StringFunc::Path::ReplaceFullName(newFullFilePath, newFileName.c_str(), MATERIAL_FILE_EXT); - - AzFramework::StringFunc::Path::Normalize(newFullFilePath); - - const bool skipReadOnly = true; - pMtl->Save(skipReadOnly, newFullFilePath.c_str()); - SetSelectedItem(pMtl); - } - } -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CMaterialManager::DuplicateMaterial(const char* newName, CMaterial* pOriginal) -{ - if (!newName) - { - assert(0 && "NULL newName passed into CMaterialManager::DuplicateMaterial"); - return 0; - } - if (!pOriginal) - { - assert(0 && "NULL pOriginal passed into CMaterialManager::DuplicateMaterial"); - return 0; - } - - - XmlNodeRef node = GetISystem()->CreateXmlNode("Material"); - CBaseLibraryItem::SerializeContext ctx(node, false); - ctx.bCopyPaste = true; - pOriginal->Serialize(ctx); - - return CreateMaterial(newName, node, pOriginal->GetFlags()); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::GenerateUniqueSubmaterialName(const CMaterial* pSourceMaterial, const CMaterial* pTargetMaterial, QString& uniqueSubmaterialName) const -{ - QString sourceMaterialName = pSourceMaterial->GetName(); - - // We don't need the whole path to the material, just the base name - QFileInfo filename(sourceMaterialName); - sourceMaterialName = filename.baseName(); - - uniqueSubmaterialName = sourceMaterialName; - size_t nameIndex = 0; - - bool nameUpdated = true; - while (nameUpdated) - { - nameUpdated = false; - for (size_t k = 0; k < pTargetMaterial->GetSubMaterialCount(); ++k) - { - CMaterial* pSubMaterial = pTargetMaterial->GetSubMaterial(k); - if (pSubMaterial && pSubMaterial->GetName() == uniqueSubmaterialName) - { - ++nameIndex; - uniqueSubmaterialName = QStringLiteral("%1%2").arg(sourceMaterialName).arg(nameIndex, 2, 10, QLatin1Char('0')); - nameUpdated = true; - break; - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -bool CMaterialManager::DuplicateAsSubMaterialAtIndex(CMaterial* pSourceMaterial, CMaterial* pTargetMaterial, int subMaterialIndex) -{ - if (pSourceMaterial && pTargetMaterial && pTargetMaterial->GetSubMaterialCount() > subMaterialIndex) - { - // Resolve name collisions between the source material and the submaterials in the target material - QString newSubMaterialName; - GenerateUniqueSubmaterialName(pSourceMaterial, pTargetMaterial, newSubMaterialName); - - // Mark the material to be duplicated as a PURE_CHILD since it is being duplicated as a submaterial - int sourceMaterialFlags = pSourceMaterial->GetFlags(); - pSourceMaterial->SetFlags(sourceMaterialFlags | MTL_FLAG_PURE_CHILD); - - CMaterial* pNewSubMaterial = DuplicateMaterial(newSubMaterialName.toUtf8().data(), pSourceMaterial); - pTargetMaterial->SetSubMaterial(subMaterialIndex, pNewSubMaterial); - - // Reset the flags of the source material to their original values - pSourceMaterial->SetFlags(sourceMaterialFlags); - return true; - } - - return false; -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_Merge() -{ - QString itemName; - QString fullPath; - QString defaultMaterialPath; - if (m_pCurrentMaterial) - { - defaultMaterialPath = Path::GetPath(m_pCurrentMaterial->GetFilename()); - } - if (!SelectSaveMaterial(itemName, fullPath, defaultMaterialPath.toUtf8().data())) - { - return; - } - - _smart_ptr pNewMaterial = CreateMaterial(itemName, XmlNodeRef(), MTL_FLAG_MULTI_SUBMTL); - - size_t totalSubMaterialCount = 0; - for (_smart_ptr pMaterial : m_markedMaterials) - { - if (pMaterial->IsMultiSubMaterial()) - { - totalSubMaterialCount += pMaterial->GetSubMaterialCount(); - } - else - { - totalSubMaterialCount++; - } - } - pNewMaterial->SetSubMaterialCount(totalSubMaterialCount); - - size_t subMaterialIndex = 0; - for (_smart_ptr pMaterial : m_markedMaterials) - { - if (pMaterial->IsMultiSubMaterial()) - { - // Loop through each submaterial and duplicate it as a submaterial in the new material - for (size_t j = 0; j < pMaterial->GetSubMaterialCount(); ++j) - { - CMaterial* pSubMaterial = pMaterial->GetSubMaterial(j); - if (DuplicateAsSubMaterialAtIndex(pSubMaterial, pNewMaterial, subMaterialIndex)) - { - ++subMaterialIndex; - } - } - } - else - { - // Duplicate the material as a submaterial in the new material - if (DuplicateAsSubMaterialAtIndex(pMaterial, pNewMaterial, subMaterialIndex)) - { - ++subMaterialIndex; - } - } - } - - pNewMaterial->Update(); - const bool skipReadOnly = true; - pNewMaterial->Save(skipReadOnly, fullPath); - SetCurrentMaterial(pNewMaterial); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_Delete() -{ - CMaterial* pMtl = GetCurrentMaterial(); - if (pMtl) - { - CUndo undo("Delete Material"); - QString str = QObject::tr("Delete Material %1?\r\nNote: Material file %2 will also be deleted.") - .arg(pMtl->GetName(), pMtl->GetFilename()); - if (QMessageBox::question(QApplication::activeWindow(), QObject::tr("Delete Confirmation"), str) == QMessageBox::Yes) - { - AZStd::string matName = pMtl->GetFilename().toUtf8().data(); - DeleteMaterial(pMtl); - RemoveMaterialFromDisk(matName.c_str()); - SetCurrentMaterial(0); - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_AssignToSelection() -{ - CMaterial* pMtl = GetCurrentMaterial(); - if (pMtl) - { - CUndo undo("Assign Material"); - CSelectionGroup* pSel = GetIEditor()->GetSelection(); - if (pMtl->IsPureChild()) - { - const QString title = QObject::tr("Assign Submaterial"); - const QString message = QObject::tr("You can assign submaterials to objects only for preview purpose. This assignment will not be saved with the level and will not be exported to the game."); - if (QMessageBox::information(QApplication::activeWindow(), title, message, QMessageBox::Ok | QMessageBox::Cancel) == QMessageBox::Cancel) - { - return; - } - } - if (!pSel->IsEmpty()) - { - for (int i = 0; i < pSel->GetCount(); i++) - { - pSel->GetObject(i)->SetMaterial(pMtl); - } - } - } - CViewport* pViewport = GetIEditor()->GetActiveView(); - if (pViewport) - { - pViewport->Drop(QPoint(-1, -1), pMtl); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_ResetSelection() -{ - CSelectionGroup* pSel = GetIEditor()->GetSelection(); - if (!pSel->IsEmpty()) - { - CUndo undo("Reset Material"); - for (int i = 0; i < pSel->GetCount(); i++) - { - pSel->GetObject(i)->SetMaterial(0); - } - } - CViewport* pViewport = GetIEditor()->GetActiveView(); - if (pViewport) - { - pViewport->Drop(QPoint(-1, -1), 0); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_SelectAssignedObjects() -{ - CMaterial* pMtl = GetCurrentMaterial(); - if (pMtl) - { - CUndo undo("Select Object(s)"); - CBaseObjectsArray objects; - GetIEditor()->GetObjectManager()->GetObjects(objects); - for (int i = 0; i < objects.size(); i++) - { - CBaseObject* pObject = objects[i]; - if (pObject->GetMaterial() == pMtl || pObject->GetRenderMaterial() == pMtl) - { - if (pObject->IsHidden() || pObject->IsFrozen()) - { - continue; - } - GetIEditor()->GetObjectManager()->SelectObject(pObject); - } - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::Command_SelectFromObject() -{ - if (GetIEditor()->IsInPreviewMode()) - { - CViewport* pViewport = GetIEditor()->GetActiveView(); - if (CModelViewport* p = viewport_cast(pViewport)) - { - CMaterial* pMtl = p->GetMaterial(); - SetCurrentMaterial(pMtl); - } - return; - } - - CSelectionGroup* pSel = GetIEditor()->GetSelection(); - if (pSel->IsEmpty()) - { - return; - } - - for (int i = 0; i < pSel->GetCount(); i++) - { - CMaterial* pMtl = pSel->GetObject(i)->GetRenderMaterial(); - if (pMtl) - { - SetCurrentMaterial(pMtl); - return; - } - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::PickPreviewMaterial() -{ - XmlNodeRef data = XmlHelpers::CreateXmlNode("ExportMaterial"); - CMaterial* pMtl = GetCurrentMaterial(); - if (!pMtl) - { - return; - } - - if (pMtl->IsPureChild() && pMtl->GetParent()) - { - pMtl = pMtl->GetParent(); - } - - if (pMtl->GetFlags() & MTL_FLAG_WIRE) - { - data->setAttr("Flag_Wire", 1); - } - if (pMtl->GetFlags() & MTL_FLAG_2SIDED) - { - data->setAttr("Flag_2Sided", 1); - } - - data->setAttr("Name", pMtl->GetName().toUtf8().data()); - data->setAttr("FileName", pMtl->GetFilename().toUtf8().data()); - - XmlNodeRef node = data->newChild("Material"); - - CBaseLibraryItem::SerializeContext serCtx(node, false); - pMtl->Serialize(serCtx); - - - if (!pMtl->IsMultiSubMaterial()) - { - XmlNodeRef texturesNode = node->findChild("Textures"); - if (texturesNode) - { - for (int i = 0; i < texturesNode->getChildCount(); i++) - { - XmlNodeRef texNode = texturesNode->getChild(i); - QString file; - if (texNode->getAttr("File", file)) - { - texNode->setAttr("File", Path::GamePathToFullPath(file).toUtf8().data()); - } - } - } - } - else - { - XmlNodeRef childsNode = node->findChild("SubMaterials"); - if (childsNode) - { - int nSubMtls = childsNode->getChildCount(); - for (int i = 0; i < nSubMtls; i++) - { - XmlNodeRef node2 = childsNode->getChild(i); - XmlNodeRef texturesNode = node2->findChild("Textures"); - if (texturesNode) - { - for (int ii = 0; ii < texturesNode->getChildCount(); ii++) - { - XmlNodeRef texNode = texturesNode->getChild(ii); - QString file; - if (texNode->getAttr("File", file)) - { - texNode->setAttr("File", Path::GamePathToFullPath(file).toUtf8().data()); - } - } - } - } - } - } - - - m_MatSender->SendMessage(eMSM_GetSelectedMaterial, data); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::SyncMaterialEditor() -{ -#if defined(AZ_PLATFORM_WINDOWS) - if (!m_MatSender) - { - return; - } - - if (!m_MatSender->GetMessage()) - { - return; - } - - if (m_MatSender->m_h.msg == eMSM_Create) - { - XmlNodeRef node = m_MatSender->m_node->findChild("Material"); - if (!node) - { - return; - } - - QString sMtlName; - QString sMaxFile; - - XmlNodeRef root = m_MatSender->m_node; - root->getAttr("Name", sMtlName); - root->getAttr("MaxFile", sMaxFile); - - int IsMulti = 0; - root->getAttr("IsMulti", IsMulti); - - int nMtlFlags = 0; - if (IsMulti) - { - nMtlFlags |= MTL_FLAG_MULTI_SUBMTL; - } - - if (root->haveAttr("Flag_Wire")) - { - nMtlFlags |= MTL_FLAG_WIRE; - } - if (root->haveAttr("Flag_2Sided")) - { - nMtlFlags |= MTL_FLAG_2SIDED; - } - - _smart_ptr pMtl = SelectNewMaterial(nMtlFlags, Path::GetPath(sMaxFile).toUtf8().data()); - - if (!pMtl) - { - return; - } - - if (!IsMulti) - { - node->delAttr("Shader"); // Remove shader attribute. - XmlNodeRef texturesNode = node->findChild("Textures"); - if (texturesNode) - { - for (int i = 0; i < texturesNode->getChildCount(); i++) - { - XmlNodeRef texNode = texturesNode->getChild(i); - QString file; - if (texNode->getAttr("File", file)) - { - //make path relative to the project specific game folder - QString newfile = Path::MakeGamePath(file); - if (!newfile.isEmpty()) - { - file = newfile; - } - texNode->setAttr("File", file.toUtf8().data()); - } - } - } - } - else - { - XmlNodeRef childsNode = node->findChild("SubMaterials"); - if (childsNode) - { - int nSubMtls = childsNode->getChildCount(); - for (int i = 0; i < nSubMtls; i++) - { - XmlNodeRef node2 = childsNode->getChild(i); - node2->delAttr("Shader"); // Remove shader attribute. - XmlNodeRef texturesNode = node2->findChild("Textures"); - if (texturesNode) - { - for (int ii = 0; ii < texturesNode->getChildCount(); ii++) - { - XmlNodeRef texNode = texturesNode->getChild(ii); - QString file; - if (texNode->getAttr("File", file)) - { - //make path relative to the project specific game folder - QString newfile = Path::MakeGamePath(file); - if (!newfile.isEmpty()) - { - file = newfile; - } - texNode->setAttr("File", file.toUtf8().data()); - } - } - } - } - } - } - - CBaseLibraryItem::SerializeContext ctx(node, true); - ctx.bUndo = true; - pMtl->Serialize(ctx); - - pMtl->Update(); - - SetCurrentMaterial(0); - SetCurrentMaterial(pMtl); - } - - if (m_MatSender->m_h.msg == eMSM_GetSelectedMaterial) - { - PickPreviewMaterial(); - } -#endif -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::InitMatSender() -{ - //MatSend(true); - m_MatSender->Create(); - QWidget* mainWindow = MainWindow::instance(); - m_MatSender->SetupWindows(mainWindow, mainWindow); - XmlNodeRef node = XmlHelpers::CreateXmlNode("Temp"); - m_MatSender->SendMessage(eMSM_Init, node); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::GotoMaterial([[maybe_unused]] CMaterial* pMaterial) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::GotoMaterial([[maybe_unused]] _smart_ptr pMtl) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::SetHighlightedMaterial(CMaterial* pMtl) -{ - if (m_pHighlightMaterial) - { - RemoveFromHighlighting(m_pHighlightMaterial, eHighlight_Pick); - } - - m_pHighlightMaterial = pMtl; - if (m_pHighlightMaterial) - { - AddForHighlighting(m_pHighlightMaterial); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::HighlightedMaterialChanged(CMaterial* pMtl) -{ - if (!pMtl) - { - return; - } - - RemoveFromHighlighting(pMtl, eHighlight_All); - AddForHighlighting(pMtl); -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::SetHighlightMask(int highlightMask) -{ - if (m_highlightMask != highlightMask) - { - m_highlightMask = highlightMask; - - UpdateHighlightedMaterials(); - } -} - -////////////////////////////////////////////////////////////////////////// -void CMaterialManager::GatherResources(_smart_ptr pMaterial, CUsedResources& resources) -{ - if (!pMaterial) - { - return; - } - - int nSubMtlCount = pMaterial->GetSubMtlCount(); - if (nSubMtlCount > 0) - { - for (int i = 0; i < nSubMtlCount; i++) - { - GatherResources(pMaterial->GetSubMtl(i), resources); - } - } - else - { - SShaderItem& shItem = pMaterial->GetShaderItem(); - if (shItem.m_pShaderResources) - { - SInputShaderResources res; - shItem.m_pShaderResources->ConvertToInputResource(&res); - - for (auto& iter : res.m_TexturesResourcesMap ) - { - SEfResTexture* pTexture = &(iter.second); - if (!pTexture->m_Name.empty()) - { - resources.Add(pTexture->m_Name.c_str()); - } - } - gEnv->pRenderer->EF_ReleaseInputShaderResource(&res); - } - } -} - -/////////////////////////////////////////////////////////////////////////// -void CMaterialManager::GetHighlightColor(ColorF* color, float* intensity, int flags) -{ - MAKE_SURE(m_pHighlighter, return ); - m_pHighlighter->GetHighlightColor(color, intensity, flags); -} - -/////////////////////////////////////////////////////////////////////////// -// This will be called when the editor welcome screen is displayed. -// At this point the editor is ready for UI events, which means we can -// process .dccmtl paths and display error to the user if necessary -bool CMaterialManager::SkipEditorStartupUI() -{ - // Editor started - m_bEditorUiReady = true; - - // If we have any file paths buffered - if (m_sourceControlBuffer.size() > 0) - { - // Start queuing - QueueSourceControlTick(); - } - - // Launch thread responsible for saving cached - // .dccmtl files as source .mtl files - StartDccMaterialSaveThread(); - - // Never want to skip Startup UI - return false; -} - -/////////////////////////////////////////////////////////////////////////// -// Queues the function TickSourceControl() to be exectued next frame -void CMaterialManager::QueueSourceControlTick() -{ - // If TickSourceControl is not currently queued - if (!m_sourceControlFunctionQueued) - { - // Queue it - AZStd::function tickFunction = [this]() - { - TickSourceControl(); - }; - AZ::SystemTickBus::QueueFunction(tickFunction); - - // Stop further queues as TickSourceControl will queue itself - // until there are no more paths in the buffer to process - m_sourceControlFunctionQueued = true; - } -} - -/////////////////////////////////////////////////////////////////////////// -// Takes a single path from m_sourceControlBuffer and passes it to -// DccMaterialSourceControlCheck(). Then if there are more paths -// remaining in the buffer, it will queue itself for execution next -// frame. The reason for doing only one material every tick is to avoid -// flooding source control with too many requests and stalling the editor -void CMaterialManager::TickSourceControl() -{ - m_sourceControlFunctionQueued = false; - AZStd::string filePath; - bool moreRemaining = false; - - { - AZStd::lock_guard lock(m_sourceControlBufferMutex); - - if (m_sourceControlBuffer.size() < 1) - { - return; - } - - filePath = m_sourceControlBuffer.back(); - m_sourceControlBuffer.pop_back(); - moreRemaining = !m_sourceControlBuffer.empty(); - } - - // Process it - DccMaterialSourceControlCheck(filePath); - - // If there are more paths to check - if (moreRemaining) - { - // Queue again - QueueSourceControlTick(); - } -} - -/////////////////////////////////////////////////////////////////////////// -// Launches new thread running the DccMaterialSaveThreadFunc() function -void CMaterialManager::StartDccMaterialSaveThread() -{ - AZStd::thread_desc threadDesc; - threadDesc.m_name = "Dcc Material Save Thread"; - - m_dccMaterialSaveThread = AZStd::thread( - [this]() - { - DccMaterialSaveThreadFunc(); - }, - &threadDesc); -} - -/////////////////////////////////////////////////////////////////////////// -// Will save all the .dccmtl file paths in the buffer to source .mtl -// Runs on a separate thread so as not to stall the main thread -void CMaterialManager::DccMaterialSaveThreadFunc() -{ - while (true) - { - m_dccMaterialSaveSemaphore.acquire(); - - // Exit condition, set to true in destructor - if (m_joinThreads) - { - return; - } - - AZStd::vector dccMaterialPaths; - - // Lock the buffer and copy file paths locally - { - AZStd::lock_guard lock(m_dccMaterialSaveMutex); - dccMaterialPaths.reserve(m_dccMaterialSaveBuffer.size()); - for (AZStd::string& fileName : m_dccMaterialSaveBuffer) - { - dccMaterialPaths.push_back(fileName); - } - m_dccMaterialSaveBuffer.clear(); - } - - // Save all the buffered .dccmtl files - for (AZStd::string& fileName : dccMaterialPaths) - { - SaveDccMaterial(fileName); - } - - // Clear local strings - dccMaterialPaths.clear(); - } -} - -/////////////////////////////////////////////////////////////////////////// -// Async source control request. If successful, the callback will add the -// file name to the buffer for processing by the Dcc Material Save Thread -void CMaterialManager::DccMaterialSourceControlCheck(const AZStd::string& relativeDccMaterialPath) -{ - AZStd::string fullSourcePath = DccMaterialToSourcePath(relativeDccMaterialPath); - - if (!DccMaterialRequiresSave(relativeDccMaterialPath, fullSourcePath)) - { - // Source .mtl update not required, early out - return; - } - - // Create callback for source control operation (see SCCommandBus::Broadcast below) - AzToolsFramework::SourceControlResponseCallback callback = - [this, relativeDccMaterialPath, fullSourcePath](bool success, const AzToolsFramework::SourceControlFileInfo& info) - { - if (success || !info.IsReadOnly()) - { - // File needs saving, add it to the buffer for processing by the dcc material thread - - // Lock access to the buffer - AZStd::lock_guard lock(m_dccMaterialSaveMutex); - - // Add file path - m_dccMaterialSaveBuffer.push_back(relativeDccMaterialPath); - - // Notify thread there's work to do - m_dccMaterialSaveSemaphore.release(); - } - else - { - QString errorMessage = QObject::tr("Could not check out read-only file %1 in source control. Either check your source control configuration or disable source control.").arg(QString::fromUtf8(fullSourcePath.c_str())); - - // Alter error message slightly if source control is disabled - bool isSourceControlActive = false; - AzToolsFramework::SourceControlConnectionRequestBus::BroadcastResult(isSourceControlActive, &AzToolsFramework::SourceControlConnectionRequestBus::Events::IsActive); - - if (!isSourceControlActive) - { - errorMessage = QObject::tr("Could not check out read-only file %1 because source control is disabled. Either enable source control or check out the file manually to make it writable.").arg(QString::fromUtf8(fullSourcePath.c_str())); - } - - // Pop open an error message box if this is the first error we encounter - if (!m_bSourceControlErrorReported) - { - // Report warning in message box - QString errorTitle = QStringLiteral("Dcc Material Error"); - QMessageBox::warning(QApplication::activeWindow(), errorTitle, errorMessage, QMessageBox::Cancel); - - // Only report source control error box to the user once, - // no need to spam them for every material - m_bSourceControlErrorReported = true; - } - - AZ_Error("Rendering", false, errorMessage.toUtf8().data()); - } - }; - - // Request edit from source control (happens asynchronously) - using SCCommandBus = AzToolsFramework::SourceControlCommandBus; - SCCommandBus::Broadcast(&SCCommandBus::Events::RequestEdit, fullSourcePath.c_str(), true, callback); -} - -/////////////////////////////////////////////////////////////////////////// -// Handles when .dccmtl is created -void CMaterialManager::EntryAdded(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* assetEntry) -{ - if (assetEntry->GetEntryType() != AzToolsFramework::AssetBrowser::AssetBrowserEntry::AssetEntryType::Product) - { - // Ignore non-product entries - return; - } - const AzToolsFramework::AssetBrowser::ProductAssetBrowserEntry* productAssetEntry = azrtti_cast(assetEntry); - if (productAssetEntry && productAssetEntry->GetAssetType() != m_dccMaterialAssetType) - { - // Ignore types that aren't .dccmtl - return; - } - - AddDccMaterialPath(productAssetEntry->GetRelativePath()); -} - -/////////////////////////////////////////////////////////////////////////// -// Handles when .dccmtl is edited -void CMaterialManager::OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) -{ - AZ::Data::AssetInfo assetInfo; - EBUS_EVENT_RESULT(assetInfo, AZ::Data::AssetCatalogRequestBus, GetAssetInfoById, assetId); - - if (assetInfo.m_assetType != m_dccMaterialAssetType) - { - // Ignore types that aren't .dccmtl - return; - } - - AddDccMaterialPath(assetInfo.m_relativePath); -} - -/////////////////////////////////////////////////////////////////////////// -void CMaterialManager::AddDccMaterialPath(const AZStd::string relativeDccMaterialPath) -{ - if (relativeDccMaterialPath.empty()) - { - return; - } - - // Lock access to the buffer - AZStd::lock_guard lock(m_sourceControlBufferMutex); - - // Add file path - m_sourceControlBuffer.push_back(relativeDccMaterialPath); - - if (m_bEditorUiReady) - { - QueueSourceControlTick(); - } -} - -/////////////////////////////////////////////////////////////////////////// -// Given the path of a .dccmtl in cache, save it as a source .mtl -void CMaterialManager::SaveDccMaterial(const AZStd::string& relativeDccMaterialPath) -{ - // __________________________________________________ - // Load .dccmtl - - XmlNodeRef dccNode = GetISystem()->LoadXmlFromFile(relativeDccMaterialPath.c_str()); - - if (!dccNode) - { - AZ_Error("MaterialManager", false, "CMaterialManager::SaveDccMaterial: Failed to load XML node from .dccmtl file: %s", relativeDccMaterialPath.c_str()); - return; - } - - // __________________________________________________ - // Save as source .mtl file - - AZStd::string fullSourcePath = DccMaterialToSourcePath(relativeDccMaterialPath); - bool saveSuccessful = dccNode->saveToFile(fullSourcePath.c_str()); - - if (!saveSuccessful) - { - AZ_Error("MaterialManager", false, "CMaterialManager::SaveDccMaterial: Failed to save source .mtl from .dccmtl file: %s", relativeDccMaterialPath.c_str()); - } -} - -/////////////////////////////////////////////////////////////////////////// -// Compares the hash values from .dccmtl and source .mtl to determine if -// .dccmtl has changed and needs to be saved. -bool CMaterialManager::DccMaterialRequiresSave(const AZStd::string& relativeDccMaterialPath, const AZStd::string& fullSourcePath) -{ - // __________________________________________________ - // Get Source Hash - - AZ::u32 sourceHash = 0; - - // Check if material is already loaded - QString unifiedName = UnifyMaterialName(QString(relativeDccMaterialPath.c_str())); - CMaterial* sourceMaterial = (CMaterial*)FindItemByName(unifiedName); - - if (sourceMaterial && !sourceMaterial->IsDummy()) - { - sourceHash = sourceMaterial->GetDccMaterialHash(); - } - else - { - XmlNodeRef sourceNode = GetISystem()->LoadXmlFromFile(fullSourcePath.c_str()); - if (sourceNode) - { - sourceNode->getAttr("DccMaterialHash", sourceHash); - } - else - { - // Couldn't find source node or material, so we need to save the dcc material as a source material - // No need to check the dcc material hash, just return true - return true; - } - } - - // __________________________________________________ - // Get DCC material Hash - - AZ::u32 dccHash = 0; - XmlNodeRef dccNode = GetISystem()->LoadXmlFromFile(relativeDccMaterialPath.c_str()); - - if (!dccNode) - { - AZ_Error("MaterialManager", false, "CMaterialManager::DccMaterialRequiresSave: Failed to load XML node from .dccmtl file: %s", relativeDccMaterialPath.c_str()); - return false; - } - - dccNode->getAttr("DccMaterialHash", dccHash); - - // __________________________________________________ - // Compare hash values - - // Only update if .dccmtl hash is different from the source hash - return (dccHash != sourceHash); -} - diff --git a/Code/Sandbox/Editor/Material/MaterialManager.h b/Code/Sandbox/Editor/Material/MaterialManager.h deleted file mode 100644 index a9dcabfa40..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialManager.h +++ /dev/null @@ -1,300 +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_MATERIAL_MATERIALMANAGER_H -#define CRYINCLUDE_EDITOR_MATERIAL_MATERIALMANAGER_H -#pragma once - -#include "BaseLibraryManager.h" -#include "Material.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -class CMaterial; -class CMaterialLibrary; -class CMaterialHighlighter; - -namespace AZ -{ - struct Uuid; -} - -namespace AzToolsFramework -{ - namespace AssetBrowser - { - struct SourceFileOpenerDetails; - typedef AZStd::vector SourceFileOpenerList; - } -} - -enum EHighlightMode -{ - eHighlight_Pick = BIT(0), - eHighlight_Breakable = BIT(1), - eHighlight_NoSurfaceType = BIT(2), - eHighlight_All = 0xFFFFFFFF -}; - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -/** Manages all entity prototypes and material libraries. -*/ -class CRYEDIT_API CMaterialManager - : public IEditorMaterialManager - , public CBaseLibraryManager - , public IMaterialManagerListener - , protected AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler - , public AzToolsFramework::AssetBrowser::AssetBrowserModelNotificationBus::Handler - , public AzFramework::AssetCatalogEventBus::Handler - , public AzToolsFramework::EditorEvents::Bus::Handler -{ -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING -public: - - //! Notification callback. - typedef AZStd::function NotifyCallback; - - CMaterialManager(CRegistrationContext& regCtx); - ~CMaterialManager(); - - void Set3DEngine(); - - // Clear all prototypes and material libraries. - void ClearAll(); - - ////////////////////////////////////////////////////////////////////////// - // Materials. - ////////////////////////////////////////////////////////////////////////// - - // Loads material. - CMaterial* LoadMaterial(const QString& sMaterialName, bool bMakeIfNotFound = true); - XmlNodeRef LoadXmlNode(const QString &fullSourcePath, const QString &relativeFilePath); - //! Loads a material, avoiding a call to CMaterialManager::MaterialToFilename if the full path is already known - CMaterial* LoadMaterialWithFullSourcePath(const QString& relativeFilePath, const QString& fullSourcePath, bool makeIfNotFound = true); - virtual CMaterial* LoadMaterial(const char* sMaterialName, bool bMakeIfNotFound = true); - virtual void OnRequestMaterial(_smart_ptr pMaterial); - // Creates a new material from a xml node. - CMaterial* CreateMaterial(const QString& sMaterialName, const XmlNodeRef& node = XmlNodeRef(), int nMtlFlags = 0, unsigned long nLoadingFlags = 0); - virtual CMaterial* CreateMaterial(const char* sMaterialName, const XmlNodeRef& node = XmlNodeRef(), int nMtlFlags = 0, unsigned long nLoadingFlags = 0); - - // Duplicate material and do nothing more. - CMaterial* DuplicateMaterial(const char* newName, CMaterial* pOriginal); - - // Delete specified material, erases material file, and unassigns from all objects. - virtual void DeleteMaterial(CMaterial* pMtl); - virtual void RemoveMaterialFromDisk(const char* fileName); - - - //! Export property manager to game. - void Export(XmlNodeRef& node); - int ExportLib(CMaterialLibrary* pLib, XmlNodeRef& libNode); - - virtual void SetSelectedItem(IDataBaseItem* pItem); - void SetCurrentMaterial(CMaterial* pMtl); - //! Get currently active material. - CMaterial* GetCurrentMaterial() const; - - void SetCurrentFolder(const QString& folder); - - // This material will be highlighted - void SetHighlightedMaterial(CMaterial* pMtl); - void GetHighlightColor(ColorF* color, float* intensity, int flags); - void HighlightedMaterialChanged(CMaterial* pMtl); - // highlightMask is a combination of EHighlightMode flags - void SetHighlightMask(int highlightMask); - int GetHighlightMask() const{ return m_highlightMask; } - void SetMarkedMaterials(const std::vector<_smart_ptr >& markedMaterials); - void OnLoadShader(CMaterial* pMaterial); - - //! Serialize property manager. - virtual void Serialize(XmlNodeRef& node, bool bLoading); - - virtual void SaveAllLibs(); - - ////////////////////////////////////////////////////////////////////////// - // IMaterialManagerListener implementation - ////////////////////////////////////////////////////////////////////////// - // Called when material manager tries to load a material. - virtual void OnCreateMaterial(_smart_ptr pMaterial); - virtual void OnDeleteMaterial(_smart_ptr pMaterial); - virtual bool IsCurrentMaterial(_smart_ptr pMaterial) const; - ////////////////////////////////////////////////////////////////////////// - - // Convert filename of material file into the name of the material. - QString FilenameToMaterial(const QString& filename); - - // Convert name of the material to the filename. - QString MaterialToFilename(const QString& sMaterialName); - - //! Get the full file path of the source material - const AZ::Data::AssetType& GetMaterialAssetType(); - - ////////////////////////////////////////////////////////////////////////// - // Convert 3DEngine IMaterial to Editor's CMaterial pointer. - CMaterial* FromIMaterial(_smart_ptr pMaterial); - - // Open File selection dialog to create a new material. - CMaterial* SelectNewMaterial(int nMtlFlags, const char* sStartPath = NULL); - - // Synchronize material between 3dsMax and editor. - void SyncMaterialEditor(); - - ////////////////////////////////////////////////////////////////////////// - void GotoMaterial(CMaterial* pMaterial); - void GotoMaterial(_smart_ptr pMaterial); - - // Gather resources from the game material. - static void GatherResources(_smart_ptr pMaterial, CUsedResources& resources); - - void Command_Create(); - void Command_CreateMulti(); - void Command_ConvertToMulti(); - void Command_Duplicate(); - void Command_Merge(); - void Command_Delete(); - void Command_AssignToSelection(); - void Command_ResetSelection(); - void Command_SelectAssignedObjects(); - void Command_SelectFromObject(); - -protected: - ////////////////////////////////////////////////////////////////////////////////////////////////////// - // protected AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler - void AddSourceFileOpeners(const char* fullSourceFileName, const AZ::Uuid& sourceUUID, AzToolsFramework::AssetBrowser::SourceFileOpenerList& openers) override; - ////////////////////////////////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////////////////////////////////// - // public AzToolsFramework::AssetBrowser::AssetBrowserModelNotificationsBus::Handler - void EntryAdded(const AzToolsFramework::AssetBrowser::AssetBrowserEntry* entry); - ////////////////////////////////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////////////////////////////////// - // AssetCatalogEventBus Functions - void OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) override; - ////////////////////////////////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////////////////////////////////// - // EditorEventsBus Functions - bool SkipEditorStartupUI() override; - ////////////////////////////////////////////////////////////////////////////////////////////////////// - - void SaveDccMaterial(const AZStd::string& relativeDccMaterialPath); - bool DccMaterialRequiresSave(const AZStd::string& relativeDccMaterialPath, const AZStd::string& fullSourcePath); - void DccMaterialSourceControlCheck(const AZStd::string& relativeDccMaterialPath); - void AddDccMaterialPath(const AZStd::string relativeDccMaterialPath); - void TickSourceControl(); - void QueueSourceControlTick(); - - // Duplicate the source material and set it as a submaterial of the target material at subMaterialIndex. Returns true if successful. - bool DuplicateAsSubMaterialAtIndex(CMaterial* pSourceMaterial, CMaterial* pTargetMaterial, int subMaterialIndex); - // Generates a unique variant of the name of the source material to resolve name collisions with the names of the submaterials in the target material. - void GenerateUniqueSubmaterialName(const CMaterial* pSourceMaterial, const CMaterial* pTargetMaterial, QString& uniqueSubmaterialName) const; - - // Open save as dialog for saving materials. - bool SelectSaveMaterial(QString& itemName, QString& fullPath, const char* defaultStartPath); - - void OnEditorNotifyEvent(EEditorNotifyEvent event); - - virtual CBaseLibraryItem* MakeNewItem(); - virtual CBaseLibrary* MakeNewLibrary(); - //! Root node where this library will be saved. - virtual QString GetRootNodeName(); - //! Path to libraries in this manager. - virtual QString GetLibsPath(); - virtual void ReportDuplicateItem(CBaseLibraryItem* pItem, CBaseLibraryItem* pOldItem); - - void RegisterCommands(CRegistrationContext& regCtx); - - void UpdateHighlightedMaterials(); - void AddForHighlighting(CMaterial* pMaterial); - void RemoveFromHighlighting(CMaterial* pMaterial, int mask); - int GetHighlightFlags(CMaterial* pMaterial) const; - - // For material syncing with 3dsMax. - void PickPreviewMaterial(); - void InitMatSender(); - - //! Reloads any registered materials that have been modified by the runtime. - void ReloadDirtyMaterials(); - -protected: - QString m_libsPath; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - // Currently selected (focused) material, in material browser. - _smart_ptr m_pCurrentMaterial; - // current selected folder - QString m_currentFolder; - // List of materials selected in material browser tree. - std::vector<_smart_ptr > m_markedMaterials; - // IMaterial is needed to not let 3Dengine release selected IMaterial - _smart_ptr m_pCurrentEngineMaterial; - - // Paths of .dccmtl that might require saving. They will be fed to - // DccMaterialSourceControlCheck() and if saving is required, they - // will be added to m_dccMaterialSaveBuffer - AZStd::vector m_sourceControlBuffer; - AZStd::mutex m_sourceControlBufferMutex; - AZStd::atomic_bool m_sourceControlFunctionQueued; - - // Paths of .dccmtl that require saving. These paths have - // gone through DccMaterialSourceControlCheck() and will - // be saved by the dcc material save thread - AZStd::vector m_dccMaterialSaveBuffer; - AZStd::mutex m_dccMaterialSaveMutex; - - // Material highlighting - _smart_ptr m_pHighlightMaterial; - CMaterialHighlighter* m_pHighlighter; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - int m_highlightMask; - - bool m_bHighlightingMaterial; - - // Only begin processing .dccmtl filepaths once editor is ready - // and we can display appropriate error messages - bool m_bEditorUiReady; - - // Only report source control error to the user once, - // no need to spam them for every material - bool m_bSourceControlErrorReported; - - class CMaterialSender* m_MatSender; - -private: - CMaterial* LoadMaterialInternal(const QString &materialNameClear, const QString &fullSourcePath, const QString &relativeFilePath, bool bMakeIfNotFound); - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - AZ::Data::AssetType m_materialAssetType; - AZ::Data::AssetType m_dccMaterialAssetType; - - void StartDccMaterialSaveThread(); - void DccMaterialSaveThreadFunc(); - AZStd::thread m_dccMaterialSaveThread; - AZStd::atomic_bool m_joinThreads; - AZStd::binary_semaphore m_dccMaterialSaveSemaphore; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // CRYINCLUDE_EDITOR_MATERIAL_MATERIALMANAGER_H diff --git a/Code/Sandbox/Editor/Material/MaterialPreviewModelView.cpp b/Code/Sandbox/Editor/Material/MaterialPreviewModelView.cpp deleted file mode 100644 index 3e1bc37c6a..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialPreviewModelView.cpp +++ /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. -* -*/ - -#include "EditorDefs.h" - -#include "MaterialPreviewModelView.h" - - - -MaterialPreviewModelView::MaterialPreviewModelView(QWidget* parent, bool enableIdleUpdate) - : CPreviewModelView(parent) - , m_enableIdleUpdate(enableIdleUpdate) -{} - -MaterialPreviewModelView::~MaterialPreviewModelView() -{} - -void MaterialPreviewModelView::SetCameraLookAt(float fRadiusScale, const Vec3& fromDir) -{ - IStatObj* target = GetStaticModel(); - if (target) - { - Vec3 dir = fromDir.GetNormalized(); - - // Calculate the camera matrix - Matrix34 tm = Matrix33::CreateRotationVDir(dir, 0); - Vec3 translation = target->GetAABB().GetCenter() - dir * target->GetAABB().GetRadius() * fRadiusScale; - tm.SetTranslation(translation); - - // Convert it to a quaternion and move the viewport's camera - QuatT quat(tm); - CameraMoved(quat, true); - } -} - -void MaterialPreviewModelView::SetMaterial(_smart_ptr material) -{ - IStatObj* staticModel = GetStaticModel(); - if (staticModel) - { - staticModel->SetMaterial(material); - } -} - -void MaterialPreviewModelView::resizeEvent(QResizeEvent* event) -{ - if (m_enableIdleUpdate) - { - CPreviewModelView::resizeEvent(event); - } -} - -void MaterialPreviewModelView::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnIdleUpdate: - { - if (m_enableIdleUpdate) - { - Update(); - } - break; - } - default: - break; - } -} diff --git a/Code/Sandbox/Editor/Material/MaterialPreviewModelView.h b/Code/Sandbox/Editor/Material/MaterialPreviewModelView.h deleted file mode 100644 index 0df7c1767f..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialPreviewModelView.h +++ /dev/null @@ -1,35 +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 "PreviewModelView.h" - -class MaterialPreviewModelView - : public CPreviewModelView -{ -public: - // set enableIdleUpdate to false if you don't want the view to update itself during - // application idle notification (and resize events). That makes sense when this view - // is only used to render into memory bitmaps. Note that the view has to been visible - // for that, but can be somewhere of-screen. - MaterialPreviewModelView(QWidget* parent, bool enableIdleUpdate = true); - virtual ~MaterialPreviewModelView(); - void SetCameraLookAt(float fRadiusScale, const Vec3& fromDir); - void SetMaterial(_smart_ptr material); - void OnEditorNotifyEvent(EEditorNotifyEvent event) override; - -protected: - void resizeEvent(QResizeEvent* event) override; - -private: - bool m_enableIdleUpdate; -}; diff --git a/Code/Sandbox/Editor/Material/MaterialPythonFuncs.cpp b/Code/Sandbox/Editor/Material/MaterialPythonFuncs.cpp deleted file mode 100644 index 5de75a7c39..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialPythonFuncs.cpp +++ /dev/null @@ -1,2208 +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 : Material support for Python - -#include "EditorDefs.h" - -#include "MaterialPythonFuncs.h" - -// Editor -#include "MaterialManager.h" -#include "ShaderEnum.h" - - -namespace -{ - void PyMaterialCreate() - { - GetIEditor()->GetMaterialManager()->Command_Create(); - } - - void PyMaterialCreateMulti() - { - GetIEditor()->GetMaterialManager()->Command_CreateMulti(); - } - - void PyMaterialConvertToMulti() - { - GetIEditor()->GetMaterialManager()->Command_ConvertToMulti(); - } - - void PyMaterialDuplicateCurrent() - { - GetIEditor()->GetMaterialManager()->Command_Duplicate(); - } - - void PyMaterialMergeSelection() - { - GetIEditor()->GetMaterialManager()->Command_Merge(); - } - - void PyMaterialDeleteCurrent() - { - GetIEditor()->GetMaterialManager()->Command_Delete(); - } - - void PyMaterialAssignCurrentToSelection() - { - CUndo undo("Assign Material To Selection"); - GetIEditor()->GetMaterialManager()->Command_AssignToSelection(); - } - - void PyMaterialResetSelection() - { - GetIEditor()->GetMaterialManager()->Command_ResetSelection(); - } - - void PyMaterialSelectObjectsWithCurrent() - { - CUndo undo("Select Objects With Current Material"); - GetIEditor()->GetMaterialManager()->Command_SelectAssignedObjects(); - } - - void PyMaterialSetCurrentFromObject() - { - GetIEditor()->GetMaterialManager()->Command_SelectFromObject(); - } - - AZStd::vector PyGetSubMaterial(const char* pMaterialPath) - { - QString materialPath = pMaterialPath; - CMaterial* pMaterial = GetIEditor()->GetMaterialManager()->LoadMaterial(pMaterialPath, false); - if (!pMaterial) - { - throw std::runtime_error("Invalid multi material."); - } - - AZStd::vector result; - for (int i = 0; i < pMaterial->GetSubMaterialCount(); i++) - { - if (pMaterial->GetSubMaterial(i)) - { - result.push_back((materialPath + "\\" + pMaterial->GetSubMaterial(i)->GetName()).toUtf8().data()); - } - } - return result; - } - - CMaterial* TryLoadingMaterial(const char* pPathAndMaterialName) - { - QString varMaterialPath = pPathAndMaterialName; - std::deque splittedMaterialPath; - for (auto token : varMaterialPath.split(QRegularExpression(R"([\\/])"), Qt::SkipEmptyParts)) - { - splittedMaterialPath.push_back(token); - } - - CMaterial* pMaterial = GetIEditor()->GetMaterialManager()->LoadMaterial(varMaterialPath, false); - if (!pMaterial) - { - QString subMaterialName = splittedMaterialPath.back(); - bool isSubMaterialExist(false); - - varMaterialPath.remove((varMaterialPath.length() - subMaterialName.length() - 1), varMaterialPath.length()); - QString test = varMaterialPath; - pMaterial = GetIEditor()->GetMaterialManager()->LoadMaterial(varMaterialPath, false); - - if (!pMaterial) - { - throw std::runtime_error("Invalid multi material."); - } - - for (int i = 0; i < pMaterial->GetSubMaterialCount(); i++) - { - if (pMaterial->GetSubMaterial(i)->GetName() == subMaterialName) - { - pMaterial = pMaterial->GetSubMaterial(i); - isSubMaterialExist = true; - } - } - - if (!pMaterial || !isSubMaterialExist) - { - throw std::runtime_error((QString("\"") + subMaterialName + "\" is an invalid sub material.").toUtf8().data()); - } - } - GetIEditor()->GetMaterialManager()->SetCurrentMaterial(pMaterial); - return pMaterial; - } - - std::deque PreparePropertyPath(const char* pPathAndPropertyName) - { - QString varPathProperty = pPathAndPropertyName; - std::deque splittedPropertyPath; - for (auto token : varPathProperty.split(QRegularExpression(R"([\\/])"), Qt::SkipEmptyParts)) - { - splittedPropertyPath.push_back(token); - } - - return splittedPropertyPath; - } - - ////////////////////////////////////////////////////////////////////////// - // Converter: Enum -> CString (human readable) - ////////////////////////////////////////////////////////////////////////// - - QString TryConvertingSEFResTextureToCString(SEfResTexture* pResTexture) - { - if (pResTexture) - { - return pResTexture->m_Name.c_str(); - } - return ""; - } - - QString TryConvertingETEX_TypeToCString(const uint8& texTypeName) - { - switch (texTypeName) - { - case eTT_2D: - return "2D"; - case eTT_Cube: - return "Cube-Map"; - case eTT_NearestCube: - return "Nearest Cube-Map probe for alpha blended"; - case eTT_Auto2D: - return "Auto 2D-Map"; - case eTT_Dyn2D: - return "Dynamic 2D-Map"; - case eTT_User: - return "From User Params"; - default: - throw std::runtime_error("Invalid tex type."); - } - } - - QString TryConvertingTexFilterToCString(const int& iFilterName) - { - switch (iFilterName) - { - case FILTER_NONE: - return "Default"; - case FILTER_POINT: - return "Point"; - case FILTER_LINEAR: - return "Linear"; - case FILTER_BILINEAR: - return "Bilinear"; - case FILTER_TRILINEAR: - return "Trilinear"; - case FILTER_ANISO2X: - return "Anisotropic 2x"; - case FILTER_ANISO4X: - return "Anisotropic 4x"; - case FILTER_ANISO8X: - return "Anisotropic 8x"; - case FILTER_ANISO16X: - return "Anisotropic 16x"; - default: - throw std::runtime_error("Invalid tex filter."); - } - } - - QString TryConvertingETexGenTypeToCString(const uint8& texGenType) - { - switch (texGenType) - { - case ETG_Stream: - return "Stream"; - case ETG_World: - return "World"; - case ETG_Camera: - return "Camera"; - default: - throw std::runtime_error("Invalid tex gen type."); - } - } - - QString TryConvertingETexModRotateTypeToCString(const uint8& rotateType) - { - switch (rotateType) - { - case ETMR_NoChange: - return "No Change"; - case ETMR_Fixed: - return "Fixed Rotation"; - case ETMR_Constant: - return "Constant Rotation"; - case ETMR_Oscillated: - return "Oscillated Rotation"; - default: - throw std::runtime_error("Invalid rotate type."); - } - } - - QString TryConvertingETexModMoveTypeToCString(const uint8& oscillatorType) - { - switch (oscillatorType) - { - case ETMM_NoChange: - return "No Change"; - case ETMM_Fixed: - return "Fixed Moving"; - case ETMM_Constant: - return "Constant Moving"; - case ETMM_Jitter: - return "Jitter Moving"; - case ETMM_Pan: - return "Pan Moving"; - case ETMM_Stretch: - return "Stretch Moving"; - case ETMM_StretchRepeat: - return "Stretch-Repeat Moving"; - default: - throw std::runtime_error("Invalid oscillator type."); - } - } - - QString TryConvertingEDeformTypeToCString(const EDeformType& deformType) - { - switch (deformType) - { - case eDT_Unknown: - return "None"; - case eDT_SinWave: - return "Sin Wave"; - case eDT_SinWaveUsingVtxColor: - return "Sin Wave using vertex color"; - case eDT_Bulge: - return "Bulge"; - case eDT_Squeeze: - return "Squeeze"; - case eDT_Perlin2D: - return "Perlin 2D"; - case eDT_Perlin3D: - return "Perlin 3D"; - case eDT_FromCenter: - return "From Center"; - case eDT_Bending: - return "Bending"; - case eDT_ProcFlare: - return "Proc. Flare"; - case eDT_AutoSprite: - return "Auto sprite"; - case eDT_Beam: - return "Beam"; - case eDT_FixedOffset: - return "FixedOffset"; - default: - throw std::runtime_error("Invalid deform type."); - } - } - - QString TryConvertingEWaveFormToCString(const EWaveForm& waveForm) - { - switch (waveForm) - { - case eWF_None: - return "None"; - case eWF_Sin: - return "Sin"; - case eWF_HalfSin: - return "Half Sin"; - case eWF_Square: - return "Square"; - case eWF_Triangle: - return "Triangle"; - case eWF_SawTooth: - return "Saw Tooth"; - case eWF_InvSawTooth: - return "Inverse Saw Tooth"; - case eWF_Hill: - return "Hill"; - case eWF_InvHill: - return "Inverse Hill"; - default: - throw std::runtime_error("Invalid wave form."); - } - } - - ////////////////////////////////////////////////////////////////////////// - // Converter: CString -> Enum - ////////////////////////////////////////////////////////////////////////// - - template - // [Shader System TO DO] remove once dynamic slots assingment is in place - EEfResTextures TryConvertingCStringToEEfResTextures(const STRING& resTextureName) - { - if (resTextureName == "Diffuse") - { - return EFTT_DIFFUSE; - } - else if (resTextureName == "Specular") - { - return EFTT_SPECULAR; - } - else if (resTextureName == "Bumpmap") - { - return EFTT_NORMALS; - } - else if (resTextureName == "Heightmap") - { - return EFTT_HEIGHT; - } - else if (resTextureName == "Environment") - { - return EFTT_ENV; - } - else if (resTextureName == "Detail") - { - return EFTT_DETAIL_OVERLAY; - } - else if (resTextureName == "Opacity") - { - return EFTT_OPACITY; - } - else if (resTextureName == "Decal") - { - return EFTT_DECAL_OVERLAY; - } - else if (resTextureName == "SubSurface") - { - return EFTT_SUBSURFACE; - } - else if (resTextureName == "Custom") - { - return EFTT_CUSTOM; - } - else if (resTextureName == "[1] Custom") - { - return EFTT_DIFFUSE; - } - else if (resTextureName == "Emittance") - { - return EFTT_EMITTANCE; - } - else if (resTextureName == "Occlusion") - { - return EFTT_OCCLUSION; - } - else if (resTextureName == "Specular2") - { - return EFTT_SPECULAR_2; - } - throw std::runtime_error("Invalid texture name."); - } - - template - ETEX_Type TryConvertingCStringToETEX_Type(const STRING& texTypeName) - { - if (texTypeName == "2D") - { - return eTT_2D; - } - else if (texTypeName == "Cube-Map") - { - return eTT_Cube; - } - else if (texTypeName == "Nearest Cube-Map probe for alpha blended") - { - return eTT_NearestCube; - } - else if (texTypeName == "Auto 2D-Map") - { - return eTT_Auto2D; - } - else if (texTypeName == "Dynamic 2D-Map") - { - return eTT_Dyn2D; - } - else if (texTypeName == "From User Params") - { - return eTT_User; - } - throw std::runtime_error("Invalid tex type name."); - } - - template - signed char TryConvertingCStringToTexFilter(const STRING& filterName) - { - if (filterName == "Default") - { - return FILTER_NONE; - } - else if (filterName == "Point") - { - return FILTER_POINT; - } - else if (filterName == "Linear") - { - return FILTER_LINEAR; - } - else if (filterName == "Bilinear") - { - return FILTER_BILINEAR; - } - else if (filterName == "Trilinear") - { - return FILTER_TRILINEAR; - } - else if (filterName == "Anisotropic 2x") - { - return FILTER_ANISO2X; - } - else if (filterName == "Anisotropic 4x") - { - return FILTER_ANISO4X; - } - else if (filterName == "Anisotropic 8x") - { - return FILTER_ANISO8X; - } - else if (filterName == "Anisotropic 16x") - { - return FILTER_ANISO16X; - } - throw std::runtime_error("Invalid filter name."); - } - - template - ETexGenType TryConvertingCStringToETexGenType(const STRING& texGenType) - { - if (texGenType == "Stream") - { - return ETG_Stream; - } - else if (texGenType == "World") - { - return ETG_World; - } - else if (texGenType == "Camera") - { - return ETG_Camera; - } - throw std::runtime_error("Invalid tex gen type name."); - } - - template - ETexModRotateType TryConvertingCStringToETexModRotateType(const STRING& rotateType) - { - if (rotateType == "No Change") - { - return ETMR_NoChange; - } - else if (rotateType == "Fixed Rotation") - { - return ETMR_Fixed; - } - else if (rotateType == "Constant Rotation") - { - return ETMR_Constant; - } - else if (rotateType == "Oscillated Rotation") - { - return ETMR_Oscillated; - } - throw std::runtime_error("Invalid rotate type name."); - } - - template - ETexModMoveType TryConvertingCStringToETexModMoveType(const STRING& oscillatorType) - { - if (oscillatorType == "No Change") - { - return ETMM_NoChange; - } - else if (oscillatorType == "Fixed Moving") - { - return ETMM_Fixed; - } - else if (oscillatorType == "Constant Moving") - { - return ETMM_Constant; - } - else if (oscillatorType == "Jitter Moving") - { - return ETMM_Jitter; - } - else if (oscillatorType == "Pan Moving") - { - return ETMM_Pan; - } - else if (oscillatorType == "Stretch Moving") - { - return ETMM_Stretch; - } - else if (oscillatorType == "Stretch-Repeat Moving") - { - return ETMM_StretchRepeat; - } - throw std::runtime_error("Invalid oscillator type."); - } - - template - EDeformType TryConvertingCStringToEDeformType(const STRING& deformType) - { - if (deformType == "None") - { - return eDT_Unknown; - } - else if (deformType == "Sin Wave") - { - return eDT_SinWave; - } - else if (deformType == "Sin Wave using vertex color") - { - return eDT_SinWaveUsingVtxColor; - } - else if (deformType == "Bulge") - { - return eDT_Bulge; - } - else if (deformType == "Squeeze") - { - return eDT_Squeeze; - } - else if (deformType == "Perlin 2D") - { - return eDT_Perlin2D; - } - else if (deformType == "Perlin 3D") - { - return eDT_Perlin3D; - } - else if (deformType == "From Center") - { - return eDT_FromCenter; - } - else if (deformType == "Bending") - { - return eDT_Bending; - } - else if (deformType == "Proc. Flare") - { - return eDT_ProcFlare; - } - else if (deformType == "Auto sprite") - { - return eDT_AutoSprite; - } - else if (deformType == "Beam") - { - return eDT_Beam; - } - else if (deformType == "FixedOffset") - { - return eDT_FixedOffset; - } - throw std::runtime_error("Invalid deform type."); - } - - template - EWaveForm TryConvertingCStringToEWaveForm(const STRING& waveForm) - { - if (waveForm == "None") - { - return eWF_None; - } - else if (waveForm == "Sin") - { - return eWF_Sin; - } - else if (waveForm == "Half Sin") - { - return eWF_HalfSin; - } - else if (waveForm == "Square") - { - return eWF_Square; - } - else if (waveForm == "Triangle") - { - return eWF_Triangle; - } - else if (waveForm == "Saw Tooth") - { - return eWF_SawTooth; - } - else if (waveForm == "Inverse Saw Tooth") - { - return eWF_InvSawTooth; - } - else if (waveForm == "Hill") - { - return eWF_Hill; - } - else if (waveForm == "Inverse Hill") - { - return eWF_InvHill; - } - throw std::runtime_error("Invalid wave form."); - } - - ////////////////////////////////////////////////////////////////////////// - // Script parser - ////////////////////////////////////////////////////////////////////////// - - QString ParseUINameFromPublicParamsScript(const char* sUIScript) - { - string uiscript = sUIScript; - string element[3]; - int p1 = 0; - string itemToken = uiscript.Tokenize(";", p1); - while (!itemToken.empty()) - { - int nElements = 0; - int p2 = 0; - string token = itemToken.Tokenize(" \t\r\n=", p2); - while (!token.empty()) - { - element[nElements++] = token; - if (nElements == 2) - { - element[nElements] = itemToken.substr(p2); - element[nElements].Trim(" =\t\""); - break; - } - token = itemToken.Tokenize(" \t\r\n=", p2); - } - - if (_stricmp(element[1], "UIName") == 0) - { - return element[2].c_str(); - } - itemToken = uiscript.Tokenize(";", p1); - } - return ""; - } - - std::map ParseValidRangeFromPublicParamsScript(const char* sUIScript) - { - string uiscript = sUIScript; - std::map result; - bool isUIMinExist(false); - bool isUIMaxExist(false); - string element[3]; - int p1 = 0; - string itemToken = uiscript.Tokenize(";", p1); - while (!itemToken.empty()) - { - int nElements = 0; - int p2 = 0; - string token = itemToken.Tokenize(" \t\r\n=", p2); - while (!token.empty()) - { - element[nElements++] = token; - if (nElements == 2) - { - element[nElements] = itemToken.substr(p2); - element[nElements].Trim(" =\t\""); - break; - } - token = itemToken.Tokenize(" \t\r\n=", p2); - } - - if (_stricmp(element[1], "UIMin") == 0) - { - result["UIMin"] = atof(element[2]); - isUIMinExist = true; - } - if (_stricmp(element[1], "UIMax") == 0) - { - result["UIMax"] = atof(element[2]); - isUIMaxExist = true; - } - itemToken = uiscript.Tokenize(";", p1); - } - if (!isUIMinExist || !isUIMaxExist) - { - throw std::runtime_error("Invalid range for shader param."); - } - return result; - } - - ////////////////////////////////////////////////////////////////////////// - // Set Flags - ////////////////////////////////////////////////////////////////////////// - - void SetMaterialFlag(CMaterial* pMaterial, const EMaterialFlags& eFlag, const bool& bFlag) - { - if (pMaterial->GetFlags() & eFlag && bFlag == false) - { - pMaterial->SetFlags(pMaterial->GetFlags() - eFlag); - } - else if (!(pMaterial->GetFlags() & eFlag) && bFlag == true) - { - pMaterial->SetFlags(pMaterial->GetFlags() | eFlag); - } - } - - void SetPropagationFlag(CMaterial* pMaterial, const eMTL_PROPAGATION& eFlag, const bool& bFlag) - { - if (pMaterial->GetPropagationFlags() & eFlag && bFlag == false) - { - pMaterial->SetPropagationFlags(pMaterial->GetPropagationFlags() - eFlag); - } - else if (!(pMaterial->GetPropagationFlags() & eFlag) && bFlag == true) - { - pMaterial->SetPropagationFlags(pMaterial->GetPropagationFlags() | eFlag); - } - } - - ////////////////////////////////////////////////////////////////////////// - template - bool IsAnyValidRange(const AZStd::any& value, const T& low, const T& high, const QString& invalidTypeMessage, const QString& invalidValueMessage) - { - static_assert(AZStd::is_arithmetic::value, "This function only works with numbers."); - - if (!value.is()) - { - throw std::runtime_error(invalidTypeMessage.toUtf8().data()); - } - - T valueData; - AZStd::any_numeric_cast(&value, valueData); - if (valueData < low || valueData > high) - { - throw std::runtime_error(invalidValueMessage.toUtf8().data()); - } - return true; - } - - template <> - bool IsAnyValidRange(const AZStd::any& value, const AZ::Color& low, const AZ::Color& high, const QString& invalidTypeMessage, const QString& invalidValueMessage) - { - if (!value.is()) - { - throw std::runtime_error(invalidTypeMessage.toUtf8().data()); - } - - const AZ::Color* valueData = AZStd::any_cast(&value); - if (!valueData) - { - throw std::runtime_error(invalidValueMessage.toUtf8().data()); - } - - if (valueData->IsLessThan(low) || valueData->IsGreaterThan(high)) - { - throw std::runtime_error(invalidValueMessage.toUtf8().data()); - } - return true; - } - - bool ValidateProperty(CMaterial* pMaterial, const std::deque& splittedPropertyPathParam, const AZStd::any& value) - { - std::deque splittedPropertyPath = splittedPropertyPathParam; - std::deque splittedPropertyPathSubCategory = splittedPropertyPathParam; - QString categoryName = splittedPropertyPath.front(); - QString subCategoryName = ""; - QString subSubCategoryName = ""; - QString currentPath = ""; - QString propertyName = splittedPropertyPath.back(); - - QString errorMsgInvalidValue = QString("Invalid value for property \"") + propertyName + "\""; - QString errorMsgInvalidDataType = QString("Invalid data type for property \"") + propertyName + "\""; - QString errorMsgInvalidPropertyPath = QString("Invalid property path"); - - const int iMinColorValue = 0; - const int iMaxColorValue = 255; - - if (splittedPropertyPathSubCategory.size() == 3) - { - splittedPropertyPathSubCategory.pop_back(); - subCategoryName = splittedPropertyPathSubCategory.back(); - currentPath = QString("") + categoryName + "/" + subCategoryName; - - if ( - subCategoryName != "TexType" && - subCategoryName != "Filter" && - subCategoryName != "IsProjectedTexGen" && - subCategoryName != "TexGenType" && - subCategoryName != "Wave X" && - subCategoryName != "Wave Y" && - subCategoryName != "Wave Z" && - subCategoryName != "Wave W" && - subCategoryName != "Shader1" && - subCategoryName != "Shader2" && - subCategoryName != "Shader3" && - subCategoryName != "Tiling" && - subCategoryName != "Rotator" && - subCategoryName != "Oscillator" && - subCategoryName != "Diffuse" && - subCategoryName != "Specular" && - subCategoryName != "Bumpmap" && - subCategoryName != "Heightmap" && - subCategoryName != "Environment" && - subCategoryName != "Detail" && - subCategoryName != "Opacity" && - subCategoryName != "Decal" && - subCategoryName != "SubSurface" && - subCategoryName != "Custom" && - subCategoryName != "[1] Custom" - ) - { - throw std::runtime_error((errorMsgInvalidPropertyPath + " (" + currentPath + ")").toUtf8().data()); - } - } - else if (splittedPropertyPathSubCategory.size() == 4) - { - splittedPropertyPathSubCategory.pop_back(); - subCategoryName = splittedPropertyPathSubCategory.back(); - splittedPropertyPathSubCategory.pop_back(); - subSubCategoryName = splittedPropertyPathSubCategory.back(); - currentPath = categoryName + "/" + subSubCategoryName + "/" + subCategoryName; - - if ( - subSubCategoryName != "Diffuse" && - subSubCategoryName != "Specular" && - subSubCategoryName != "Bumpmap" && - subSubCategoryName != "Heightmap" && - subSubCategoryName != "Environment" && - subSubCategoryName != "Detail" && - subSubCategoryName != "Opacity" && - subSubCategoryName != "Decal" && - subSubCategoryName != "SubSurface" && - subSubCategoryName != "Custom" && - subSubCategoryName != "[1] Custom" - ) - { - throw std::runtime_error((errorMsgInvalidPropertyPath + " (" + currentPath + ")").toUtf8().data()); - } - else if (subCategoryName != "Tiling" && subCategoryName != "Rotator" && subCategoryName != "Oscillator") - { - throw std::runtime_error((errorMsgInvalidPropertyPath + " (" + currentPath + ")").toUtf8().data()); - } - } - else - { - currentPath = categoryName; - } - - if ( - categoryName == "Material Settings" || - categoryName == "Opacity Settings" || - categoryName == "Lighting Settings" || - categoryName == "Advanced" || - categoryName == "Texture Maps" || - categoryName == "Vertex Deformation" || - categoryName == "Layer Presets") - { - if (propertyName == "Opacity" || propertyName == "AlphaTest" || propertyName == "Glow Amount") - { - // int: 0 < x < 100 - if (!value.is()) - { - throw std::runtime_error(errorMsgInvalidDataType.toUtf8().data()); - } - - AZ::s64 valueData; - AZStd::any_numeric_cast(&value, valueData); - if (valueData < 0 || valueData > 100) - { - throw std::runtime_error(errorMsgInvalidValue.toUtf8().data()); - } - return true; - } - else if (propertyName == "Smoothness" || propertyName == "Glossiness") - { - // int: 0 < x < 255 - return IsAnyValidRange(value, 0, 255, errorMsgInvalidDataType, errorMsgInvalidValue); - } - else if (propertyName == "Specular Level") - { - // float: 0.0 < x < 4.0 - return IsAnyValidRange(value, 0.0, 4.0, errorMsgInvalidDataType, errorMsgInvalidValue); - } - else if ( - propertyName == "TileU" || - propertyName == "TileV" || - propertyName == "OffsetU" || - propertyName == "OffsetV" || - propertyName == "RotateU" || - propertyName == "RotateV" || - propertyName == "RotateW" || - propertyName == "Rate" || - propertyName == "Phase" || - propertyName == "Amplitude" || - propertyName == "CenterU" || - propertyName == "CenterV" || - propertyName == "RateU" || - propertyName == "RateV" || - propertyName == "PhaseU" || - propertyName == "PhaseV" || - propertyName == "AmplitudeU" || - propertyName == "AmplitudeV" || - propertyName == "Wave Length X" || - propertyName == "Wave Length Y" || - propertyName == "Wave Length Z" || - propertyName == "Wave Length W" || - propertyName == "Level" || - propertyName == "Amplitude" || - propertyName == "Phase" || - propertyName == "Frequency") - { - // float: 0.0 < x < 100.0 - return IsAnyValidRange(value, 0.0, 100.0, errorMsgInvalidDataType, errorMsgInvalidValue); - } - else if (propertyName == "Voxel Coverage") - { - // float: 0.0 < x < 1.0 - return IsAnyValidRange(value, 0.0, 1.0, errorMsgInvalidDataType, errorMsgInvalidValue); - } - else if (propertyName == "Emissive Intensity") - { - // float: 0.0 < x < 200.0 - return IsAnyValidRange(value, 0.0, 200.0, errorMsgInvalidDataType, errorMsgInvalidValue); - } - else if (propertyName == "Diffuse Color" || propertyName == "Specular Color" || propertyName == "Emissive Color") - { - // intVector(RGB): 0 < x < 255 - return IsAnyValidRange(value, AZ::Color::CreateZero(), AZ::Color::CreateOne(), errorMsgInvalidDataType, errorMsgInvalidValue); - } - else if ( - propertyName == "Link to Material" || - propertyName == "Surface Type" || - propertyName == "Diffuse" || - propertyName == "Specular" || - propertyName == "Bumpmap" || - propertyName == "Heightmap" || - propertyName == "Environment" || - propertyName == "Detail" || - propertyName == "Opacity" || - propertyName == "Decal" || - propertyName == "SubSurface" || - propertyName == "Custom" || - propertyName == "[1] Custom" || - propertyName == "TexType" || - propertyName == "Filter" || - propertyName == "TexGenType" || - propertyName == "Type" || - propertyName == "TypeU" || - propertyName == "TypeV") - { - // string - if (!value.is()) - { - throw std::runtime_error(errorMsgInvalidDataType.toUtf8().data()); - } - return true; - } - else if ( - propertyName == "Additive" || - propertyName == "Allow layer activation" || - propertyName == "2 Sided" || - propertyName == "No Shadow" || - propertyName == "Use Scattering" || - propertyName == "Hide After Breaking" || - propertyName == "Fog Volume Shading Quality High" || - propertyName == "Blend Terrain Color" || - propertyName == "Propagate Material Settings" || - propertyName == "Propagate Opacity Settings" || - propertyName == "Propagate Lighting Settings" || - propertyName == "Propagate Advanced Settings" || - propertyName == "Propagate Texture Maps" || - propertyName == "Propagate Shader Params" || - propertyName == "Propagate Shader Generation" || - propertyName == "Propagate Vertex Deformation" || - propertyName == "Propagate Layer Presets" || - propertyName == "IsProjectedTexGen" || - propertyName == "IsTileU" || - propertyName == "IsTileV" || - propertyName == "No Draw") - { - // bool - if (!value.is()) - { - throw std::runtime_error(errorMsgInvalidDataType.toUtf8().data()); - } - return true; - } - else if (propertyName == "Shader" || propertyName == "Shader1" || propertyName == "Shader2" || propertyName == "Shader3") - { - // string && valid shader - if (!value.is()) - { - throw std::runtime_error(errorMsgInvalidDataType.toUtf8().data()); - } - - CShaderEnum* pShaderEnum = GetIEditor()->GetShaderEnum(); - if (!pShaderEnum) - { - throw std::runtime_error("Shader enumerator corrupted."); - } - pShaderEnum->EnumShaders(); - for (int i = 0; i < pShaderEnum->GetShaderCount(); i++) - { - if (pShaderEnum->GetShader(i) == AZStd::any_cast(value).data()) - { - return true; - } - } - } - else if (propertyName == "Noise Scale") - { - // FloatVec: undefined < x < undefined - if (!value.is()) - { - throw std::runtime_error(errorMsgInvalidDataType.toUtf8().data()); - } - return true; - } - } - else if (categoryName == "Shader Params") - { - auto& shaderParams = pMaterial->GetShaderResources().m_ShaderParams; - for (int i = 0; i < shaderParams.size(); i++) - { - if (propertyName == ParseUINameFromPublicParamsScript(shaderParams[i].m_Script.c_str())) - { - if (shaderParams[i].m_Type == eType_FLOAT) - { - // float: valid range (from script) - float floatValue; - if (!AZStd::any_numeric_cast(&value, floatValue)) - { - throw std::runtime_error(errorMsgInvalidDataType.toUtf8().data()); - } - std::map range = ParseValidRangeFromPublicParamsScript(shaderParams[i].m_Script.c_str()); - if (floatValue < range["UIMin"] || floatValue > range["UIMax"]) - { - QString errorMsg; - errorMsg = QStringLiteral("Invalid value for shader param \"%1\" (min: %2, max: %3)").arg(propertyName).arg(range["UIMin"]).arg(range["UIMax"]); - throw std::runtime_error(errorMsg.toUtf8().data()); - } - return true; - } - else if (shaderParams[i].m_Type == eType_FCOLOR) - { - return IsAnyValidRange(value, AZ::Color::CreateZero(), AZ::Color::CreateOne(), errorMsgInvalidDataType, errorMsgInvalidValue); - } - } - } - } - else if (categoryName == "Shader Generation Params") - { - for (int i = 0; i < pMaterial->GetShaderGenParamsVars()->GetNumVariables(); i++) - { - if (propertyName == pMaterial->GetShaderGenParamsVars()->GetVariable(i)->GetHumanName()) - { - if (!value.is()) - { - throw std::runtime_error(errorMsgInvalidDataType.toUtf8().data()); - } - return true; - } - } - } - else - { - throw std::runtime_error((errorMsgInvalidPropertyPath + " (" + currentPath + ")").toUtf8().data()); - } - return false; - } - - ////////////////////////////////////////////////////////////////////////// - template - T PyFetchNumericType(const AZStd::any& value) - { - T numericValue; - AZStd::any_numeric_cast(&value, numericValue); - return numericValue; - } - - AZStd::any PyGetProperty(const char* pPathAndMaterialName, const char* pPathAndPropertyName) - { - CMaterial* pMaterial = TryLoadingMaterial(pPathAndMaterialName); - std::deque splittedPropertyPath = PreparePropertyPath(pPathAndPropertyName); - std::deque splittedPropertyPathCategory = splittedPropertyPath; - QString categoryName = splittedPropertyPath.front(); - QString subCategoryName = "None"; - QString subSubCategoryName = "None"; - QString propertyName = splittedPropertyPath.back(); - QString errorMsgInvalidPropertyPath = "Invalid property path."; - - if (splittedPropertyPathCategory.size() == 3) - { - splittedPropertyPathCategory.pop_back(); - subCategoryName = splittedPropertyPathCategory.back(); - } - else if (splittedPropertyPathCategory.size() == 4) - { - splittedPropertyPathCategory.pop_back(); - subCategoryName = splittedPropertyPathCategory.back(); - splittedPropertyPathCategory.pop_back(); - subSubCategoryName = splittedPropertyPathCategory.back(); - } - - // ########## Material Settings ########## - if (categoryName == "Material Settings") - { - if (propertyName == "Shader") - { - return AZStd::make_any(pMaterial->GetShaderName().toUtf8().data()); - } - else if (propertyName == "Surface Type") - { - QString stringValue = pMaterial->GetSurfaceTypeName(); - if (stringValue.startsWith("mat_")) - { - stringValue.remove(0, 4); - } - return AZStd::make_any(stringValue.toLatin1().data()); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid material setting.").toUtf8().data()); - } - } - // ########## Opacity Settings ########## - else if (categoryName == "Opacity Settings") - { - if (propertyName == "Opacity") - { - AZ::s64 intValue = aznumeric_cast(pMaterial->GetShaderResources().m_LMaterial.m_Opacity * 100.0f); - return AZStd::make_any(intValue); - } - else if (propertyName == "AlphaTest") - { - AZ::s64 intValue = aznumeric_cast(pMaterial->GetShaderResources().m_AlphaRef * 100.0f); - return AZStd::make_any(intValue); - } - else if (propertyName == "Additive") - { - return AZStd::make_any(pMaterial->GetFlags() & MTL_FLAG_ADDITIVE); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid opacity setting.").toUtf8().data()); - } - } - // ########## Lighting Settings ########## - else if (categoryName == "Lighting Settings") - { - if (propertyName == "Diffuse Color") - { - QColor col = ColorLinearToGamma(ColorF( - pMaterial->GetShaderResources().m_LMaterial.m_Diffuse.r, - pMaterial->GetShaderResources().m_LMaterial.m_Diffuse.g, - pMaterial->GetShaderResources().m_LMaterial.m_Diffuse.b)); - return AZStd::make_any(col.red(), col.green(), col.blue(), 1.0f); - } - else if (propertyName == "Specular Color") - { - QColor col = ColorLinearToGamma(ColorF( - pMaterial->GetShaderResources().m_LMaterial.m_Specular.r / pMaterial->GetShaderResources().m_LMaterial.m_Specular.a, - pMaterial->GetShaderResources().m_LMaterial.m_Specular.g / pMaterial->GetShaderResources().m_LMaterial.m_Specular.a, - pMaterial->GetShaderResources().m_LMaterial.m_Specular.b / pMaterial->GetShaderResources().m_LMaterial.m_Specular.a)); - return AZStd::make_any(col.red(), col.green(), col.blue(), 1.0f); - } - else if (propertyName == "Glossiness") - { - return AZStd::make_any(pMaterial->GetShaderResources().m_LMaterial.m_Smoothness); - } - else if (propertyName == "Specular Level") - { - return AZStd::make_any(pMaterial->GetShaderResources().m_LMaterial.m_Specular.a); - } - else if (propertyName == "Emissive Color") - { - QColor col = ColorLinearToGamma(ColorF( - pMaterial->GetShaderResources().m_LMaterial.m_Emittance.r, - pMaterial->GetShaderResources().m_LMaterial.m_Emittance.g, - pMaterial->GetShaderResources().m_LMaterial.m_Emittance.b)); - return AZStd::make_any(col.red(), col.green(), col.blue(), 1.0f); - } - else if (propertyName == "Emissive Intensity") - { - return AZStd::make_any(pMaterial->GetShaderResources().m_LMaterial.m_Emittance.a); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid lighting setting.").toUtf8().data()); - } - } - // ########## Advanced ########## - else if (categoryName == "Advanced") - { - if (propertyName == "Allow layer activation") - { - return AZStd::make_any(pMaterial->LayerActivationAllowed()); - } - else if (propertyName == "2 Sided") - { - return AZStd::make_any(pMaterial->GetFlags() & MTL_FLAG_2SIDED); - } - else if (propertyName == "No Shadow") - { - return AZStd::make_any(pMaterial->GetFlags() & MTL_FLAG_NOSHADOW); - } - else if (propertyName == "Use Scattering") - { - return AZStd::make_any(pMaterial->GetFlags() & MTL_FLAG_SCATTER); - } - else if (propertyName == "Hide After Breaking") - { - return AZStd::make_any(pMaterial->GetFlags() & MTL_FLAG_HIDEONBREAK); - } - else if (propertyName == "Fog Volume Shading Quality High") - { - return AZStd::make_any(pMaterial->GetFlags() & MTL_FLAG_FOG_VOLUME_SHADING_QUALITY_HIGH); - } - else if (propertyName == "Blend Terrain Color") - { - return AZStd::make_any(pMaterial->GetFlags() & MTL_FLAG_BLEND_TERRAIN); - } - else if (propertyName == "Voxel Coverage") - { - return AZStd::make_any(aznumeric_cast(pMaterial->GetShaderResources().m_VoxelCoverage) / 255.0f); - } - else if (propertyName == "Link to Material") - { - return AZStd::make_any(pMaterial->GetMatInfo()->GetMaterialLinkName()); - } - else if (propertyName == "Propagate Material Settings") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_MATERIAL_SETTINGS); - } - else if (propertyName == "Propagate Opacity Settings") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_OPACITY); - } - else if (propertyName == "Propagate Lighting Settings") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_LIGHTING); - } - else if (propertyName == "Propagate Advanced Settings") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_ADVANCED); - } - else if (propertyName == "Propagate Texture Maps") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_TEXTURES); - } - else if (propertyName == "Propagate Shader Params") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_SHADER_PARAMS); - } - else if (propertyName == "Propagate Shader Generation") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_SHADER_GEN); - } - else if (propertyName == "Propagate Vertex Deformation") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_VERTEX_DEF); - } - else if (propertyName == "Propagate Layer Presets") - { - return AZStd::make_any(pMaterial->GetPropagationFlags() & MTL_PROPAGATE_LAYER_PRESETS); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid advanced setting.").toUtf8().data()); - } - } - // ########## Texture Maps ########## - else if (categoryName == "Texture Maps") - { - SInputShaderResources& shaderResources = pMaterial->GetShaderResources(); - // ########## Texture Maps / [name] ########## - if (splittedPropertyPath.size() == 2) - { - uint16 nSlot = aznumeric_cast(TryConvertingCStringToEEfResTextures(propertyName)); - SEfResTexture* pTextureRes = shaderResources.GetTextureResource(nSlot); - if (!pTextureRes || pTextureRes->m_Name.empty()) - { - AZ_Warning("ShadersSystem", false, "PyGetProperty - Error: empty texture slot [%d] (or missing name) for material %s", - nSlot, pMaterial->GetName().toStdString().c_str()); - return AZStd::any(); - } - else - { - return AZStd::make_any(pTextureRes->m_Name); - } - } - // ########## Texture Maps / [TexType | Filter | IsProjectedTexGen | TexGenType ] ########## - else if (splittedPropertyPath.size() == 3) - { - SEfResTexture* pTextureRes = shaderResources.GetTextureResource(TryConvertingCStringToEEfResTextures(subCategoryName)); - if (pTextureRes) - { - if (propertyName == "TexType") - { - return AZStd::make_any(TryConvertingETEX_TypeToCString(pTextureRes->m_Sampler.m_eTexType).toLatin1().data()); - } - else if (propertyName == "Filter") - { - return AZStd::make_any(TryConvertingTexFilterToCString(pTextureRes->m_Filter).toLatin1().data()); - } - else if (propertyName == "IsProjectedTexGen") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_bTexGenProjected); - } - else if (propertyName == "TexGenType") - { - return AZStd::make_any(TryConvertingETexGenTypeToCString(pTextureRes->AddModificator()->m_eTGType).toLatin1().data()); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid property.").toUtf8().data()); - } - } - else - { - AZ_Warning("ShadersSystem", false, "PyGetProperty - Error: empty 'subCategoryName' texture slot [%d] for material %s", - aznumeric_cast(TryConvertingCStringToEEfResTextures(subCategoryName)), - pMaterial->GetName().toStdString().c_str()); - } - } - // ########## Texture Maps / [Tiling | Rotator | Oscillator] ########## - else if (splittedPropertyPath.size() == 4) - { - SEfResTexture* pTextureRes = shaderResources.GetTextureResource(TryConvertingCStringToEEfResTextures(subSubCategoryName)); - if (pTextureRes) - { - if (subCategoryName == "Tiling") - { - if (propertyName == "IsTileU") - { - return AZStd::make_any(pTextureRes->m_bUTile); - } - else if (propertyName == "IsTileV") - { - return AZStd::make_any(pTextureRes->m_bVTile); - } - else if (propertyName == "TileU") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_Tiling[0]); - } - else if (propertyName == "TileV") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_Tiling[1]); - } - else if (propertyName == "OffsetU") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_Offs[0]); - } - else if (propertyName == "OffsetV") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_Offs[1]); - } - else if (propertyName == "RotateU") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_Rot[0]); - } - else if (propertyName == "RotateV") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_Rot[1]); - } - else if (propertyName == "RotateW") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_Rot[2]); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid property.").toUtf8().data()); - } - } - else if (subCategoryName == "Rotator") - { - if (propertyName == "Type") - { - return AZStd::make_any(TryConvertingETexModRotateTypeToCString(pTextureRes->AddModificator()->m_eRotType).toLatin1().data()); - } - else if (propertyName == "Rate") - { - return AZStd::make_any(Word2Degr(pTextureRes->AddModificator()->m_RotOscRate[2])); - } - else if (propertyName == "Phase") - { - return AZStd::make_any(Word2Degr(pTextureRes->AddModificator()->m_RotOscPhase[2])); - } - else if (propertyName == "Amplitude") - { - return AZStd::make_any(Word2Degr(pTextureRes->AddModificator()->m_RotOscAmplitude[2])); - } - else if (propertyName == "CenterU") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_RotOscCenter[0]); - } - else if (propertyName == "CenterV") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_RotOscCenter[1]); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid property.").toUtf8().data()); - } - } - else if (subCategoryName == "Oscillator") - { - if (propertyName == "TypeU") - { - return AZStd::make_any(TryConvertingETexModMoveTypeToCString(pTextureRes->AddModificator()->m_eMoveType[0]).toLatin1().data()); - } - else if (propertyName == "TypeV") - { - return AZStd::make_any(TryConvertingETexModMoveTypeToCString(pTextureRes->AddModificator()->m_eMoveType[1]).toLatin1().data()); - } - else if (propertyName == "RateU") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_OscRate[0]); - - } - else if (propertyName == "RateV") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_OscRate[1]); - } - else if (propertyName == "PhaseU") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_OscPhase[0]); - } - else if (propertyName == "PhaseV") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_OscPhase[1]); - } - else if (propertyName == "AmplitudeU") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_OscAmplitude[0]); - } - else if (propertyName == "AmplitudeV") - { - return AZStd::make_any(pTextureRes->AddModificator()->m_OscAmplitude[1]); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid property.").toUtf8().data()); - } - } - else - { - throw std::runtime_error((QString("\"") + subCategoryName + "\" is an invalid sub category.").toUtf8().data()); - } - } - else - { - AZ_Warning("ShadersSystem", false, "PyGetProperty - Error: empty 'subSubCategoryName' texture slot [%d] for material %s", - aznumeric_cast(TryConvertingCStringToEEfResTextures(subSubCategoryName)), - pMaterial->GetName().toStdString().c_str()); - } - } - else - { - throw std::runtime_error(errorMsgInvalidPropertyPath.toUtf8().data()); - } - } - // ########## Shader Params ########## - else if (categoryName == "Shader Params") - { - auto& shaderParams = pMaterial->GetShaderResources().m_ShaderParams; - - for (int i = 0; i < shaderParams.size(); i++) - { - if (propertyName == ParseUINameFromPublicParamsScript(shaderParams[i].m_Script.c_str())) - { - if (shaderParams[i].m_Type == eType_FLOAT) - { - return AZStd::make_any(shaderParams[i].m_Value.m_Float); - } - else if (shaderParams[i].m_Type == eType_FCOLOR) - { - QColor col = ColorLinearToGamma(ColorF( - shaderParams[i].m_Value.m_Vector[0], - shaderParams[i].m_Value.m_Vector[1], - shaderParams[i].m_Value.m_Vector[2])); - return AZStd::make_any(col.red(), col.green(), col.blue(), 1.0f); - } - } - } - - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid shader param.").toUtf8().data()); - } - // ########## Shader Generation Params ########## - else if (categoryName == "Shader Generation Params") - { - for (int i = 0; i < pMaterial->GetShaderGenParamsVars()->GetNumVariables(); i++) - { - if (propertyName == pMaterial->GetShaderGenParamsVars()->GetVariable(i)->GetHumanName()) - { - // get the current Boolean value for this shader variable and return so that the std::runtime_error() will not throw to indicate failure - bool boolValue = false; - pMaterial->GetShaderGenParamsVars()->GetVariable(i)->Get(boolValue); - return AZStd::make_any(boolValue); - } - } - - // not matching property was found, so throw a std::runtime_error() to indcate an error - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid shader generation param.").toUtf8().data()); - } - // ########## Vertex Deformation ########## - else if (categoryName == "Vertex Deformation") - { - // ########## Vertex Deformation / [ Type | Wave Length X | Wave Length Y | Wave Length Z | Wave Length W | Noise Scale ] ########## - if (splittedPropertyPath.size() == 2) - { - if (propertyName == "Type") - { - return AZStd::make_any(TryConvertingEDeformTypeToCString(pMaterial->GetShaderResources().m_DeformInfo.m_eType).toLatin1().data()); - } - else if (propertyName == "Wave Length X") - { - return AZStd::make_any(pMaterial->GetShaderResources().m_DeformInfo.m_fDividerX); - } - else if (propertyName == "Noise Scale") - { - return AZStd::make_any( - pMaterial->GetShaderResources().m_DeformInfo.m_vNoiseScale[0], - pMaterial->GetShaderResources().m_DeformInfo.m_vNoiseScale[1], - pMaterial->GetShaderResources().m_DeformInfo.m_vNoiseScale[2]); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid property.").toUtf8().data()); - } - } - // ########## Vertex Deformation / [ Wave X ] ########## - else if (splittedPropertyPath.size() == 3) - { - if (subCategoryName == "Wave X") - { - SWaveForm2 currentWaveForm; - if (subCategoryName == "Wave X") - { - currentWaveForm = pMaterial->GetShaderResources().m_DeformInfo.m_WaveX; - } - - if (propertyName == "Type") - { - return AZStd::make_any(TryConvertingEWaveFormToCString(currentWaveForm.m_eWFType).toLatin1().data()); - } - else if (propertyName == "Level") - { - return AZStd::make_any(currentWaveForm.m_Level); - } - else if (propertyName == "Amplitude") - { - return AZStd::make_any(currentWaveForm.m_Amp); - } - else if (propertyName == "Phase") - { - return AZStd::make_any(currentWaveForm.m_Phase); - } - else if (propertyName == "Frequency") - { - return AZStd::make_any(currentWaveForm.m_Freq); - } - else - { - throw std::runtime_error((QString("\"") + propertyName + "\" is an invalid property.").toUtf8().data()); - } - } - else - { - throw std::runtime_error((QString("\"") + categoryName + "\" is an invalid category.").toUtf8().data()); - } - } - else - { - throw std::runtime_error(errorMsgInvalidPropertyPath.toUtf8().data()); - } - } - // ########## Layer Presets ########## - else if (categoryName == "Layer Presets") - { - // names are "Shader1", "Shader2" and "Shader3", because all have the name "Shader" in material editor - if (splittedPropertyPath.size() == 2) - { - int shaderNumber = -1; - if (propertyName == "Shader1") - { - shaderNumber = 0; - } - else if (propertyName == "Shader2") - { - shaderNumber = 1; - } - else if (propertyName == "Shader3") - { - shaderNumber = 2; - } - else - { - throw std::runtime_error("Invalid shader."); - } - - return AZStd::make_any(pMaterial->GetMtlLayerResources()[shaderNumber].m_shaderName.toLatin1().data()); - } - else if (splittedPropertyPath.size() == 3) - { - if (propertyName == "No Draw") - { - int shaderNumber = -1; - if (subCategoryName == "Shader1") - { - shaderNumber = 0; - } - else if (subCategoryName == "Shader2") - { - shaderNumber = 1; - } - else if (subCategoryName == "Shader3") - { - shaderNumber = 2; - } - else - { - throw std::runtime_error("Invalid shader."); - } - return AZStd::make_any(pMaterial->GetMtlLayerResources()[shaderNumber].m_nFlags & MTL_LAYER_USAGE_NODRAW); - } - } - } - - throw std::runtime_error(errorMsgInvalidPropertyPath.toUtf8().data()); - return AZStd::any(); - } - - void PySetProperty(const char* pPathAndMaterialName, const char* pPathAndPropertyName, const AZStd::any& value) - { - CMaterial* pMaterial = TryLoadingMaterial(pPathAndMaterialName); - std::deque splittedPropertyPath = PreparePropertyPath(pPathAndPropertyName); - std::deque splittedPropertyPathCategory = splittedPropertyPath; - QString categoryName = splittedPropertyPath.front(); - QString subCategoryName = "None"; - QString subSubCategoryName = "None"; - QString propertyName = splittedPropertyPath.back(); - QString errorMsgInvalidPropertyPath = "Invalid property path."; - - if (!ValidateProperty(pMaterial, splittedPropertyPath, value)) - { - throw std::runtime_error("Invalid property."); - } - - QString undoMsg = "Set Material Property"; - CUndo undo(undoMsg.toUtf8().data()); - pMaterial->RecordUndo(undoMsg.toUtf8().data(), true); - - if (splittedPropertyPathCategory.size() == 3) - { - splittedPropertyPathCategory.pop_back(); - subCategoryName = splittedPropertyPathCategory.back(); - } - else if (splittedPropertyPathCategory.size() == 4) - { - splittedPropertyPathCategory.pop_back(); - subCategoryName = splittedPropertyPathCategory.back(); - splittedPropertyPathCategory.pop_back(); - subSubCategoryName = splittedPropertyPathCategory.back(); - } - - // ########## Material Settings ########## - if (categoryName == "Material Settings") - { - if (propertyName == "Shader") - { - pMaterial->SetShaderName(AZStd::any_cast(value).data()); - } - else if (propertyName == "Surface Type") - { - bool isSurfaceExist(false); - QString realSurfacename = ""; - ISurfaceTypeEnumerator* pSurfaceTypeEnum = gEnv->p3DEngine->GetMaterialManager()->GetSurfaceTypeManager()->GetEnumerator(); - if (pSurfaceTypeEnum) - { - for (ISurfaceType* pSurfaceType = pSurfaceTypeEnum->GetFirst(); pSurfaceType; pSurfaceType = pSurfaceTypeEnum->GetNext()) - { - QString surfaceName = pSurfaceType->GetName(); - realSurfacename = surfaceName; - if (surfaceName.left(4) == "mat_") - { - surfaceName.remove(0, 4); - } - if (surfaceName == AZStd::any_cast(value).data()) - { - isSurfaceExist = true; - pMaterial->SetSurfaceTypeName(realSurfacename); - } - } - - if (!isSurfaceExist) - { - throw std::runtime_error("Invalid surface type name."); - } - } - else - { - throw std::runtime_error("Surface Type Enumerator corrupted."); - } - } - } - // ########## Opacity Settings ########## - else if (categoryName == "Opacity Settings") - { - if (propertyName == "Opacity") - { - pMaterial->GetShaderResources().m_LMaterial.m_Opacity = PyFetchNumericType(value) / 100.0f; - } - else if (propertyName == "AlphaTest") - { - pMaterial->GetShaderResources().m_AlphaRef = PyFetchNumericType(value) / 100.0f; - } - else if (propertyName == "Additive") - { - SetMaterialFlag(pMaterial, MTL_FLAG_ADDITIVE, PyFetchNumericType(value)); - } - } - // ########## Lighting Settings ########## - else if (categoryName == "Lighting Settings") - { - if (propertyName == "Diffuse Color") - { - const AZ::Color* color = AZStd::any_cast(&value); - pMaterial->GetShaderResources().m_LMaterial.m_Diffuse = ColorGammaToLinear(QColor(color->GetR8(), color->GetG8(), color->GetB8())); - } - else if (propertyName == "Specular Color") - { - const AZ::Color* color = AZStd::any_cast(&value); - ColorF colorFloat = ColorGammaToLinear(QColor(color->GetR8(), color->GetG8(), color->GetB8())); - colorFloat.a = pMaterial->GetShaderResources().m_LMaterial.m_Specular.a; - colorFloat.r *= colorFloat.a; - colorFloat.g *= colorFloat.a; - colorFloat.b *= colorFloat.a; - pMaterial->GetShaderResources().m_LMaterial.m_Specular = colorFloat; - } - else if (propertyName == "Glossiness" || propertyName == "Smoothness") - { - pMaterial->GetShaderResources().m_LMaterial.m_Smoothness = PyFetchNumericType(value); - } - else if (propertyName == "Specular Level") - { - const float localVariableAlpha = PyFetchNumericType(value); - ColorF colorFloat = pMaterial->GetShaderResources().m_LMaterial.m_Specular; - colorFloat.r *= localVariableAlpha; - colorFloat.g *= localVariableAlpha; - colorFloat.b *= localVariableAlpha; - colorFloat.a = 1.0f; - pMaterial->GetShaderResources().m_LMaterial.m_Specular = colorFloat; - } - else if (propertyName == "Emissive Color") - { - const AZ::Color* color = AZStd::any_cast(&value); - float emissiveIntensity = pMaterial->GetShaderResources().m_LMaterial.m_Emittance.a; - pMaterial->GetShaderResources().m_LMaterial.m_Emittance = ColorGammaToLinear(QColor(color->GetR8(), color->GetG8(), color->GetB8())); - pMaterial->GetShaderResources().m_LMaterial.m_Emittance.a = emissiveIntensity; - } - else if (propertyName == "Emissive Intensity") - { - pMaterial->GetShaderResources().m_LMaterial.m_Emittance.a = PyFetchNumericType(value); - } - } - // ########## Advanced ########## - else if (categoryName == "Advanced") - { - if (propertyName == "Allow layer activation") - { - pMaterial->SetLayerActivation(PyFetchNumericType(value)); - } - else if (propertyName == "2 Sided") - { - SetMaterialFlag(pMaterial, MTL_FLAG_2SIDED, PyFetchNumericType(value)); - } - else if (propertyName == "No Shadow") - { - SetMaterialFlag(pMaterial, MTL_FLAG_NOSHADOW, PyFetchNumericType(value)); - } - else if (propertyName == "Use Scattering") - { - SetMaterialFlag(pMaterial, MTL_FLAG_SCATTER, PyFetchNumericType(value)); - } - else if (propertyName == "Hide After Breaking") - { - SetMaterialFlag(pMaterial, MTL_FLAG_HIDEONBREAK, PyFetchNumericType(value)); - } - else if (propertyName == "Fog Volume Shading Quality High") - { - SetMaterialFlag(pMaterial, MTL_FLAG_FOG_VOLUME_SHADING_QUALITY_HIGH, PyFetchNumericType(value)); - } - else if (propertyName == "Blend Terrain Color") - { - SetMaterialFlag(pMaterial, MTL_FLAG_BLEND_TERRAIN, PyFetchNumericType(value)); - } - else if (propertyName == "Voxel Coverage") - { - pMaterial->GetShaderResources().m_VoxelCoverage = aznumeric_cast(PyFetchNumericType(value) * 255.0f); - } - else if (propertyName == "Link to Material") - { - pMaterial->GetMatInfo()->SetMaterialLinkName(AZStd::any_cast(value).data()); - } - else if (propertyName == "Propagate Material Settings") - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_MATERIAL_SETTINGS, PyFetchNumericType(value)); - } - else if (propertyName == "Propagate Opacity Settings") - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_OPACITY, PyFetchNumericType(value)); - } - else if (propertyName == "Propagate Lighting Settings") - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_LIGHTING, PyFetchNumericType(value)); - } - else if (propertyName == "Propagate Advanced Settings") - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_ADVANCED, PyFetchNumericType(value)); - } - else if (propertyName == "Propagate Texture Maps") - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_TEXTURES, PyFetchNumericType(value)); - } - else if (propertyName == "Propagate Shader Params") - { - if (PyFetchNumericType(value)) - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_MATERIAL_SETTINGS, true); - } - SetPropagationFlag(pMaterial, MTL_PROPAGATE_SHADER_PARAMS, PyFetchNumericType(value)); - } - else if (propertyName == "Propagate Shader Generation") - { - if (PyFetchNumericType(value)) - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_MATERIAL_SETTINGS, true); - } - SetPropagationFlag(pMaterial, MTL_PROPAGATE_SHADER_GEN, PyFetchNumericType(value)); - } - else if (propertyName == "Propagate Vertex Deformation") - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_VERTEX_DEF, PyFetchNumericType(value)); - } - else if (propertyName == "Propagate Layer Presets") - { - SetPropagationFlag(pMaterial, MTL_PROPAGATE_LAYER_PRESETS, PyFetchNumericType(value)); - } - } - // ########## Texture Maps ########## - else if (categoryName == "Texture Maps") - { - // ########## Texture Maps / [name] ########## - SInputShaderResources& shaderResources = pMaterial->GetShaderResources(); - if (splittedPropertyPath.size() == 2) - { - uint16 nSlot = aznumeric_cast(TryConvertingCStringToEEfResTextures(propertyName)); - auto stringValue = AZStd::any_cast(value); - if (stringValue.empty()) - { - AZ_Warning("ShadersSystem", false, "PySetProperty - Error: empty texture [%d] name for material %s", - nSlot, pMaterial->GetName().toStdString().c_str()); - } - // notice that the following is an insertion operation if the index did not exist in the map - shaderResources.m_TexturesResourcesMap[nSlot].m_Name = stringValue.data(); - } - // ########## Texture Maps / [TexType | Filter | IsProjectedTexGen | TexGenType ] ########## - else if (splittedPropertyPath.size() == 3) - { - uint16 nSlot = aznumeric_cast(TryConvertingCStringToEEfResTextures(subCategoryName)); - // notice that each of the following will add the texture slot if did not exist yet - if (propertyName == "TexType") - { - shaderResources.m_TexturesResourcesMap[nSlot].m_Sampler.m_eTexType = TryConvertingCStringToETEX_Type(AZStd::any_cast(value)); - } - else if (propertyName == "Filter") - { - shaderResources.m_TexturesResourcesMap[nSlot].m_Filter = TryConvertingCStringToTexFilter(AZStd::any_cast(value)); - } - else if (propertyName == "IsProjectedTexGen") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_bTexGenProjected = PyFetchNumericType(value); - } - else if (propertyName == "TexGenType") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_eTGType = TryConvertingCStringToETexGenType(AZStd::any_cast(value)); - } - } - // ########## Texture Maps / [Tiling | Rotator | Oscillator] ########## - else if (splittedPropertyPath.size() == 4) - { - uint16 nSlot = aznumeric_cast(TryConvertingCStringToEEfResTextures(subSubCategoryName)); - if (subCategoryName == "Tiling") - { - if (propertyName == "IsTileU") - { - shaderResources.m_TexturesResourcesMap[nSlot].m_bUTile = PyFetchNumericType(value); - } - else if (propertyName == "IsTileV") - { - shaderResources.m_TexturesResourcesMap[nSlot].m_bVTile = PyFetchNumericType(value); - } - else if (propertyName == "TileU") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_Tiling[0] = PyFetchNumericType(value); - } - else if (propertyName == "TileV") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_Tiling[1] = PyFetchNumericType(value); - } - else if (propertyName == "OffsetU") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_Offs[0] = PyFetchNumericType(value); - } - else if (propertyName == "OffsetV") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_Offs[1] = PyFetchNumericType(value); - } - else if (propertyName == "RotateU") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_Rot[0] = Degr2Word(PyFetchNumericType(value)); - } - else if (propertyName == "RotateV") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_Rot[1] = Degr2Word(PyFetchNumericType(value)); - } - else if (propertyName == "RotateW") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_Rot[2] = Degr2Word(PyFetchNumericType(value)); - } - } - else if (subCategoryName == "Rotator") - { - if (propertyName == "Type") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_eRotType = TryConvertingCStringToETexModRotateType(AZStd::any_cast(value)); - } - else if (propertyName == "Rate") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_RotOscRate[2] = Degr2Word(PyFetchNumericType(value)); - } - else if (propertyName == "Phase") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_RotOscPhase[2] = Degr2Word(PyFetchNumericType(value)); - } - else if (propertyName == "Amplitude") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_RotOscAmplitude[2] = Degr2Word(PyFetchNumericType(value)); - } - else if (propertyName == "CenterU") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_RotOscCenter[0] = PyFetchNumericType(value); - } - else if (propertyName == "CenterV") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_RotOscCenter[1] = PyFetchNumericType(value); - } - } - else if (subCategoryName == "Oscillator") - { - if (propertyName == "TypeU") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_eMoveType[0] = TryConvertingCStringToETexModMoveType(AZStd::any_cast(value)); - } - else if (propertyName == "TypeV") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_eMoveType[1] = TryConvertingCStringToETexModMoveType(AZStd::any_cast(value)); - } - else if (propertyName == "RateU") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_OscRate[0] = PyFetchNumericType(value); - } - else if (propertyName == "RateV") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_OscRate[1] = PyFetchNumericType(value); - } - else if (propertyName == "PhaseU") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_OscPhase[0] = PyFetchNumericType(value); - } - else if (propertyName == "PhaseV") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_OscPhase[1] = PyFetchNumericType(value); - } - else if (propertyName == "AmplitudeU") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_OscAmplitude[0] = PyFetchNumericType(value); - } - else if (propertyName == "AmplitudeV") - { - shaderResources.m_TexturesResourcesMap[nSlot].AddModificator()->m_OscAmplitude[1] = PyFetchNumericType(value); - } - } - } - } - // ########## Shader Params ########## - else if (categoryName == "Shader Params") - { - auto& shaderParams = pMaterial->GetShaderResources().m_ShaderParams; - - for (int i = 0; i < shaderParams.size(); i++) - { - if (propertyName == ParseUINameFromPublicParamsScript(shaderParams[i].m_Script.c_str())) - { - if (shaderParams[i].m_Type == eType_FLOAT) - { - shaderParams[i].m_Value.m_Float = PyFetchNumericType(value); - break; - } - else if (shaderParams[i].m_Type == eType_FCOLOR) - { - const AZ::Color* color = AZStd::any_cast(&value); - ColorF colorLinear = ColorGammaToLinear(QColor(color->GetR8(), color->GetG8(), color->GetB8())); - shaderParams[i].m_Value.m_Vector[0] = colorLinear.r; - shaderParams[i].m_Value.m_Vector[1] = colorLinear.g; - shaderParams[i].m_Value.m_Vector[2] = colorLinear.b; - break; - } - else - { - throw std::runtime_error("Invalid data type (Shader Params)"); - } - } - } - } - // ########## Shader Generation Params ########## - else if (categoryName == "Shader Generation Params") - { - for (int i = 0; i < pMaterial->GetShaderGenParamsVars()->GetNumVariables(); i++) - { - if (propertyName == pMaterial->GetShaderGenParamsVars()->GetVariable(i)->GetHumanName()) - { - CVarBlock* shaderGenBlock = pMaterial->GetShaderGenParamsVars(); - shaderGenBlock->GetVariable(i)->Set(PyFetchNumericType(value)); - pMaterial->SetShaderGenParamsVars(shaderGenBlock); - break; - } - } - } - // ########## Vertex Deformation ########## - else if (categoryName == "Vertex Deformation") - { - // ########## Vertex Deformation / [ Type | Wave Length X | Noise Scale ] ########## - if (splittedPropertyPath.size() == 2) - { - if (propertyName == "Type") - { - pMaterial->GetShaderResources().m_DeformInfo.m_eType = TryConvertingCStringToEDeformType(AZStd::any_cast(value)); - } - else if (propertyName == "Wave Length X") - { - pMaterial->GetShaderResources().m_DeformInfo.m_fDividerX = PyFetchNumericType(value); - } - else if (propertyName == "Noise Scale") - { - const AZ::Vector3* vecValue = AZStd::any_cast(&value); - pMaterial->GetShaderResources().m_DeformInfo.m_vNoiseScale[0] = vecValue->GetX(); - pMaterial->GetShaderResources().m_DeformInfo.m_vNoiseScale[1] = vecValue->GetY(); - pMaterial->GetShaderResources().m_DeformInfo.m_vNoiseScale[2] = vecValue->GetZ(); - } - } - // ########## Vertex Deformation / [ Wave X ] ########## - else if (splittedPropertyPath.size() == 3) - { - if (subCategoryName == "Wave X") - { - SWaveForm2& currentWaveForm = pMaterial->GetShaderResources().m_DeformInfo.m_WaveX; - - if (propertyName == "Type") - { - currentWaveForm.m_eWFType = TryConvertingCStringToEWaveForm(AZStd::any_cast(value)); - } - else if (propertyName == "Level") - { - currentWaveForm.m_Level = PyFetchNumericType(value); - } - else if (propertyName == "Amplitude") - { - currentWaveForm.m_Amp = PyFetchNumericType(value); - } - else if (propertyName == "Phase") - { - currentWaveForm.m_Phase = PyFetchNumericType(value); - } - else if (propertyName == "Frequency") - { - currentWaveForm.m_Freq = PyFetchNumericType(value); - } - } - } - } - // ########## Layer Presets ########## - else if (categoryName == "Layer Presets") - { - // names are "Shader1", "Shader2" and "Shader3", because all have the name "Shader" in material editor - if (splittedPropertyPath.size() == 2) - { - int shaderNumber = -1; - if (propertyName == "Shader1") - { - shaderNumber = 0; - } - else if (propertyName == "Shader2") - { - shaderNumber = 1; - } - else if (propertyName == "Shader3") - { - shaderNumber = 2; - } - - pMaterial->GetMtlLayerResources()[shaderNumber].m_shaderName = AZStd::any_cast(value).data(); - } - else if (splittedPropertyPath.size() == 3) - { - if (propertyName == "No Draw") - { - int shaderNumber = -1; - if (subCategoryName == "Shader1") - { - shaderNumber = 0; - } - else if (subCategoryName == "Shader2") - { - shaderNumber = 1; - } - else if (subCategoryName == "Shader3") - { - shaderNumber = 2; - } - - if (pMaterial->GetMtlLayerResources()[shaderNumber].m_nFlags & MTL_LAYER_USAGE_NODRAW && PyFetchNumericType(value) == false) - { - pMaterial->GetMtlLayerResources()[shaderNumber].m_nFlags = pMaterial->GetMtlLayerResources()[shaderNumber].m_nFlags - MTL_LAYER_USAGE_NODRAW; - } - else if (!(pMaterial->GetMtlLayerResources()[shaderNumber].m_nFlags & MTL_LAYER_USAGE_NODRAW) && PyFetchNumericType(value) == true) - { - pMaterial->GetMtlLayerResources()[shaderNumber].m_nFlags = pMaterial->GetMtlLayerResources()[shaderNumber].m_nFlags | MTL_LAYER_USAGE_NODRAW; - } - } - } - } - - pMaterial->Update(); - pMaterial->Save(); - GetIEditor()->GetMaterialManager()->OnUpdateProperties(pMaterial, true); - } -} - -namespace AzToolsFramework -{ - void MaterialPythonFuncsHandler::Reflect(AZ::ReflectContext* context) - { - if (auto behaviorContext = azrtti_cast(context)) - { - // this will put these methods into the 'azlmbr.legacy.material' module - auto addLegacyMaterial = [](AZ::BehaviorContext::GlobalMethodBuilder methodBuilder) - { - methodBuilder->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) - ->Attribute(AZ::Script::Attributes::Category, "Legacy/Material") - ->Attribute(AZ::Script::Attributes::Module, "legacy.material"); - }; - addLegacyMaterial(behaviorContext->Method("create", PyMaterialCreate, nullptr, "Creates a material.")); - addLegacyMaterial(behaviorContext->Method("create_multi", PyMaterialCreateMulti, nullptr, "Creates a multi-material.")); - addLegacyMaterial(behaviorContext->Method("convert_to_multi", PyMaterialConvertToMulti, nullptr, "Converts the selected material to a multi-material.")); - addLegacyMaterial(behaviorContext->Method("duplicate_current", PyMaterialDuplicateCurrent, nullptr, "Duplicates the current material.")); - addLegacyMaterial(behaviorContext->Method("merge_selection", PyMaterialMergeSelection, nullptr, "Merges the selected materials.")); - addLegacyMaterial(behaviorContext->Method("delete_current", PyMaterialDeleteCurrent, nullptr, "Deletes the current material.")); - addLegacyMaterial(behaviorContext->Method("get_submaterial", PyGetSubMaterial, nullptr, "Gets sub materials of a material.")); - addLegacyMaterial(behaviorContext->Method("get_property", PyGetProperty, nullptr, "Gets a property of a material.")); - addLegacyMaterial(behaviorContext->Method("set_property", PySetProperty, nullptr, "Sets a property of a material.")); - } - } -} diff --git a/Code/Sandbox/Editor/Material/MaterialPythonFuncs.h b/Code/Sandbox/Editor/Material/MaterialPythonFuncs.h deleted file mode 100644 index f04542f466..0000000000 --- a/Code/Sandbox/Editor/Material/MaterialPythonFuncs.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 - -namespace AzToolsFramework -{ - //! A component to reflect scriptable commands for materials in the Editor - class MaterialPythonFuncsHandler - : public AZ::Component - { - public: - AZ_COMPONENT(MaterialPythonFuncsHandler, "{E437BCF2-DE71-43E1-A7EC-DD243EB41F0B}") - - SANDBOX_API static void Reflect(AZ::ReflectContext* context); - - // AZ::Component ... - void Activate() override {} - void Deactivate() override {} - }; - -} // namespace AzToolsFramework diff --git a/Code/Sandbox/Editor/Material/PreviewModelView.cpp b/Code/Sandbox/Editor/Material/PreviewModelView.cpp deleted file mode 100644 index 41a50436d1..0000000000 --- a/Code/Sandbox/Editor/Material/PreviewModelView.cpp +++ /dev/null @@ -1,416 +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" - -//AZCore -#include - -//CRY -#include -#include - -//Editor -#include -#include -#include -#include -#include -#include -#include -#include - -//EditorCommon -#include - -//Local -#include "PreviewModelView.h" - -//QT -#include - - - -CPreviewModelView::CPreviewModelView(QWidget* parent) - : QViewport(parent, QViewport::StartupMode_Manual) // Manual since we need to set WA_DontCreateNativeAncestors before QViewport::Startup() creates the internal native window and propagates - , m_Flags(0) - , m_GridColor(150, 150, 150, 40) - , m_BackgroundColor(0.5f, 0.5f, 0.5f) - , m_TimeScale(1.0f) - , m_PlayState(PlayState::NONE) - , m_pStaticModel(nullptr) - , m_PostUpdateCallback(nullptr) - , m_ContextMenuCallback(nullptr) -{ -#ifdef Q_OS_MACOS - // Don't propagate the nativeness up, as dockwidgets on macOS don't like it - setAttribute(Qt::WA_DontCreateNativeAncestors); -#endif - Startup(); - - ////////////////////////////////////////////////////////// - //QViewport - AddConsumer(this); - ////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////// - //IEditorNotifyListener - GetIEditor()->RegisterNotifyListener(this); - ////////////////////////////////////////////////////////// - - FocusOnScreen();//update the camera ... - SetDefaultFlags(); - UpdateSettings(); -} - -CPreviewModelView::~CPreviewModelView() -{ - CRY_ASSERT(GetIEditor()); - - ////////////////////////////////////////////////////////// - //IEditorNotifyListener - GetIEditor()->UnregisterNotifyListener(this); - ////////////////////////////////////////////////////////// - - ReleaseModel(); -} - - -bool CPreviewModelView::IsFlagSet(PreviewModelViewFlag flag) const -{ - CRY_ASSERT(flag < PreviewModelViewFlag::END_POSSIBLE_ITEMS); - return (m_Flags & (1 << static_cast(flag))); -} - -void CPreviewModelView::ToggleFlag(PreviewModelViewFlag flag) -{ - CRY_ASSERT(flag < PreviewModelViewFlag::END_POSSIBLE_ITEMS); - if (IsFlagSet(flag)) - { - UnSetFlag(flag); - } - else - { - SetFlag(flag); - } -} - -void CPreviewModelView::SetFlag(PreviewModelViewFlag flag) -{ - CRY_ASSERT(flag < PreviewModelViewFlag::END_POSSIBLE_ITEMS); - m_Flags |= (1 << static_cast(flag)); -} - -void CPreviewModelView::UnSetFlag(PreviewModelViewFlag flag) -{ - CRY_ASSERT(flag < PreviewModelViewFlag::END_POSSIBLE_ITEMS); - m_Flags &= ~(1 << static_cast(flag)); -} - -void CPreviewModelView::ResetPlaybackControls() -{ - UnSetFlag(CPreviewModelView::PreviewModelViewFlag::LOOPING_PLAY); - m_TimeScale = 1.0f; -} - -void CPreviewModelView::ResetBackgroundColor() -{ - SetBackgroundColor(ColorF(0.5f, 0.5f, 0.5f)); -} - -void CPreviewModelView::ResetGridColor() -{ - SetGridColor(ColorF(150, 150, 150, 40)); -} - -void CPreviewModelView::ResetCamera() -{ - FocusOnScreen(); -} - -void CPreviewModelView::ResetAll() -{ - ResetPlaybackControls(); - ResetGridColor(); - ResetBackgroundColor(); - ReleaseModel(); - SetDefaultFlags(); -} - -void CPreviewModelView::SetGridColor(ColorF color) -{ - m_GridColor = color; -} - -void CPreviewModelView::SetBackgroundColor(ColorF color) -{ - m_BackgroundColor = color; -} - -void CPreviewModelView::SetPlayState(PlayState state) -{ - m_PlayState = state; -} - -void CPreviewModelView::SetTimeScale(float scale) -{ - m_TimeScale = scale; -} - -CPreviewModelView::PlayState CPreviewModelView::GetPlayState() const -{ - return m_PlayState; -} - -float CPreviewModelView::GetTimeScale() const -{ - return m_TimeScale; -} - - -ColorF CPreviewModelView::GetGridColor() const -{ - return m_GridColor; -} - -ColorF CPreviewModelView::GetBackgroundColor() const -{ - return m_BackgroundColor; -} - -void CPreviewModelView::ImportModel() -{ - SResourceSelectorContext x; - x.typeName = Prop::GetPropertyTypeToResourceType(ePropertyModel); - - QString currPath = m_ModelFilename.toLower(); - QString selected = GetIEditor()->GetResourceSelectorHost()->SelectResource(x, currPath); - LoadModelFile(selected); -} - -void CPreviewModelView::SetPostUpdateCallback(PostUpdateCallback callback) -{ - m_PostUpdateCallback = callback; -} - -void CPreviewModelView::SetContextMenuCallback(ContextMenuCallback callback) -{ - m_ContextMenuCallback = callback; -} - -//////////////////////////////////////////////////////// -//QViewportConsumer -void CPreviewModelView::OnViewportRender(const SRenderContext& rc) -{ - ///UPDATE - UpdateSettings();//Some changes may take effect next frame ... - - //External updating ... - if (m_PostUpdateCallback) - { - m_PostUpdateCallback(); - } - - //RENDER - CRY_ASSERT(rc.renderParams); - CRY_ASSERT(rc.passInfo); - RenderModels(*rc.renderParams, *rc.passInfo); -} - -void CPreviewModelView::OnViewportKey([[maybe_unused]] const SKeyEvent& ev) -{ -} - -void CPreviewModelView::OnViewportMouse([[maybe_unused]] const SMouseEvent& ev) -{ -} -//////////////////////////////////////////////////////// - -//////////////////////////////////////////////////////// -//IEditorNotifyListener -void CPreviewModelView::OnEditorNotifyEvent(EEditorNotifyEvent event) -{ - switch (event) - { - case eNotify_OnCloseScene: - { - ResetAll(); - break; - } - case eNotify_OnIdleUpdate: - { - Update(); - } - break; - default: - break; - } -} -/////////////////////////////////////////////////////// - - -void CPreviewModelView::UpdateSettings() -{ - //Update the settings - SViewportSettings allsettings; - - allsettings.background.topColor = m_BackgroundColor; - allsettings.background.useGradient = false; - - allsettings.grid.showGrid = IsFlagSet(PreviewModelViewFlag::SHOW_GRID); - allsettings.grid.middleColor = m_BackgroundColor; - allsettings.grid.mainColor = m_GridColor; - - allsettings.rendering.wireframe = IsFlagSet(PreviewModelViewFlag::DRAW_WIREFRAME); - allsettings.rendering.sunlight = IsFlagSet(PreviewModelViewFlag::ENABLE_TIME_OF_DAY); - allsettings.rendering.fps = false; - - - // Set zoom speed to 1.0f for better UI workflow, instead of the default 0.1f - allsettings.camera.zoomSpeed = 1.0f; - allsettings.camera.moveSpeed = GetIEditor()->GetEditorSettings()->cameraMoveSpeed; - allsettings.camera.fastMoveMultiplier = GetIEditor()->GetEditorSettings()->cameraFastMoveSpeed; - allsettings.camera.rotationSpeed = GetIEditor()->GetEditorSettings()->cameraRotateSpeed; - allsettings.camera.showViewportOrientation = IsFlagSet(PreviewModelViewFlag::SHOW_GRID_AXIS); - - //Set them ... - SetSettings(allsettings); -} - - - -void CPreviewModelView::RenderModels(SRendParams& rendParams, SRenderingPassInfo& passInfo) -{ - if (m_pStaticModel) - { - if (IsFlagSet(PreviewModelViewFlag::PRECACHE_MATERIAL)) - { - _smart_ptr pCurMat = m_pStaticModel->GetMaterial(); - if (pCurMat) - { - pCurMat->PrecacheMaterial(0.0f, nullptr, true, true); - } - } - m_pStaticModel->Render(rendParams, passInfo); - } -} - -void CPreviewModelView::ReleaseModel() -{ - m_ModelFilename = ""; - SAFE_RELEASE(m_pStaticModel); -} - -void CPreviewModelView::SetDefaultFlags() -{ - UnSetFlag(PreviewModelViewFlag::SHOW_OVERDRAW); - - m_Flags = 0; - - SetFlag(PreviewModelViewFlag::SHOW_GRID); - SetFlag(PreviewModelViewFlag::SHOW_GRID_AXIS); -} - -void CPreviewModelView::LoadModelFile(const QString& modelFile) -{ - //Something to load - if (!modelFile.isEmpty()) - { - //Make sure we are not loading the same thing ... - if (m_ModelFilename != modelFile) - { - ReleaseModel();//release any old mesh - - QString strFileExt = Path::GetExt(modelFile); - bool isCGF = (QString::compare(strFileExt, CRY_GEOMETRY_FILE_EXT, Qt::CaseInsensitive) == 0); - - // NOTE: have to create a local buffer and evaluate the full message here due to calling into another address space to evaluate va_args - // this prevents passing of random data to the log system ... any plugin that does not do it this way is rolling the dice each time. - char buffer[2046]; - CRY_ASSERT(GetIEditor()); - if (isCGF) - { - CRY_ASSERT(GetIEditor()->Get3DEngine()); - // Load object. - m_pStaticModel = GetIEditor()->Get3DEngine()->LoadStatObjUnsafeManualRef(modelFile.toUtf8().data(), nullptr, nullptr, false); - if (m_pStaticModel) - { - m_pStaticModel->AddRef(); - } - else - { - CRY_ASSERT(GetIEditor()->GetLogFile()); - azsprintf(buffer, "Loading of geometry object %s failed.", modelFile.toUtf8().data()); - GetIEditor()->GetLogFile()->Warning(buffer); - } - } - else - { - CRY_ASSERT(GetIEditor()->GetLogFile()); - azsprintf(buffer, "Unknown model file (%s) attempting to be loaded.", modelFile.toUtf8().data()); - GetIEditor()->GetLogFile()->Warning(buffer); - } - - //if something was loaded then we store off the model path for the future - if (m_pStaticModel) - { - m_ModelFilename = modelFile; - } - } - } -} - -IStatObj* CPreviewModelView::GetStaticModel() -{ - return m_pStaticModel; -} - -void CPreviewModelView::FocusOnScreen() -{ - CCamera* camera = Camera(); - if (camera) - { - AABB accumulated(2); - - if (m_pStaticModel) - { - AABB temp; - temp.min = m_pStaticModel->GetBoxMin(); - temp.max = m_pStaticModel->GetBoxMax(); - accumulated.Add(temp); - } - - Vec3 fromDir(1.0f, 1.0f, -0.5f); - Vec3 target = accumulated.GetCenter(); - float bbRadius = accumulated.GetRadius(); - - Vec3 dir = fromDir.GetNormalized(); - Matrix34 tm = Matrix33::CreateRotationVDir(dir, 0); - tm.SetTranslation(target - dir * bbRadius); - CameraMoved(QuatT(tm), true); - } -} - -float CPreviewModelView::GetSpeedScale() const -{ - CRY_ASSERT(GetIEditor()); - CRY_ASSERT(GetIEditor()->GetSystem()); - CRY_ASSERT(GetIEditor()->GetSystem()->GetITimer()); - //Taken from CRenderViewport to mirror controls from there ... - float speedScale = 60.0f * GetIEditor()->GetSystem()->GetITimer()->GetFrameTime(); - if (speedScale > 20.0f) - { - speedScale = 20.0f; - } - return speedScale; -} - diff --git a/Code/Sandbox/Editor/Material/PreviewModelView.h b/Code/Sandbox/Editor/Material/PreviewModelView.h deleted file mode 100644 index 3d27983be1..0000000000 --- a/Code/Sandbox/Editor/Material/PreviewModelView.h +++ /dev/null @@ -1,173 +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 - -//Editor -#if !defined(Q_MOC_RUN) -#include "IEditor.h" -#include "../EditorCommon/QViewport.h" -#include "../EditorCommon/QViewportConsumer.h" - -#endif - -struct IStatObj; -struct SRenderingPassInfo; -struct SRendParams; -class CParticleItem; -class CAxisHelper; -struct HitContext; -struct IGizmoMouseDragHandler; -struct SLodInfo; - -namespace RotationDrawHelper -{ - class Axis; -} - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -class CPreviewModelView - : public QViewport - , public QViewportConsumer - , public IEditorNotifyListener -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING -public: - enum class PlayState - { - NONE, - PLAY, - PAUSE, - STEP, - RESET - }; - enum class SplineMode - { - NONE, - LINE, - SINEWAVE, - COIL - }; - - //NOTE: these need to be limited to 32 as these are being used for bit wise operations. - enum class PreviewModelViewFlag - { - DRAW_WIREFRAME = 0, - - SHOW_BOUNDINGBOX, - SHOW_GIZMO, - SHOW_GRID, - SHOW_GRID_AXIS, - SHOW_EMITTER_SHAPE, - SHOW_OVERDRAW, - SHOW_FIRST_CONTAINER, - - LOOPING_PLAY, - - //Spline - SPLINE_LOOPING, - SPLINE_PINGPONG, - - PRECACHE_MATERIAL, - - ENABLE_TIME_OF_DAY, - - END_POSSIBLE_ITEMS = 32, - }; - - explicit CPreviewModelView(QWidget* parent); - virtual ~CPreviewModelView(); - - //Flags - bool IsFlagSet(PreviewModelViewFlag flag) const; - void ToggleFlag(PreviewModelViewFlag flag); - virtual void SetFlag(PreviewModelViewFlag flag); - virtual void UnSetFlag(PreviewModelViewFlag flag); - - //Resets - void ResetPlaybackControls(); - void ResetBackgroundColor(); - void ResetGridColor(); - virtual void ResetCamera(); - virtual void ResetAll(); - - void SetGridColor(ColorF color); - void SetBackgroundColor(ColorF color); - void SetPlayState(PlayState state); - void SetTimeScale(float scale); - - PlayState GetPlayState() const; - float GetTimeScale() const; - ColorF GetGridColor() const; - ColorF GetBackgroundColor() const; - - void ImportModel(); - - void LoadModelFile(const QString& modelFile); - IStatObj* GetStaticModel(); - - typedef std::function PostUpdateCallback; - void SetPostUpdateCallback(PostUpdateCallback callback); - - typedef std::function ContextMenuCallback; - void SetContextMenuCallback(ContextMenuCallback callback); - - //////////////////////////////////////////////////////// - //QViewportConsumer - virtual void OnViewportRender(const SRenderContext& rc) override; - virtual void OnViewportKey(const SKeyEvent& ev) override; - virtual void OnViewportMouse(const SMouseEvent& ev) override; - //////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////// - //IEditorNotifyListener - virtual void OnEditorNotifyEvent(EEditorNotifyEvent event) override; - //////////////////////////////////////////////////////// - -private: - - //Update - void UpdateSettings(); -protected: -private: - //Render - void RenderModels(SRendParams& rendParams, SRenderingPassInfo& passInfo); - - //Misc - void ReleaseModel(); - void SetDefaultFlags(); -protected: - void FocusOnScreen(); -private: - float GetSpeedScale() const; - -private: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - ColorF m_GridColor; - ColorF m_BackgroundColor; - - QString m_ModelFilename; - - - IStatObj* m_pStaticModel; - -protected: - PostUpdateCallback m_PostUpdateCallback; - ContextMenuCallback m_ContextMenuCallback; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - -protected: - PlayState m_PlayState; - float m_TimeScale; -private: - unsigned int m_Flags; -}; diff --git a/Code/Sandbox/Editor/Material/images/filestatus_00.png b/Code/Sandbox/Editor/Material/images/filestatus_00.png deleted file mode 100644 index 414609f486..0000000000 --- a/Code/Sandbox/Editor/Material/images/filestatus_00.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3e5d226d043630028a1fe88af240b627a08966066b605294cc79ff8273588166 -size 194 diff --git a/Code/Sandbox/Editor/Material/images/filestatus_01.png b/Code/Sandbox/Editor/Material/images/filestatus_01.png deleted file mode 100644 index d644fcfe12..0000000000 --- a/Code/Sandbox/Editor/Material/images/filestatus_01.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f80544a0537398979dd423ffdc8e99c08e47dbe814cd4225646761cbe281eecc -size 206 diff --git a/Code/Sandbox/Editor/Material/images/filestatus_02.png b/Code/Sandbox/Editor/Material/images/filestatus_02.png deleted file mode 100644 index da155a1d2a..0000000000 --- a/Code/Sandbox/Editor/Material/images/filestatus_02.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bee8a3d1d5571e5afe0bd02edf0fc58d8297f96494a7c074fd2a37ecda7ae4dc -size 208 diff --git a/Code/Sandbox/Editor/Material/images/filestatus_03.png b/Code/Sandbox/Editor/Material/images/filestatus_03.png deleted file mode 100644 index a047cb4599..0000000000 --- a/Code/Sandbox/Editor/Material/images/filestatus_03.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d3d0fc234e3154c06abd4e3b8d3d7e52a75f80d527b1d05541f55221cba199d7 -size 183 diff --git a/Code/Sandbox/Editor/Material/images/filestatus_04.png b/Code/Sandbox/Editor/Material/images/filestatus_04.png deleted file mode 100644 index 519b68d500..0000000000 --- a/Code/Sandbox/Editor/Material/images/filestatus_04.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ffb3586ef4309d8bfa93a581c38fe970e8b0411f170955921054522b0bf52bd3 -size 182 diff --git a/Code/Sandbox/Editor/Material/images/filestatus_05.png b/Code/Sandbox/Editor/Material/images/filestatus_05.png deleted file mode 100644 index f4f548cdc9..0000000000 --- a/Code/Sandbox/Editor/Material/images/filestatus_05.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f258e9617a1d4c7be16fcab12533a4f0bfe4072151f2140ca41364ef1a3cea62 -size 196 diff --git a/Code/Sandbox/Editor/Material/images/filestatus_06.png b/Code/Sandbox/Editor/Material/images/filestatus_06.png deleted file mode 100644 index 7b7412b19d..0000000000 --- a/Code/Sandbox/Editor/Material/images/filestatus_06.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:68c609d7bde1796f281690148c19694afddcc2cf4ea306116b546327cb50aad2 -size 249 diff --git a/Code/Sandbox/Editor/Material/images/material_00.png b/Code/Sandbox/Editor/Material/images/material_00.png deleted file mode 100644 index a7f48148f1..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_00.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bd5106eebb6cf264fdac5f3568977fc8f944df4a4d4de6b0e9f35b3a001a3001 -size 206 diff --git a/Code/Sandbox/Editor/Material/images/material_01.png b/Code/Sandbox/Editor/Material/images/material_01.png deleted file mode 100644 index e6c26f748a..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_01.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2b08a8d94c64aed944901b76afcb921c3df2c122c9eac6d52140552c2eb4e5cc -size 227 diff --git a/Code/Sandbox/Editor/Material/images/material_02.png b/Code/Sandbox/Editor/Material/images/material_02.png deleted file mode 100644 index a116e84295..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_02.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:623a937f09f1de3ebb889d7ac9e042f91bf67bef34695801b3603f4517166c8e -size 223 diff --git a/Code/Sandbox/Editor/Material/images/material_03.png b/Code/Sandbox/Editor/Material/images/material_03.png deleted file mode 100644 index a116e84295..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_03.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:623a937f09f1de3ebb889d7ac9e042f91bf67bef34695801b3603f4517166c8e -size 223 diff --git a/Code/Sandbox/Editor/Material/images/material_04.png b/Code/Sandbox/Editor/Material/images/material_04.png deleted file mode 100644 index 1d83e3526a..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_04.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0ad56ab7be0a5a40b644045ac01c90fed6e70433a693e80c5b4b88d63801d75f -size 14604 diff --git a/Code/Sandbox/Editor/Material/images/material_05.png b/Code/Sandbox/Editor/Material/images/material_05.png deleted file mode 100644 index 8d953a6ae4..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_05.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9cc845c4eb0ed6fb772064d73f1c679e3b28288411a02f0cafaf248b83b44ca2 -size 221 diff --git a/Code/Sandbox/Editor/Material/images/material_06.png b/Code/Sandbox/Editor/Material/images/material_06.png deleted file mode 100644 index 7e5159a2fc..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_06.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:966fd5ef5c1e0fe6e920511952d7aea98ad0f165f9ce0197f000f9f48ccd338b -size 14628 diff --git a/Code/Sandbox/Editor/Material/images/material_07.png b/Code/Sandbox/Editor/Material/images/material_07.png deleted file mode 100644 index 7e5159a2fc..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_07.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:966fd5ef5c1e0fe6e920511952d7aea98ad0f165f9ce0197f000f9f48ccd338b -size 14628 diff --git a/Code/Sandbox/Editor/Material/images/material_browser_00.png b/Code/Sandbox/Editor/Material/images/material_browser_00.png deleted file mode 100644 index f1e7a2ffce..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_browser_00.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c4a8dc85c9928faacd184148aaf0f17ef7b68c185b04b0b5f16e942fb11c528e -size 209 diff --git a/Code/Sandbox/Editor/Material/images/material_browser_01.png b/Code/Sandbox/Editor/Material/images/material_browser_01.png deleted file mode 100644 index 1ff2ea213f..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_browser_01.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d9047378404e0893b79bafaad9e6b312d467033daab2191a8c8839e4ff494bd8 -size 321 diff --git a/Code/Sandbox/Editor/Material/images/material_browser_02.png b/Code/Sandbox/Editor/Material/images/material_browser_02.png deleted file mode 100644 index edd5148133..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_browser_02.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2e79122edef52c3f9a31fd662f9f5cfd08b06e44e861c7379d8869635fd1d245 -size 168 diff --git a/Code/Sandbox/Editor/Material/images/material_browser_03.png b/Code/Sandbox/Editor/Material/images/material_browser_03.png deleted file mode 100644 index bfbcc6ce98..0000000000 --- a/Code/Sandbox/Editor/Material/images/material_browser_03.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8cc16bbb4c4c0c1bea14c94d0609f4b11a7cd0ead4af3d236d329a404e8223a8 -size 200 diff --git a/Code/Sandbox/Editor/MaterialSender.cpp b/Code/Sandbox/Editor/MaterialSender.cpp deleted file mode 100644 index 2123eadb31..0000000000 --- a/Code/Sandbox/Editor/MaterialSender.cpp +++ /dev/null @@ -1,60 +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 "MaterialSender.h" - -bool CMaterialSender::SendMessage(int msg, const XmlNodeRef& node) -{ - bool bRet = false; - -#if defined(AZ_PLATFORM_WINDOWS) - if (!CheckWindows()) - { - return false; - } - - m_h.msg = msg; - - int nDataSize = sizeof(SMaterialMapFileHeader) + strlen(node->getXML().c_str()) + 1; - - //hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, nDataSize, "EditMatMappingObject"); - - HANDLE mapFileHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, "EditMatMappingObject"); - if (mapFileHandle) - { - void* pMes = MapViewOfFile(mapFileHandle, FILE_MAP_ALL_ACCESS, 0, 0, nDataSize); - if (pMes) - { - memcpy(pMes, &m_h, sizeof(SMaterialMapFileHeader)); - azstrcpy(((char*)pMes) + sizeof(SMaterialMapFileHeader), nDataSize - sizeof(SMaterialMapFileHeader), node->getXML().c_str()); - UnmapViewOfFile(pMes); - if (m_bIsMatEditor) - { - ::SendMessage(m_h.GetMaxHWND(), WM_MATEDITSEND, msg, 0); - } - else - { - ::SendMessage(m_h.GetEditorHWND(), WM_MATEDITSEND, msg, 0); - } - bRet = true; - } - CloseHandle(mapFileHandle); - } - else - { - CryLog("No File Map"); - } -#endif - - return bRet; -} diff --git a/Code/Sandbox/Editor/MaterialSender.h b/Code/Sandbox/Editor/MaterialSender.h deleted file mode 100644 index 0123223821..0000000000 --- a/Code/Sandbox/Editor/MaterialSender.h +++ /dev/null @@ -1,175 +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_MATERIALSENDER_H -#define CRYINCLUDE_EDITOR_MATERIALSENDER_H -#pragma once - -#ifndef WM_MATEDITSEND -// Value copied from Code/Tools/MaxCryExport/CryShader/MaterialSender.h -# define WM_MATEDITSEND (WM_USER + 315) -#endif - -enum EMaterialSenderMessage -{ - eMSM_Create = 1, - eMSM_GetSelectedMaterial = 2, - eMSM_Init = 3, -}; - -#if defined(AZ_PLATFORM_WINDOWS) -struct SMaterialMapFileHeader -{ - // max - void SetMaxHWND(HWND hWnd) - { - hwndMax = (int64)hWnd; - } - HWND GetMaxHWND() const - { - return (HWND)hwndMax; - } - // editor - void SetEditorHWND(HWND hWnd) - { - hwndMatEdit = (int64)hWnd; - } - HWND GetEditorHWND() const - { - return (HWND)hwndMatEdit; - } - int64 msg;// 64bits for both 32 and 64 - int64 Reserved;// 64bits for both 32 and 64 -protected: - uint64 hwndMax;// HWND for 32 and 64 is different - uint64 hwndMatEdit;// HWND for 32 and 64 is different -}; -#endif // AZ_PLATFORM_WINDOWS - - -class CMaterialSender -{ -public: - - CMaterialSender(bool bIsMatEditor) - : m_bIsMatEditor(bIsMatEditor) - { -#if defined(AZ_PLATFORM_WINDOWS) - m_h.SetEditorHWND(0); - m_h.SetMaxHWND(0); - m_h.msg = 0; - hMapFile = 0; -#endif - } - - ~CMaterialSender() - { -#if defined(AZ_PLATFORM_WINDOWS) - if (hMapFile) - { - CloseHandle(hMapFile); - } - hMapFile = 0; -#endif - } - - bool GetMessage() - { - LoadMapFile(); - return true; - } - - bool CheckWindows() - { -#if defined(AZ_PLATFORM_WINDOWS) - if (!m_h.GetMaxHWND() || !m_h.GetEditorHWND() || !::IsWindow(m_h.GetMaxHWND()) || !::IsWindow(m_h.GetEditorHWND())) - { - LoadMapFile(); - } - if (!m_h.GetMaxHWND() || !m_h.GetEditorHWND() || !::IsWindow(m_h.GetMaxHWND()) || !::IsWindow(m_h.GetEditorHWND())) - { - return false; - } -#endif - return true; - } - - bool Create() - { -#if defined(AZ_PLATFORM_WINDOWS) - hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, 1024 * 1024, "EditMatMappingObject"); - if (hMapFile) - { - return true; - } - CryLog("Can't create File Map"); - - return false; -#else - return true; -#endif - } - - bool SendMessage(int msg, const XmlNodeRef& node); - - void SetupWindows(QWidget* hwndMax, QWidget* hwndMatEdit) - { -#if defined(AZ_PLATFORM_WINDOWS) - m_h.SetMaxHWND(reinterpret_cast(hwndMax->winId())); - m_h.SetEditorHWND(reinterpret_cast(hwndMatEdit->winId())); -#endif - } - -private: - - bool LoadMapFile() - { -#if defined(AZ_PLATFORM_WINDOWS) - bool bRet = false; - const HANDLE mapFileHandle = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, "EditMatMappingObject"); - if (mapFileHandle) - { - void* const pMes = MapViewOfFile(mapFileHandle, FILE_MAP_ALL_ACCESS, 0, 0, 0); - - if (pMes) - { - memcpy(&m_h, pMes, sizeof(SMaterialMapFileHeader)); - const char* const pXml = ((const char*)pMes) + sizeof(SMaterialMapFileHeader); - m_node = XmlHelpers::LoadXmlFromBuffer(pXml, strlen(pXml)); - UnmapViewOfFile(pMes); - bRet = true; - } - - CloseHandle(mapFileHandle); - } - - return bRet; -#else - return false; -#endif - } - -public: -#if defined(AZ_PLATFORM_WINDOWS) - SMaterialMapFileHeader m_h; -#endif - XmlNodeRef m_node; -private: - bool m_bIsMatEditor; -#if defined(AZ_PLATFORM_WINDOWS) - HANDLE hMapFile; -#endif -}; - - -#endif // CRYINCLUDE_EDITOR_MATERIALSENDER_H diff --git a/Code/Sandbox/Editor/ModelViewport.cpp b/Code/Sandbox/Editor/ModelViewport.cpp index bf15f2fbaf..2e00adb4fc 100644 --- a/Code/Sandbox/Editor/ModelViewport.cpp +++ b/Code/Sandbox/Editor/ModelViewport.cpp @@ -29,7 +29,6 @@ // Editor #include "ThumbnailGenerator.h" // for CThumbnailGenerator #include "FileTypeUtils.h" // for IsPreviewableFileType -#include "Material/MaterialManager.h" // for CMaterialManager #include "ErrorRecorder.h" @@ -652,32 +651,6 @@ void CModelViewport::DrawInfo() const } } -////////////////////////////////////////////////////////////////////////// -void CModelViewport::SetCustomMaterial(CMaterial* pMaterial) -{ - m_pCurrentMaterial = pMaterial; -} - -////////////////////////////////////////////////////////////////////////// -CMaterial* CModelViewport::GetMaterial() -{ - if (m_pCurrentMaterial) - { - return m_pCurrentMaterial; - } - else - { - _smart_ptr pMtl = 0; - if (m_object) - { - pMtl = m_object->GetMaterial(); - } - - CMaterial* pCMaterial = GetIEditor()->GetMaterialManager()->FromIMaterial(pMtl); - return pCMaterial; - } -} - ////////////////////////////////////////////////////////////////////////// bool CModelViewport::CanDrop([[maybe_unused]] const QPoint& point, IDataBaseItem* pItem) { @@ -686,26 +659,12 @@ bool CModelViewport::CanDrop([[maybe_unused]] const QPoint& point, IDataBaseItem return false; } - if (pItem->GetType() == EDB_TYPE_MATERIAL) - { - SetCustomMaterial((CMaterial*)pItem); - } return true; } ////////////////////////////////////////////////////////////////////////// -void CModelViewport::Drop([[maybe_unused]] const QPoint& point, IDataBaseItem* pItem) +void CModelViewport::Drop([[maybe_unused]] const QPoint& point, [[maybe_unused]] IDataBaseItem* pItem) { - if (!pItem) - { - SetCustomMaterial(NULL); - return; - } - - if (pItem->GetType() == EDB_TYPE_MATERIAL) - { - SetCustomMaterial((CMaterial*)pItem); - } } ////////////////////////////////////////////////////////////////////////// @@ -788,10 +747,6 @@ void CModelViewport::DrawModel(const SRenderingPassInfo& passInfo) } rp.dwFObjFlags = 0; - if (m_pCurrentMaterial) - { - rp.pMaterial = m_pCurrentMaterial->GetMatInfo(); - } //----------------------------------------------------------------------------- //----- Render Static Object (handled by 3DEngine) ---- diff --git a/Code/Sandbox/Editor/ModelViewport.h b/Code/Sandbox/Editor/ModelViewport.h index d9b119c5d5..a5d1ac2a26 100644 --- a/Code/Sandbox/Editor/ModelViewport.h +++ b/Code/Sandbox/Editor/ModelViewport.h @@ -31,7 +31,6 @@ #if !defined(Q_MOC_RUN) #include "RenderViewport.h" -#include "Material/Material.h" #include "Util/Variable.h" #endif @@ -90,14 +89,6 @@ public: void UseWeaponIK([[maybe_unused]] bool val) { m_weaponIK = true; } - // Set current material to render object. - void SetCustomMaterial(CMaterial* pMaterial); - // Get custom material that object is rendered with. - CMaterial* GetCustomMaterial() { return m_pCurrentMaterial; }; - - // Get material the object is actually rendered with. - CMaterial* GetMaterial(); - void ReleaseObject(); void RePhysicalize(); @@ -182,7 +173,6 @@ protected: class CRESky* m_pRESky; struct ICVar* m_pSkyboxName; IShader* m_pSkyBoxShader; - _smart_ptr m_pCurrentMaterial; //--------------------------------------------------- //--- debug options --- diff --git a/Code/Sandbox/Editor/Objects/AxisGizmo.cpp b/Code/Sandbox/Editor/Objects/AxisGizmo.cpp index 40970838c1..ef2b91685a 100644 --- a/Code/Sandbox/Editor/Objects/AxisGizmo.cpp +++ b/Code/Sandbox/Editor/Objects/AxisGizmo.cpp @@ -22,7 +22,6 @@ #include "ViewManager.h" #include "Settings.h" #include "RenderHelpers/AxisHelper.h" -#include "RenderHelpers/AxisHelperExtended.h" #include "IObjectManager.h" ////////////////////////////////////////////////////////////////////////// @@ -36,7 +35,6 @@ CAxisGizmo::CAxisGizmo(CBaseObject* object) assert(object != 0); m_object = object; m_pAxisHelper.reset(new CAxisHelper); - m_pAxisHelperExtended.reset(new CAxisHelperExtended); // Set selectable flag. SetFlags(EGIZMO_SELECTABLE | EGIZMO_TRANSFORM_MANIPULATOR); @@ -60,7 +58,6 @@ CAxisGizmo::CAxisGizmo() SetFlags(EGIZMO_SELECTABLE); m_axisGizmoCount++; m_pAxisHelper.reset(new CAxisHelper); - m_pAxisHelperExtended.reset(new CAxisHelperExtended); m_bDragging = false; m_bAlwaysUseLocal = false; m_coordSysBackUp = COORDS_VIEW; diff --git a/Code/Sandbox/Editor/Objects/AxisGizmo.h b/Code/Sandbox/Editor/Objects/AxisGizmo.h index 55506ed6b5..689b011972 100644 --- a/Code/Sandbox/Editor/Objects/AxisGizmo.h +++ b/Code/Sandbox/Editor/Objects/AxisGizmo.h @@ -22,7 +22,6 @@ // forward declarations. struct DisplayContext; class CAxisHelper; -class CAxisHelperExtended; /** Gizmo of Objects animation track. */ @@ -75,7 +74,6 @@ private: CBaseObjectPtr m_object; AABB m_bbox; std::unique_ptr m_pAxisHelper; - std::unique_ptr m_pAxisHelperExtended; bool m_bDragging; QPoint m_cMouseDownPos; diff --git a/Code/Sandbox/Editor/Objects/BaseObject.cpp b/Code/Sandbox/Editor/Objects/BaseObject.cpp index a579f303a9..109b28798f 100644 --- a/Code/Sandbox/Editor/Objects/BaseObject.cpp +++ b/Code/Sandbox/Editor/Objects/BaseObject.cpp @@ -30,8 +30,6 @@ #include "DisplaySettings.h" #include "Undo/Undo.h" #include "UsedResources.h" -#include "Material/Material.h" -#include "Material/MaterialManager.h" #include "GizmoManager.h" #include "Include/IIconManager.h" #include "Objects/SelectionGroup.h" @@ -398,7 +396,6 @@ CBaseObject::CBaseObject() , m_classDesc(nullptr) , m_numRefs(0) , m_parent(nullptr) - , m_pMaterial(nullptr) , m_bInSelectionBox(false) , m_pTransformDelegate(nullptr) , m_bMatrixInWorldSpace(false) @@ -438,7 +435,6 @@ bool CBaseObject::Init([[maybe_unused]] IEditor* ie, CBaseObject* prev, [[maybe_ SetArea(prev->GetArea()); SetColor(prev->GetColor()); m_nMaterialLayersMask = prev->m_nMaterialLayersMask; - SetMaterial(prev->GetMaterial()); SetMinSpec(prev->GetMinSpec(), false); // Copy all basic variables. @@ -485,12 +481,6 @@ void CBaseObject::Done() NotifyListeners(CBaseObject::ON_DELETE); m_eventListeners.clear(); - - if (m_pMaterial) - { - m_pMaterial->Release(); - m_pMaterial = NULL; - } } ////////////////////////////////////////////////////////////////////////// @@ -1838,11 +1828,6 @@ void CBaseObject::Serialize(CObjectArchive& ar) SetFrozen(bFrozen); SetHidden(bHidden); - ////////////////////////////////////////////////////////////////////////// - // Load material. - ////////////////////////////////////////////////////////////////////////// - SetMaterial(mtlName); - ar.SetResolveCallback(this, parentId, AZStd::bind(&CBaseObject::ResolveParent, this, AZStd::placeholders::_1 )); ar.SetResolveCallback(this, lookatId, AZStd::bind(&CBaseObject::SetLookAt, this, AZStd::placeholders::_1)); @@ -1912,11 +1897,6 @@ void CBaseObject::Serialize(CObjectArchive& ar) xmlNode->setAttr("Flags", flags); } - if (m_pMaterial) - { - xmlNode->setAttr("Material", GetMaterialName().toUtf8().data()); - } - if (m_nMinSpec != 0) { xmlNode->setAttr("MinSpec", (uint32)m_nMinSpec); @@ -1937,11 +1917,6 @@ XmlNodeRef CBaseObject::Export([[maybe_unused]] const QString& levelPath, XmlNod objNode->setAttr("Type", GetTypeName().toUtf8().data()); objNode->setAttr("Name", GetName().toUtf8().data()); - if (m_pMaterial) - { - objNode->setAttr("Material", m_pMaterial->GetName().toUtf8().data()); - } - Vec3 pos, scale; Quat rotate; if (m_parent) @@ -2926,7 +2901,6 @@ bool CBaseObject::ConvertFromObject(CBaseObject* object) { object->GetParent()->AttachChild(this); } - SetMaterial(object->GetMaterial()); return true; } @@ -2981,14 +2955,6 @@ void CBaseObject::Validate(IErrorReport* report) report->ReportError(err); } ////////////////////////////////////////////////////////////////////////// - - if (GetMaterial() != NULL && GetMaterial()->IsDummy()) - { - CErrorRecord err; - err.error = QStringLiteral("Material: %1 for object: %2 not found,").arg(GetMaterial()->GetName(), GetName()); - err.pObject = this; - report->ReportError(err); - } }; ////////////////////////////////////////////////////////////////////////// @@ -3055,10 +3021,6 @@ void CBaseObject::GatherUsedResources(CUsedResources& resources) { GetVarBlock()->GatherUsedResources(resources); } - if (m_pMaterial) - { - m_pMaterial->GatherUsedResources(resources); - } } ////////////////////////////////////////////////////////////////////////// @@ -3071,50 +3033,6 @@ bool CBaseObject::IsSimilarObject(CBaseObject* pObject) return false; } -////////////////////////////////////////////////////////////////////////// -void CBaseObject::SetMaterial(CMaterial* mtl) -{ - if (m_pMaterial == mtl) - { - return; - } - - StoreUndo("Assign Material"); - if (m_pMaterial) - { - m_pMaterial->Release(); - } - m_pMaterial = mtl; - if (m_pMaterial) - { - m_pMaterial->AddRef(); - } - - OnMaterialChanged(MATERIALCHANGE_ALL); -} - -////////////////////////////////////////////////////////////////////////// -QString CBaseObject::GetMaterialName() const -{ - if (m_pMaterial) - { - return m_pMaterial->GetName(); - } - return ""; -} - -////////////////////////////////////////////////////////////////////////// -void CBaseObject::SetMaterial(const QString& materialName) -{ - CMaterial* pMaterial = NULL; - CMaterialManager* pManager = GetIEditor()->GetMaterialManager(); - if (!materialName.isEmpty() && pManager != NULL) - { - pMaterial = pManager->LoadMaterial(materialName); - } - SetMaterial(pMaterial); -} - ////////////////////////////////////////////////////////////////////////// void CBaseObject::SetMinSpec(uint32 nSpec, bool bSetChildren) { diff --git a/Code/Sandbox/Editor/Objects/BaseObject.h b/Code/Sandbox/Editor/Objects/BaseObject.h index d62e0bed5f..44df1e5757 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 CMaterial; class CEdGeometry; struct SSubObjSelectionModifyContext; struct SRayHitInfo; @@ -135,13 +134,6 @@ enum ObjectEditFlags OBJECT_COLLAPSE_OBJECTPANEL = 0x004 }; -/////////////////////////////////////////////////////////////////////////// -enum MaterialChangeFlags -{ - MATERIALCHANGE_SURFACETYPE = 0x001, - MATERIALCHANGE_ALL = 0xFFFFFFFF, -}; - ////////////////////////////////////////////////////////////////////////// //! Return values from CBaseObject::MouseCreateCallback method. enum MouseCreateResult @@ -554,22 +546,6 @@ public: //! Remove event listener callback. void RemoveEventListener(EventListener* listener); - ////////////////////////////////////////////////////////////////////////// - //! Material handling for this base object. - //! Override in derived classes. - ////////////////////////////////////////////////////////////////////////// - //! Assign new material to this object. - virtual void SetMaterial(CMaterial* mtl); - //! Assign new material to this object as a material name. - virtual void SetMaterial(const QString& materialName); - //! Get assigned material for this object. - virtual CMaterial* GetMaterial() const { return m_pMaterial; }; - // Get actual rendering material for this object. - virtual CMaterial* GetRenderMaterial() const { return m_pMaterial; }; - // Get the material name. Even though the material pointer is null, the material name can exist separately. - virtual QString GetMaterialName() const; - virtual void OnMaterialChanged([[maybe_unused]] MaterialChangeFlags change) {} - ////////////////////////////////////////////////////////////////////////// //! Analyze errors for this object. virtual void Validate(IErrorReport* report); @@ -861,9 +837,6 @@ private: //! Pointer to parent node. mutable CBaseObject* m_parent; - //! Material of this object. - CMaterial* m_pMaterial; - AABB m_worldBounds; // The transform delegate diff --git a/Code/Sandbox/Editor/Objects/EntityObject.cpp b/Code/Sandbox/Editor/Objects/EntityObject.cpp index 82d45f8ae5..0b2627091c 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.cpp +++ b/Code/Sandbox/Editor/Objects/EntityObject.cpp @@ -25,7 +25,6 @@ #include "Settings.h" #include "Viewport.h" #include "LineGizmo.h" -#include "Material/MaterialManager.h" #include "Include/IObjectManager.h" #include "Objects/ObjectManager.h" #include "ViewManager.h" @@ -1077,11 +1076,6 @@ XmlNodeRef CEntityObject::Export([[maybe_unused]] const QString& levelPath, XmlN objNode->setAttr("Name", GetName().toUtf8().data()); - if (GetMaterial()) - { - objNode->setAttr("Material", GetMaterial()->GetName().toUtf8().data()); - } - Vec3 pos = GetPos(), scale = GetScale(); Quat rotate = GetRotation(); @@ -1860,17 +1854,6 @@ void CEntityObject::OnLoadFailed() GetIEditor()->GetErrorReport()->ReportError(err); } -////////////////////////////////////////////////////////////////////////// -CMaterial* CEntityObject::GetRenderMaterial() const -{ - if (GetMaterial()) - { - return GetMaterial(); - } - - return NULL; -} - ////////////////////////////////////////////////////////////////////////// void CEntityObject::SetHelperScale(float scale) { @@ -1943,21 +1926,6 @@ void CEntityObject::OnContextMenu(QMenu* pMenu) CBaseObject::OnContextMenu(pMenu); } -////////////////////////////////////////////////////////////////////////// -void CEntityObject::OnMaterialChanged(MaterialChangeFlags change) -{ - if (change & MATERIALCHANGE_SURFACETYPE) - { - m_statObjValidator.Validate(0, GetRenderMaterial()); - } -} - -////////////////////////////////////////////////////////////////////////// -QString CEntityObject::GetTooltip() const -{ - return m_statObjValidator.GetDescription(); -} - ////////////////////////////////////////////////////////////////////////// IOpticsElementBasePtr CEntityObject::GetOpticsElement() { @@ -1979,7 +1947,6 @@ void CEntityObject::SetOpticsName(const QString& opticsFullName) { pLight->SetLensOpticsElement(NULL); } - SetMaterial(NULL); } } diff --git a/Code/Sandbox/Editor/Objects/EntityObject.h b/Code/Sandbox/Editor/Objects/EntityObject.h index 941094c755..a287cd8828 100644 --- a/Code/Sandbox/Editor/Objects/EntityObject.h +++ b/Code/Sandbox/Editor/Objects/EntityObject.h @@ -21,7 +21,6 @@ #include "IMovieSystem.h" #include "IEntityObjectListener.h" -#include "StatObjValidator.h" #include "Gizmo.h" #include "CryListenerSet.h" #include "StatObjBus.h" @@ -108,8 +107,6 @@ public: void SetEntityPropertyFloat(const char* name, float value); void SetEntityPropertyString(const char* name, const QString& value); - virtual QString GetTooltip() const; - virtual int MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags); virtual void OnContextMenu(QMenu* menu); @@ -134,9 +131,6 @@ public: virtual void SetTransformDelegate(ITransformDelegate* pTransformDelegate) override; - virtual CMaterial* GetRenderMaterial() const; - virtual void OnMaterialChanged(MaterialChangeFlags change); - // Set attach flags and target enum EAttachmentType { @@ -405,8 +399,6 @@ protected: static float m_helperScale; - CStatObjValidator m_statObjValidator; - EAttachmentType m_attachmentType; bool m_bEnableReload; diff --git a/Code/Sandbox/Editor/Objects/ObjectLoader.cpp b/Code/Sandbox/Editor/Objects/ObjectLoader.cpp index 746b9e8c73..41f543a5a3 100644 --- a/Code/Sandbox/Editor/Objects/ObjectLoader.cpp +++ b/Code/Sandbox/Editor/Objects/ObjectLoader.cpp @@ -17,7 +17,6 @@ // Editor #include "Util/PakFile.h" -#include "Material/MaterialManager.h" #include "WaitProgress.h" #include "Include/IObjectManager.h" @@ -239,14 +238,6 @@ void CObjectArchive::ResolveObjects() obj.pObject->CreateGameObject(); - CMaterial* pMaterial = obj.pObject->GetRenderMaterial(); - CMaterialManager* pManager = GetIEditor()->GetMaterialManager(); - - if (pMaterial && pMaterial->GetMatInfo() && pManager) - { - pManager->OnRequestMaterial(pMaterial->GetMatInfo()); - } - // unset the current validator object because the wait Step // might generate unrelated errors m_pCurrentErrorReport->SetCurrentValidatorObject(nullptr); diff --git a/Code/Sandbox/Editor/Objects/SelectionGroup.cpp b/Code/Sandbox/Editor/Objects/SelectionGroup.cpp index b883b78e49..08abf8f763 100644 --- a/Code/Sandbox/Editor/Objects/SelectionGroup.cpp +++ b/Code/Sandbox/Editor/Objects/SelectionGroup.cpp @@ -20,7 +20,7 @@ // Editor #include "ViewManager.h" -#include "SurfaceInfoPicker.h" +#include "Include/IObjectManager.h" ////////////////////////////////////////////////////////////////////////// @@ -238,16 +238,6 @@ void CSelectionGroup::Move(const Vec3& offset, EMoveSelectionFlag moveFlag, [[ma } SRayHitInfo pickedInfo; - if (moveFlag == eMS_FollowGeometryPosNorm && bValidFollowGeometryMode) - { - CSurfaceInfoPicker::CExcludedObjects excludeObjects; - for (int i = 0; i < GetFilteredCount(); ++i) - { - excludeObjects.Add(GetFilteredObject(i)); - } - CSurfaceInfoPicker surfacePicker; - bValidFollowGeometryMode = surfacePicker.Pick(point, pickedInfo, &excludeObjects); - } if (moveFlag == eMS_FollowGeometryPosNorm) { diff --git a/Code/Sandbox/Editor/Objects/StatObjValidator.cpp b/Code/Sandbox/Editor/Objects/StatObjValidator.cpp deleted file mode 100644 index 85226fb236..0000000000 --- a/Code/Sandbox/Editor/Objects/StatObjValidator.cpp +++ /dev/null @@ -1,200 +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 "StatObjValidator.h" - -// Editor -#include "Material/Material.h" - - -CStatObjValidator::CStatObjValidator() - : m_isValid(true) -{ -} - -template -bool HasPrefix(const char* name, const char (&prefix)[size]) -{ - return _strnicmp(name, prefix, size - 1) == 0; -} - -struct SMeshMaterialIssue -{ - AZStd::string nodeName; - AZStd::string description; - int subMaterialIndex; - - SMeshMaterialIssue() - : subMaterialIndex(-1) - { - } - - SMeshMaterialIssue(const AZStd::string& name, const AZStd::string& description) - : nodeName(name) - , description(description) - , subMaterialIndex(-1) - { - } -}; - -static void ValidateMeshMaterials(std::vector* issues, IStatObj* pStatObj, CMaterial* pMaterial) -{ - _smart_ptr pIMaterial = 0; - if (pMaterial) - { - if (pMaterial->GetParent()) - { - pIMaterial = pMaterial->GetParent()->GetMatInfo(); - } - else - { - pIMaterial = pMaterial->GetMatInfo(); - } - } - - IIndexedMesh* pIndexedMesh = pStatObj->GetIndexedMesh(true); - if (pIndexedMesh) - { - int breakableSubmeshes = 0; - int nonbreakableSubmeshes = 0; - - int subsetCount = pIndexedMesh->GetSubSetCount(); - for (int i = 0; i < subsetCount; ++i) - { - const SMeshSubset& subset = pIndexedMesh->GetSubSet(i); - if (subset.nNumVerts == 0) - { - continue; - } - - // Check to see if the material uses multiple uv sets and if the vertex format has the same number of texCoord attributes - SShaderItem shaderItem = pIMaterial->GetShaderItem(i); - if (shaderItem.m_pShader) - { - size_t materialUVs = shaderItem.m_pShader->GetNumberOfUVSets(); - size_t meshUVs = subset.vertexFormat.GetAttributeUsageCount(AZ::Vertex::AttributeUsage::TexCoord); - if (materialUVs != meshUVs) - { - const char* meshName = pStatObj->GetRenderMesh() ? pStatObj->GetRenderMesh()->GetSourceName() : "unknown"; - AZStd::string errorMessage; - errorMessage = AZStd::string::format("Material '%s' sub-material %d with %zu uv set(s) was assigned to mesh '%s' with %zu uv set(s). ", pIMaterial->GetName(), i + 1, materialUVs, meshName, meshUVs); - - AZStd::string recommendedAction; - if (materialUVs < meshUVs) - { - recommendedAction = AZStd::string::format("If you do not intend to use %zu uv sets, remove the extra uv set(s) from the source mesh during the import process. Otherwise, consider checking the desired 'Use uv set 2 for...' shader gen params in the material editor.", meshUVs); - } - else - { - recommendedAction = AZStd::string::format("If you intend to use %zu uv sets, include the additional uv set(s) in the source mesh during the import process. Otherwise, consider unchecking the 'Use uv set 2 for...' shader gen params in the material editor.", materialUVs); - } - errorMessage += recommendedAction; - AZ_Warning("Material Editor", false, errorMessage.c_str()); - SMeshMaterialIssue issue(meshName, errorMessage); - issues->push_back(issue); - } - } - - _smart_ptr pSubMaterial = pIMaterial->GetSubMtl(subset.nMatID); - if (!pSubMaterial) - { - continue; - } - - if (size_t(subset.nMatID) > size_t(pMaterial->GetSubMaterialCount())) - { - continue; - } - - if (pSubMaterial->GetSurfaceType()->GetBreakable2DParams()) - { - ++breakableSubmeshes; - } - else - { - ++nonbreakableSubmeshes; - } - } - } - - - int subobjectCount = pStatObj->GetSubObjectCount(); - for (int i = 0; i < subobjectCount; ++i) - { - const IStatObj::SSubObject* subobject = pStatObj->GetSubObject(i); - if (subobject->pStatObj) - { - ValidateMeshMaterials(issues, subobject->pStatObj, pMaterial); - } - } -} - -void CStatObjValidator::Validate(IStatObj* statObj, CMaterial* editorMaterial) -{ - m_description = QString(); - m_isValid = true; - - _smart_ptr pIMaterial = 0; - if (editorMaterial) - { - if (editorMaterial->GetParent()) - { - pIMaterial = editorMaterial->GetParent()->GetMatInfo(); - } - else - { - pIMaterial = editorMaterial->GetMatInfo(); - } - } - - if (statObj && editorMaterial) - { - std::vector issues; - ValidateMeshMaterials(&issues, statObj, editorMaterial); - - if (!issues.empty()) - { - m_isValid = false; - } - - for (size_t i = 0; i < issues.size(); ++i) - { - const SMeshMaterialIssue& issue = issues[i]; - if (!m_description.isEmpty()) - { - m_description += "\n"; - } - if (!issue.nodeName.empty()) - { - m_description += "Node "; - m_description += issue.nodeName.c_str(); - m_description += ":"; - } - if (issue.subMaterialIndex >= 0) - { - m_description += QStringLiteral("SubMaterial %1:").arg(issue.subMaterialIndex + 1); - } - if (!issue.nodeName.empty() || issue.subMaterialIndex >= 0) - { - m_description += "\n "; - } - if (!issue.description.empty()) - { - m_description += issue.description.c_str(); - } - } - } -} - diff --git a/Code/Sandbox/Editor/Objects/StatObjValidator.h b/Code/Sandbox/Editor/Objects/StatObjValidator.h deleted file mode 100644 index 40145e90c5..0000000000 --- a/Code/Sandbox/Editor/Objects/StatObjValidator.h +++ /dev/null @@ -1,32 +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. - -// This class is supposed to validate CGF with assigned material. -// Some of the asset issues may be diagnosed only when SurfaceType is known. - -#pragma once - -class CRYEDIT_API CStatObjValidator -{ -public: - CStatObjValidator(); - - void Validate(IStatObj* statObj, CMaterial* editorMaterial); - bool IsValid() const { return m_isValid; } - - QString GetDescription() const { return m_description; } -private: - bool m_isValid; - QString m_description; -}; - diff --git a/Code/Sandbox/Editor/RenderHelpers/AxisHelperExtended.cpp b/Code/Sandbox/Editor/RenderHelpers/AxisHelperExtended.cpp deleted file mode 100644 index cee7f0f716..0000000000 --- a/Code/Sandbox/Editor/RenderHelpers/AxisHelperExtended.cpp +++ /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. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "AxisHelperExtended.h" - -#include "CryPhysicsDeprecation.h" - -// Editor -#include "Include/IDisplayViewport.h" -#include "SurfaceInfoPicker.h" -#include "Objects/DisplayContext.h" -#include "Objects/SelectionGroup.h" -#include "Util/fastlib.h" - - -////////////////////////////////////////////////////////////////////////// -// Helper Extended Axis object. -////////////////////////////////////////////////////////////////////////// -CAxisHelperExtended::CAxisHelperExtended() - : m_matrix(IDENTITY) - , m_vPos(ZERO) - , m_pCurObject(0) - , m_dwLastUpdateTime(0) - , m_fMaxDist(100.0f) -{ -} - -////////////////////////////////////////////////////////////////////////// -void CAxisHelperExtended::DrawAxes(DisplayContext& dc, const Matrix34& matrix, bool bUsePhysicalProxy) -{ - const DWORD dwUpdateTime = 2000; // 2 sec - CSelectionGroup* pSel = GetIEditor()->GetSelection(); - int numSels = pSel->GetCount(); - - if (numSels == 0) - { - return; - } - - CBaseObject* pCurObject = pSel->GetObject(numSels - 1); // get just last object for simple check - - // Add current selection to the elements to be skipped - CRY_PHYSICS_REPLACEMENT_ASSERT(); - - Vec3 x = Vec3(1, 0, 0); - Vec3 y = Vec3(0, 1, 0); - Vec3 z = Vec3(0, 0, 1); - - Vec3 colR = Vec3(1, 0, 0); - Vec3 colG = Vec3(0, 1, 0); - Vec3 colB = Vec3(0, 0.8f, 1); - - m_vPos = matrix.GetTranslation(); - - Vec3 vDirX = (matrix * x - m_vPos); - Vec3 vDirY = (matrix * y - m_vPos); - Vec3 vDirZ = (matrix * z - m_vPos); - vDirX.Normalize(); - vDirY.Normalize(); - vDirZ.Normalize(); - - if ( - m_pCurObject != pCurObject || - GetTickCount() - m_dwLastUpdateTime > dwUpdateTime || - !Matrix34::IsEquivalent(m_matrix, matrix) - ) - { - Vec3 outTmp; - AABB aabb(m_vPos, m_fMaxDist); - m_objects.clear(); - CBaseObjectsArray allObjects; - GetIEditor()->GetObjectManager()->GetObjects(allObjects); - - for (size_t i = 0, n = allObjects.size(); i < n; ++i) - { - CBaseObject* pObject = allObjects[i]; - if (pObject->IsSelected() || !pObject->GetEngineNode()) - { - continue; - } - - AABB aabbObj; - pObject->GetBoundBox(aabbObj); - - if (!Intersect::Ray_AABB(m_vPos, vDirX, aabbObj, outTmp) - && !Intersect::Ray_AABB(m_vPos, vDirY, aabbObj, outTmp) - && !Intersect::Ray_AABB(m_vPos, vDirZ, aabbObj, outTmp) - && !Intersect::Ray_AABB(m_vPos, -vDirX, aabbObj, outTmp) - && !Intersect::Ray_AABB(m_vPos, -vDirY, aabbObj, outTmp) - && !Intersect::Ray_AABB(m_vPos, -vDirZ, aabbObj, outTmp)) - { - continue; - } - - if (aabb.IsIntersectBox(aabbObj)) - { - m_objects.push_back(pObject); - } - } - m_dwLastUpdateTime = GetTickCount(); - } - m_pCurObject = pCurObject; - m_matrix = matrix; - - DrawAxis(dc, vDirX, z, colR, bUsePhysicalProxy); - DrawAxis(dc, vDirY, z, colG, bUsePhysicalProxy); - DrawAxis(dc, vDirZ, x, colB, bUsePhysicalProxy); - DrawAxis(dc, -vDirX, z, colR, bUsePhysicalProxy); - DrawAxis(dc, -vDirY, z, colG, bUsePhysicalProxy); - DrawAxis(dc, -vDirZ, x, colB, bUsePhysicalProxy); -} - - -////////////////////////////////////////////////////////////////////////// -void CAxisHelperExtended::DrawAxis(DisplayContext& dc, const Vec3& vDir, const Vec3& vUpAxis, const Vec3& col, bool bUsePhysicalProxy) -{ - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Editor); - - const float fBallSize = 0.005f; - const float fTextSize = 1.4f; - - float fDist = m_fMaxDist + 1.0f; - size_t objectsSize = m_objects.size(); - for (size_t i = 0; i < objectsSize; ++i) - { - CBaseObject* pObject = m_objects[i]; - if (pObject->CheckFlags(OBJFLAG_DELETED)) - { - continue; - } - - SRayHitInfo hitInfo; - if (pObject->IntersectRayMesh(m_vPos, vDir, hitInfo)) - { - Vec3 newP = pObject->GetWorldTM().TransformPoint(hitInfo.vHitPos); - float fNewDist = (newP - m_vPos).GetLength(); - if (fDist > fNewDist) - { - fDist = fNewDist; - } - } - } - - if (bUsePhysicalProxy) - { - CRY_PHYSICS_REPLACEMENT_ASSERT(); - } - else - { - CSurfaceInfoPicker picker; - m_objectsForPicker.assign(m_objects.begin(), m_objects.end()); - picker.SetObjects(&m_objectsForPicker); - SRayHitInfo hitInfo; - if (picker.Pick(m_vPos, fDist * vDir, hitInfo, NULL, CSurfaceInfoPicker::ePOG_All)) - { - fDist = hitInfo.fDistance; - } - picker.SetObjects(0); - } - - if (fDist < m_fMaxDist) - { - Vec3 p = m_vPos + vDir * fDist; - - dc.SetColor(col); - dc.DrawLine(m_vPos, p); - float fScreenScale = dc.view->GetScreenScaleFactor(p); - dc.DrawBall(p, fBallSize * fScreenScale); - QString label; - label = QString::number(fDist, 'f', 2); - dc.DrawTextOn2DBox((p + m_vPos) * 0.5f, label.toUtf8().data(), fTextSize, col, ColorF(0.0f, 0.0f, 0.0f, 0.7f)); - - Vec3 vUp = (m_matrix * vUpAxis - m_vPos); - vUp.Normalize(); - - Vec3 u = vUp; - Vec3 v = vDir ^ vUp; - float fPlaneSize = fDist / 4.0f; - float alphaMax = 1.0f, alphaMin = 0.0f; - ColorF colAlphaMin = ColorF(col.x, col.y, col.z, alphaMin); - - float fStepSize = dc.view->GetGridStep(); - const int MIN_STEP_COUNT = 5; - const int MAX_STEP_COUNT = 20; - int nSteps = std::min(std::max(FloatToIntRet(fPlaneSize / fStepSize), MIN_STEP_COUNT), MAX_STEP_COUNT); - float fGridSize = nSteps * fStepSize; - - for (int i = -nSteps; i <= nSteps; ++i) - { - Vec3 stepV = v * (fStepSize * i); - Vec3 stepU = u * (fStepSize * i); - ColorF colCurAlpha = ColorF(col.x, col.y, col.z, alphaMax - fabsf(float(i) / float(nSteps)) * (alphaMax - alphaMin)); - // Draw u lines. - dc.DrawLine(p + stepV, p + u * fGridSize + stepV, colCurAlpha, colAlphaMin); - dc.DrawLine(p + stepV, p - u * fGridSize + stepV, colCurAlpha, colAlphaMin); - // Draw v lines. - dc.DrawLine(p + stepU, p + v * fGridSize + stepU, colCurAlpha, colAlphaMin); - dc.DrawLine(p + stepU, p - v * fGridSize + stepU, colCurAlpha, colAlphaMin); - } - } -} diff --git a/Code/Sandbox/Editor/RenderHelpers/AxisHelperExtended.h b/Code/Sandbox/Editor/RenderHelpers/AxisHelperExtended.h deleted file mode 100644 index 42a1c66b9c..0000000000 --- a/Code/Sandbox/Editor/RenderHelpers/AxisHelperExtended.h +++ /dev/null @@ -1,44 +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_RENDERHELPERS_AXISHELPEREXTENDED_H -#define CRYINCLUDE_EDITOR_RENDERHELPERS_AXISHELPEREXTENDED_H -#pragma once - -#include "Objects/BaseObject.h" -#include "Include/IObjectManager.h" - -struct DisplayContext; -struct HitContext; - -class CAxisHelperExtended -{ -public: - CAxisHelperExtended(); - void DrawAxes(DisplayContext& dc, const Matrix34& matrix, bool bUsePhysicalProxy); - -private: - void DrawAxis(DisplayContext& dc, const Vec3& vDirAxis, const Vec3& vUpAxis, const Vec3& col, bool bUsePhysicalProxy); - -private: - Matrix34 m_matrix; - Vec3 m_vPos; - std::vector m_objects; - CBaseObjectsArray m_objectsForPicker; - CBaseObject* m_pCurObject; - DWORD m_dwLastUpdateTime; - - float m_fMaxDist; -}; - -#endif // CRYINCLUDE_EDITOR_RENDERHELPERS_AXISHELPEREXTENDED_H diff --git a/Code/Sandbox/Editor/Resource.h b/Code/Sandbox/Editor/Resource.h index 78a9855d71..51f9b1f3e9 100644 --- a/Code/Sandbox/Editor/Resource.h +++ b/Code/Sandbox/Editor/Resource.h @@ -95,9 +95,6 @@ #define ID_CHANGEMOVESPEED_INCREASE 32928 #define ID_CHANGEMOVESPEED_DECREASE 32929 #define ID_CHANGEMOVESPEED_CHANGESTEP 32930 -#define ID_MATERIAL_ASSIGNCURRENT 32933 -#define ID_MATERIAL_RESETTODEFAULT 32934 -#define ID_MATERIAL_GETMATERIAL 32935 #define ID_PHYSICS_GETPHYSICSSTATE 32937 #define ID_PHYSICS_RESETPHYSICSSTATE 32938 #define ID_GAME_SYNCPLAYER 32941 diff --git a/Code/Sandbox/Editor/SurfaceInfoPicker.cpp b/Code/Sandbox/Editor/SurfaceInfoPicker.cpp deleted file mode 100644 index 5ef20dcec0..0000000000 --- a/Code/Sandbox/Editor/SurfaceInfoPicker.cpp +++ /dev/null @@ -1,535 +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 "SurfaceInfoPicker.h" - -// AzToolsFramework -#include - -// Editor -#include "Material/MaterialManager.h" -#include "Objects/EntityObject.h" -#include "Viewport.h" -#include "QtViewPane.h" - -// ComponentEntityEditorPlugin -#include "Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h" - -static const float kEnoughFarDistance(5000.0f); - -CSurfaceInfoPicker::CSurfaceInfoPicker() - : m_pObjects(NULL) - , m_pSetObjects(NULL) - , m_PickOption(0) -{ - m_pActiveView = GetIEditor()->GetActiveView(); -} - -bool CSurfaceInfoPicker::PickByAABB(const QPoint& point, [[maybe_unused]] int nFlag, IDisplayViewport* pView, CExcludedObjects* pExcludedObjects, std::vector* pOutObjects) -{ - GetIEditor()->GetObjectManager()->GetObjects(m_objects); - - Vec3 vWorldRaySrc, vWorldRayDir; - m_pActiveView->ViewToWorldRay(point, vWorldRaySrc, vWorldRayDir); - vWorldRaySrc = vWorldRaySrc + vWorldRayDir * 0.1f; - vWorldRayDir = vWorldRayDir * kEnoughFarDistance; - - bool bPicked = false; - - for (int i = 0, iCount(m_objects.size()); i < iCount; ++i) - { - if (pExcludedObjects && pExcludedObjects->Contains(m_objects[i])) - { - continue; - } - - AABB worldObjAABB; - m_objects[i]->GetBoundBox(worldObjAABB); - - if (pView) - { - float fScreenFactor = pView->GetScreenScaleFactor(m_objects[i]->GetPos()); - worldObjAABB.Expand(0.01f * Vec3(fScreenFactor, fScreenFactor, fScreenFactor)); - } - - Vec3 vHitPos; - if (Intersect::Ray_AABB(vWorldRaySrc, vWorldRayDir, worldObjAABB, vHitPos)) - { - if ((vHitPos - vWorldRaySrc).GetNormalized().Dot(vWorldRayDir) > 0 || worldObjAABB.IsContainPoint(vHitPos)) - { - if (pOutObjects) - { - pOutObjects->push_back(m_objects[i]); - } - bPicked = true; - } - } - } - - return bPicked; -} - -bool CSurfaceInfoPicker::PickImpl(const QPoint& point, - _smart_ptr* ppOutLastMaterial, - SRayHitInfo& outHitInfo, - CExcludedObjects* pExcludedObjects, - int nFlag) -{ - Vec3 vWorldRaySrc; - Vec3 vWorldRayDir; - if (!m_pActiveView) - { - m_pActiveView = GetIEditor()->GetActiveView(); - } - m_pActiveView->ViewToWorldRay(point, vWorldRaySrc, vWorldRayDir); - vWorldRaySrc = vWorldRaySrc + vWorldRayDir * 0.1f; - vWorldRayDir = vWorldRayDir * kEnoughFarDistance; - - return PickImpl(vWorldRaySrc, vWorldRayDir, ppOutLastMaterial, outHitInfo, pExcludedObjects, nFlag); -} - -bool CSurfaceInfoPicker::PickImpl(const Vec3& vWorldRaySrc, const Vec3& vWorldRayDir, - _smart_ptr* ppOutLastMaterial, - SRayHitInfo& outHitInfo, - CExcludedObjects* pExcludedObjects, - int nFlag) -{ - memset(&outHitInfo, 0, sizeof(outHitInfo)); - outHitInfo.fDistance = kEnoughFarDistance; - - if (m_pSetObjects) - { - m_pObjects = m_pSetObjects; - } - else - { - GetIEditor()->GetObjectManager()->GetObjects(m_objects); - m_pObjects = &m_objects; - } - - if (pExcludedObjects) - { - m_ExcludedObjects = *pExcludedObjects; - } - else - { - m_ExcludedObjects.Clear(); - } - - m_pPickedObject = NULL; - - if (nFlag & ePOG_Entity) - { - FindNearestInfoFromEntities(vWorldRaySrc, vWorldRayDir, ppOutLastMaterial, outHitInfo); - } - - if (!m_pSetObjects) - { - m_objects.clear(); - } - - m_ExcludedObjects.Clear(); - - return outHitInfo.fDistance < kEnoughFarDistance; -} - -void CSurfaceInfoPicker::FindNearestInfoFromEntities( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - _smart_ptr* pOutLastMaterial, - SRayHitInfo& outHitInfo) const -{ - for (size_t i = 0; i < m_pObjects->size(); ++i) - { - CBaseObject* object((*m_pObjects)[i]); - - if (object == nullptr - || !qobject_cast(object) - || object->IsHidden() - || IsFrozen(object) - || m_ExcludedObjects.Contains(object) - ) - { - continue; - } - - CEntityObject* entityObject = static_cast(object); - - // If a legacy entity doesn't have a material override, we'll get the default material for that statObj - _smart_ptr statObjDefaultMaterial = nullptr; - // And in some cases the material we want does comes from RayIntersection(), and we will skip AssignObjectMaterial(). - _smart_ptr pickedMaterial = nullptr; - - bool hit = false; - - // entityObject is a component entity... - if (entityObject->GetType() == OBJTYPE_AZENTITY) - { - AZ::EntityId id; - AzToolsFramework::ComponentEntityObjectRequestBus::EventResult(id, entityObject, &AzToolsFramework::ComponentEntityObjectRequestBus::Events::GetAssociatedEntityId); - - // If the entity has an ActorComponent or another component that overrides RenderNodeRequestBus, it will hit here - if (!hit) - { - // There might be multiple components with render nodes on the same entity - // This will get the highest priority one, as determined by RenderNodeRequests::GetRenderNodeRequestBusOrder - IRenderNode* renderNode = entityObject->GetEngineNode(); - - // If the renderNode exists and is physicalized, it will hit here - hit = RayIntersection_IRenderNode(vWorldRaySrc, vWorldRayDir, renderNode, &pickedMaterial, object->GetWorldTM(), outHitInfo); - if (!hit) - { - // If the renderNode is not physicalized, such as an actor component, but still exists and has a valid material we might want to pick - if (renderNode && renderNode->GetMaterial()) - { - // Do a hit test with anything in this entity that has overridden EditorComponentSelectionRequestsBus - CComponentEntityObject* componentEntityObject = static_cast(entityObject); - HitContext hc; - hc.raySrc = vWorldRaySrc; - hc.rayDir = vWorldRayDir; - bool intersects = componentEntityObject->HitTest(hc); - - if (intersects) - { - // If the distance is closer than the nearest distance so far - if (hc.dist < outHitInfo.fDistance) - { - hit = true; - outHitInfo.vHitPos = hc.raySrc + hc.rayDir * hc.dist; - outHitInfo.fDistance = hc.dist; - // We don't get material/sub-material information back from HitTest, so just use the material from the render node - pickedMaterial = renderNode->GetMaterial(); - outHitInfo.nHitMatID = 0; - // We don't get normal information back from HitTest, so just orient the selection disk towards the camera - outHitInfo.vHitNormal = vWorldRayDir.normalized(); - } - } - } - } - } - } - - if (hit) - { - if(pickedMaterial) - { - AssignMaterial(pickedMaterial, outHitInfo, pOutLastMaterial); - } - else - { - if (object->GetMaterial()) - { - // If the entity has a material override, assign the object material - AssignObjectMaterial(object, outHitInfo, pOutLastMaterial); - } - else - { - // Otherwise assign the default material for that object - AssignMaterial(statObjDefaultMaterial, outHitInfo, pOutLastMaterial); - } - } - - m_pPickedObject = object; - } - } -} - -bool CSurfaceInfoPicker::RayIntersection_CBaseObject( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - CBaseObject* pBaseObject, - _smart_ptr* pOutLastMaterial, - SRayHitInfo& outHitInfo) -{ - if (pBaseObject == NULL) - { - return false; - } - IRenderNode* pRenderNode(pBaseObject->GetEngineNode()); - if (pRenderNode == NULL) - { - return false; - } - IStatObj* pStatObj(pRenderNode->GetEntityStatObj()); - if (pStatObj == NULL) - { - return false; - } - return RayIntersection(vWorldRaySrc, vWorldRayDir, pRenderNode, pStatObj, pBaseObject->GetWorldTM(), outHitInfo, pOutLastMaterial); -} - -bool CSurfaceInfoPicker::RayIntersection( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - IRenderNode* pRenderNode, - IStatObj* pStatObj, - const Matrix34A& WorldTM, - SRayHitInfo& outHitInfo, - _smart_ptr* ppOutLastMaterial) -{ - SRayHitInfo hitInfo; - bool bRayIntersection = false; - _smart_ptr pMaterial(NULL); - - bRayIntersection = RayIntersection_IStatObj(vWorldRaySrc, vWorldRayDir, pStatObj, &pMaterial, WorldTM, hitInfo); - if (!bRayIntersection) - { - bRayIntersection = RayIntersection_IRenderNode(vWorldRaySrc, vWorldRayDir, pRenderNode, &pMaterial, WorldTM, hitInfo); - } - - if (bRayIntersection) - { - hitInfo.fDistance = vWorldRaySrc.GetDistance(hitInfo.vHitPos); - if (hitInfo.fDistance < outHitInfo.fDistance) - { - if (ppOutLastMaterial) - { - *ppOutLastMaterial = pMaterial; - } - memcpy(&outHitInfo, &hitInfo, sizeof(SRayHitInfo)); - outHitInfo.vHitNormal.Normalize(); - return true; - } - } - return false; -} - -bool CSurfaceInfoPicker::RayIntersection_IStatObj( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - IStatObj* pStatObj, - _smart_ptr* ppOutLastMaterial, - const Matrix34A& worldTM, - SRayHitInfo& outHitInfo) -{ - if (pStatObj == NULL) - { - return false; - } - - Vec3 localRaySrc; - Vec3 localRayDir; - if (!RayWorldToLocal(worldTM, vWorldRaySrc, vWorldRayDir, localRaySrc, localRayDir)) - { - return false; - } - - // the outHitInfo contains information about the previous closest hit and should not be cleared / replaced unless you have a better hit! - // all of the intersection functions called (such as statobj's RayIntersection) only modify the hit info if it actually hits it closer than the current distance of the last hit. - - outHitInfo.inReferencePoint = localRaySrc; - outHitInfo.inRay = Ray(localRaySrc, localRayDir); - outHitInfo.bInFirstHit = false; - outHitInfo.bUseCache = false; - - _smart_ptr hitMaterial = nullptr; - - Vec3 hitPosOnAABB; - if (Intersect::Ray_AABB(outHitInfo.inRay, pStatObj->GetAABB(), hitPosOnAABB) == 0x00) - { - return false; - } - - if (pStatObj->RayIntersection(outHitInfo)) - { - if (outHitInfo.fDistance < 0) - { - return false; - } - outHitInfo.vHitPos = worldTM.TransformPoint(outHitInfo.vHitPos); - outHitInfo.vHitNormal = worldTM.GetTransposed().GetInverted().TransformVector(outHitInfo.vHitNormal); - - // we need to set nHitSurfaceID anyway - so we need to do this regardless of whether the caller - // has asked for detailed material info by passing in a non-null ppOutLastMaterial - hitMaterial = pStatObj->GetMaterial(); - - if (hitMaterial) - { - if (outHitInfo.nHitMatID >= 0) - { - if (hitMaterial->GetSubMtlCount() > 0 && outHitInfo.nHitMatID < hitMaterial->GetSubMtlCount()) - { - _smart_ptr subMaterial = hitMaterial->GetSubMtl(outHitInfo.nHitMatID); - if (subMaterial) - { - hitMaterial = subMaterial; - } - } - } - outHitInfo.nHitSurfaceID = hitMaterial->GetSurfaceTypeId(); - } - - if ((ppOutLastMaterial) && (hitMaterial)) - { - *ppOutLastMaterial = hitMaterial; - } - - return true; - } - - return outHitInfo.fDistance < kEnoughFarDistance; -} - -#if defined(USE_GEOM_CACHES) -bool CSurfaceInfoPicker::RayIntersection_IGeomCacheRenderNode( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - IGeomCacheRenderNode* pGeomCacheRenderNode, - _smart_ptr* ppOutLastMaterial, - [[maybe_unused]] const Matrix34A& worldTM, - SRayHitInfo& outHitInfo) -{ - if (!pGeomCacheRenderNode) - { - return false; - } - - SRayHitInfo newHitInfo = outHitInfo; - newHitInfo.inReferencePoint = vWorldRaySrc; - newHitInfo.inRay = Ray(vWorldRaySrc, vWorldRayDir); - newHitInfo.bInFirstHit = false; - newHitInfo.bUseCache = false; - - if (pGeomCacheRenderNode->RayIntersection(newHitInfo)) - { - if (newHitInfo.fDistance < 0 || newHitInfo.fDistance > kEnoughFarDistance || (outHitInfo.fDistance != 0 && newHitInfo.fDistance > outHitInfo.fDistance)) - { - return false; - } - - // Only override outHitInfo if the new hit is closer than the original hit - outHitInfo = newHitInfo; - if (ppOutLastMaterial) - { - _smart_ptr pMaterial = pGeomCacheRenderNode->GetMaterial(); - if (pMaterial) - { - *ppOutLastMaterial = pMaterial; - if (outHitInfo.nHitMatID >= 0) - { - if (pMaterial->GetSubMtlCount() > 0 && outHitInfo.nHitMatID < pMaterial->GetSubMtlCount()) - { - *ppOutLastMaterial = pMaterial->GetSubMtl(outHitInfo.nHitMatID); - } - } - } - } - return true; - } - - return false; -} -#endif - -bool CSurfaceInfoPicker::RayIntersection_IRenderNode( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - IRenderNode* pRenderNode, - _smart_ptr* pOutLastMaterial, - [[maybe_unused]] const Matrix34A& WorldTM, - SRayHitInfo& outHitInfo) -{ - if (pRenderNode == NULL) - { - return false; - } - - AZ_UNUSED(vWorldRaySrc) - AZ_UNUSED(vWorldRayDir) - AZ_UNUSED(pRenderNode) - AZ_UNUSED(pOutLastMaterial) - AZ_UNUSED(WorldTM) - AZ_UNUSED(outHitInfo) - return false; -} - -bool CSurfaceInfoPicker::RayWorldToLocal( - const Matrix34A& WorldTM, - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - Vec3& outRaySrc, - Vec3& outRayDir) -{ - if (!WorldTM.IsValid()) - { - return false; - } - Matrix34A invertedM(WorldTM.GetInverted()); - if (!invertedM.IsValid()) - { - return false; - } - outRaySrc = invertedM.TransformPoint(vWorldRaySrc); - outRayDir = invertedM.TransformVector(vWorldRayDir).GetNormalized(); - return true; -} - -bool CSurfaceInfoPicker::IsMaterialValid(CMaterial* pMaterial) -{ - if (pMaterial == NULL) - { - return false; - } - return !(pMaterial->GetMatInfo()->GetFlags() & MTL_FLAG_NODRAW); -} - -void CSurfaceInfoPicker::AssignObjectMaterial(CBaseObject* pObject, const SRayHitInfo& outHitInfo, _smart_ptr* pOutMaterial) -{ - CMaterial* material = pObject->GetMaterial(); - if (material) - { - if (material->GetMatInfo()) - { - if (pOutMaterial) - { - *pOutMaterial = material->GetMatInfo(); - if (*pOutMaterial) - { - if (outHitInfo.nHitMatID >= 0 && (*pOutMaterial)->GetSubMtlCount() > 0 && outHitInfo.nHitMatID < (*pOutMaterial)->GetSubMtlCount()) - { - *pOutMaterial = (*pOutMaterial)->GetSubMtl(outHitInfo.nHitMatID); - } - } - } - } - } -} - -void CSurfaceInfoPicker::AssignMaterial(_smart_ptr pMaterial, const SRayHitInfo& outHitInfo, _smart_ptr* pOutMaterial) -{ - if (pOutMaterial) - { - *pOutMaterial = pMaterial; - if (*pOutMaterial) - { - if (outHitInfo.nHitMatID >= 0 && (*pOutMaterial)->GetSubMtlCount() > 0 && outHitInfo.nHitMatID < (*pOutMaterial)->GetSubMtlCount()) - { - *pOutMaterial = (*pOutMaterial)->GetSubMtl(outHitInfo.nHitMatID); - } - } - } -} - -void CSurfaceInfoPicker::SetActiveView(IDisplayViewport* view) -{ - if (view) - { - m_pActiveView = view; - } - else - { - m_pActiveView = GetIEditor()->GetActiveView(); - } -} diff --git a/Code/Sandbox/Editor/SurfaceInfoPicker.h b/Code/Sandbox/Editor/SurfaceInfoPicker.h deleted file mode 100644 index 110408d558..0000000000 --- a/Code/Sandbox/Editor/SurfaceInfoPicker.h +++ /dev/null @@ -1,220 +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_SURFACEINFOPICKER_H -#define CRYINCLUDE_EDITOR_SURFACEINFOPICKER_H - -#pragma once - -#include "Include/IObjectManager.h" -#include "Objects/BaseObject.h" - -class CKDTree; -struct IDisplayViewport; - -////////////////////////////////////////////////////////////////////////// -class SANDBOX_API CSurfaceInfoPicker -{ -public: - - CSurfaceInfoPicker(); - - class CExcludedObjects - { - public: - - CExcludedObjects(){} - ~CExcludedObjects(){} - CExcludedObjects(const CExcludedObjects& excluded) - { - objects = excluded.objects; - } - - void Add(CBaseObject* pObject) - { - objects.insert(pObject); - } - - void Clear() - { - objects.clear(); - } - - bool Contains(CBaseObject* pObject) const - { - return objects.find(pObject) != objects.end(); - } - - private: - std::set objects; - }; - - enum EPickedObjectGroup - { - ePOG_Entity = BIT(1), - ePOG_All = ePOG_Entity, - }; - - enum EPickOption - { - ePickOption_IncludeFrozenObject = BIT(0), - }; - - void SetPickOptionFlag(int nFlag) { m_PickOption = nFlag; } - -public: - - bool Pick(const Vec3& vWorldRaySrc, const Vec3& vWorldRayDir, - _smart_ptr& ppOutLastMaterial, - SRayHitInfo& outHitInfo, - CExcludedObjects* pExcludedObjects = NULL, - int nFlag = ePOG_All) - { - return PickImpl(vWorldRaySrc, vWorldRayDir, &ppOutLastMaterial, outHitInfo, pExcludedObjects, nFlag); - } - - bool Pick(const Vec3& vWorldRaySrc, const Vec3& vWorldRayDir, - SRayHitInfo& outHitInfo, - CExcludedObjects* pExcludedObjects = NULL, - int nFlag = ePOG_All) - { - return PickImpl(vWorldRaySrc, vWorldRayDir, NULL, outHitInfo, pExcludedObjects, nFlag); - } - - bool Pick(const QPoint& point, - SRayHitInfo& outHitInfo, - CExcludedObjects* pExcludedObjects = NULL, - int nFlag = ePOG_All) - { - return PickImpl(point, NULL, outHitInfo, pExcludedObjects, nFlag); - } - - bool Pick(const QPoint& point, - _smart_ptr& ppOutLastMaterial, - SRayHitInfo& outHitInfo, - CExcludedObjects* pExcludedObjects = NULL, - int nFlag = ePOG_All) - { - return PickImpl(point, &ppOutLastMaterial, outHitInfo, pExcludedObjects, nFlag); - } - - bool PickByAABB(const QPoint& point, int nFlag = ePOG_All, IDisplayViewport* pView = NULL, CExcludedObjects* pExcludedObjects = NULL, std::vector* pOutObjects = NULL); - - void SetObjects(CBaseObjectsArray* pSetObjects) { m_pSetObjects = pSetObjects; } - - CBaseObjectPtr GetPickedObject() - { - return m_pPickedObject; - } - - void SetActiveView(IDisplayViewport* view); - -public: - - static bool RayWorldToLocal( - const Matrix34A& WorldTM, - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - Vec3& outRaySrc, - Vec3& outRayDir); - -private: - - bool IsFrozen(CBaseObject* pBaseObject) const - { - return !(m_PickOption & ePickOption_IncludeFrozenObject) && pBaseObject->IsFrozen(); - } - - bool PickImpl(const QPoint& point, - _smart_ptr* ppOutLastMaterial, - SRayHitInfo& outHitInfo, - CExcludedObjects* pExcludedObjects = NULL, - int nFlag = ePOG_All); - - bool PickImpl(const Vec3& vWorldRaySrc, const Vec3& vWorldRayDir, - _smart_ptr* ppOutLastMaterial, - SRayHitInfo& outHitInfo, - CExcludedObjects* pExcludedObjects = NULL, - int nFlag = ePOG_All); - - void FindNearestInfoFromEntities( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - _smart_ptr* ppOutLastMaterial, - SRayHitInfo& outHitInfo) const; - - /// Detect ray intersection with a IRenderNode or IStatObj. - /// But only if the intersection is closer than the one already in outHitInfo. - static bool RayIntersection( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - IRenderNode* pRenderNode, - IStatObj* pStatObj, - const Matrix34A& WorldTM, - SRayHitInfo& outHitInfo, - _smart_ptr* ppOutLastMaterial); - - /// Detect ray intersection with a IStatObj - static bool RayIntersection_IStatObj( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - IStatObj* pStatObj, - _smart_ptr* ppOutLastMaterial, - const Matrix34A& WorldTM, - SRayHitInfo& outHitInfo); - - /// Detect ray intersection with a IGeomCacheRenderNode - static bool RayIntersection_IGeomCacheRenderNode( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - IGeomCacheRenderNode* pGeomCacheRenderNode, - _smart_ptr* ppOutLastMaterial, - const Matrix34A& worldTM, - SRayHitInfo& outHitInfo); - - /// Detect ray intersection with a IRenderNode - static bool RayIntersection_IRenderNode( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - IRenderNode* pRenderNode, - _smart_ptr* ppOutLastMaterial, - const Matrix34A& WorldTM, - SRayHitInfo& outHitInfo); - - /// Detect ray intersection with a CBaseObject - static bool RayIntersection_CBaseObject( - const Vec3& vWorldRaySrc, - const Vec3& vWorldRayDir, - CBaseObject* pBaseObject, - _smart_ptr* ppOutLastMaterial, - SRayHitInfo& outHitInfo); - - static void AssignObjectMaterial(CBaseObject* pObject, const SRayHitInfo& outHitInfo, _smart_ptr* pOutMaterial); - static void AssignMaterial(_smart_ptr pObject, const SRayHitInfo& outHitInfo, _smart_ptr* pOutMaterial); - static bool IsMaterialValid(CMaterial* pMaterial); - -private: - - int m_PickOption; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - CBaseObjectsArray* m_pObjects; - CBaseObjectsArray* m_pSetObjects; - CBaseObjectsArray m_objects; - IDisplayViewport* m_pActiveView; - CExcludedObjects m_ExcludedObjects; - mutable CBaseObjectPtr m_pPickedObject; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // CRYINCLUDE_EDITOR_SURFACEINFOPICKER_H diff --git a/Code/Sandbox/Editor/SurfaceTypeValidator.cpp b/Code/Sandbox/Editor/SurfaceTypeValidator.cpp index 68bbdcf3bb..9aec070912 100644 --- a/Code/Sandbox/Editor/SurfaceTypeValidator.cpp +++ b/Code/Sandbox/Editor/SurfaceTypeValidator.cpp @@ -16,7 +16,6 @@ #include "SurfaceTypeValidator.h" // Editor -#include "Material/Material.h" #include "Include/IObjectManager.h" #include "Objects/BaseObject.h" #include "ErrorReport.h" diff --git a/Code/Sandbox/Editor/TrackView/TrackViewSequenceManager.cpp b/Code/Sandbox/Editor/TrackView/TrackViewSequenceManager.cpp index 12f38c920a..0ba7c5b325 100644 --- a/Code/Sandbox/Editor/TrackView/TrackViewSequenceManager.cpp +++ b/Code/Sandbox/Editor/TrackView/TrackViewSequenceManager.cpp @@ -27,7 +27,6 @@ #include "AnimationContext.h" #include "GameEngine.h" #include "Include/IObjectManager.h" -#include "Material/MaterialManager.h" #include "Objects/ObjectManager.h" @@ -35,7 +34,6 @@ CTrackViewSequenceManager::CTrackViewSequenceManager() { GetIEditor()->RegisterNotifyListener(this); - GetIEditor()->GetMaterialManager()->AddListener(this); AZ::EntitySystemBus::Handler::BusConnect(); } @@ -45,7 +43,6 @@ CTrackViewSequenceManager::~CTrackViewSequenceManager() { AZ::EntitySystemBus::Handler::BusDisconnect(); - GetIEditor()->GetMaterialManager()->RemoveListener(this); GetIEditor()->UnregisterNotifyListener(this); } diff --git a/Code/Sandbox/Editor/Util/Variable.h b/Code/Sandbox/Editor/Util/Variable.h index 20c18d4409..d00ef6103a 100644 --- a/Code/Sandbox/Editor/Util/Variable.h +++ b/Code/Sandbox/Editor/Util/Variable.h @@ -152,7 +152,7 @@ struct IVariable DT_LOCAL_STRING, DT_EQUIP, DT_REVERBPRESET, - DT_MATERIAL, + DT_DEPRECATED0, // formerly DT_MATERIAL DT_MATERIALLOOKUP, DT_EXTARRAY, // Extendable Array DT_SEQUENCE, // Movie Sequence (DEPRECATED, use DT_SEQUENCE_ID, instead.) diff --git a/Code/Sandbox/Editor/Util/VariablePropertyType.cpp b/Code/Sandbox/Editor/Util/VariablePropertyType.cpp index c80461182d..c7fd3d9de2 100644 --- a/Code/Sandbox/Editor/Util/VariablePropertyType.cpp +++ b/Code/Sandbox/Editor/Util/VariablePropertyType.cpp @@ -49,7 +49,7 @@ namespace Prop { IVariable::DT_SIMPLE, "Selection", ePropertySelection, -1 }, { IVariable::DT_SIMPLE, "List", ePropertyList, -1 }, { IVariable::DT_SHADER, "Shader", ePropertyShader, 9 }, - { IVariable::DT_MATERIAL, "Material", ePropertyMaterial, 14 }, + { IVariable::DT_DEPRECATED0, "DEPRECATED", ePropertyDeprecated2, -1 }, { IVariable::DT_EQUIP, "Equip", ePropertyEquip, 11 }, { IVariable::DT_REVERBPRESET, "ReverbPreset", ePropertyReverbPreset, 11 }, { IVariable::DT_LOCAL_STRING, "LocalString", ePropertyLocalString, 3 }, diff --git a/Code/Sandbox/Editor/Util/VariablePropertyType.h b/Code/Sandbox/Editor/Util/VariablePropertyType.h index 76379c1bc0..130148c903 100644 --- a/Code/Sandbox/Editor/Util/VariablePropertyType.h +++ b/Code/Sandbox/Editor/Util/VariablePropertyType.h @@ -39,7 +39,7 @@ enum PropertyType ePropertySelection, ePropertyList, ePropertyShader, - ePropertyMaterial, + ePropertyDeprecated2, // formerly ePropertyMaterial ePropertyEquip, ePropertyReverbPreset, ePropertyLocalString, diff --git a/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp b/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp index 61cdac53c6..206131e5a9 100644 --- a/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp +++ b/Code/Sandbox/Editor/Util/VariableTypeInfo.cpp @@ -112,10 +112,6 @@ void CVariableTypeInfo::SetTypes(CTypeInfo const& TypeInfo, EType eType) { SetDataType(DT_TEXTURE); } - else if (m_name == "Material") - { - SetDataType(DT_MATERIAL); - } else if (m_name == "Geometry") { SetDataType(DT_OBJECT); diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index e6337796d6..a0c22c9a14 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -309,15 +309,6 @@ set(FILES Util/AffineParts.cpp Objects/BaseObject.cpp Objects/BaseObject.h - Material/Material.cpp - Material/Material.h - Material/MaterialHelpers.cpp - Material/MaterialHelpers.h - Material/MaterialDialog.qrc - Material/MaterialPreviewModelView.cpp - Material/MaterialPreviewModelView.h - Material/PreviewModelView.cpp - Material/PreviewModelView.h Alembic/AlembicCompileDialog.cpp Alembic/AlembicCompileDialog.h Alembic/AlembicCompileDialog.ui @@ -553,7 +544,6 @@ set(FILES IObservable.h IPostRenderer.h LightmapCompiler/SimpleTriangleRasterizer.h - SurfaceInfoPicker.h ToolBox.h TrackViewNewSequenceDialog.h UndoConfigSpec.h @@ -570,25 +560,6 @@ set(FILES LevelIndependentFileMan.h LogFileImpl.cpp LogFileImpl.h - MatEditPreviewDlg.cpp - MatEditPreviewDlg.h - Material/MaterialBrowser.cpp - Material/MaterialBrowser.h - Material/MaterialBrowser.ui - Material/MaterialBrowserSearchFilters.cpp - Material/MaterialBrowserSearchFilters.h - Material/MaterialBrowserFilterModel.cpp - Material/MaterialBrowserFilterModel.h - Material/MaterialImageListCtrl.cpp - Material/MaterialImageListCtrl.h - Material/MaterialLibrary.cpp - Material/MaterialLibrary.h - Material/MaterialManager.cpp - Material/MaterialManager.h - MaterialSender.h - MaterialSender.cpp - Material/MaterialPythonFuncs.h - Material/MaterialPythonFuncs.cpp Mission.cpp Mission.h Objects/ClassDesc.cpp @@ -596,8 +567,6 @@ set(FILES Objects/IEntityObjectListener.h Objects/SelectionGroup.cpp Objects/SelectionGroup.h - Objects/StatObjValidator.cpp - Objects/StatObjValidator.h Objects/SubObjSelection.cpp Objects/SubObjSelection.h Objects/ObjectLoader.cpp @@ -631,9 +600,7 @@ set(FILES QtUI/WaitCursor.h QtUI/WaitCursor.cpp RenderHelpers/AxisHelper.cpp - RenderHelpers/AxisHelperExtended.cpp RenderHelpers/AxisHelper.h - RenderHelpers/AxisHelperExtended.h Serialization.h Serialization/VariableOArchive.cpp Serialization/VariableOArchive.h @@ -687,7 +654,6 @@ set(FILES LightmapCompiler/SimpleTriangleRasterizer.cpp ResourceSelectorHost.cpp ResourceSelectorHost.h - SurfaceInfoPicker.cpp ThumbnailGenerator.cpp ThumbnailGenerator.h ToolBox.cpp diff --git a/Code/Sandbox/Editor/editor_lib_test_files.cmake b/Code/Sandbox/Editor/editor_lib_test_files.cmake index f537169136..9eca3c56ae 100644 --- a/Code/Sandbox/Editor/editor_lib_test_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_test_files.cmake @@ -18,7 +18,6 @@ set(FILES Lib/Tests/test_EditorUtils.cpp Lib/Tests/test_Main.cpp Lib/Tests/test_MainWindowPythonBindings.cpp - Lib/Tests/test_MaterialPythonFuncs.cpp Lib/Tests/test_ObjectManagerPythonBindings.cpp Lib/Tests/test_TrackViewPythonBindings.cpp Lib/Tests/test_ViewPanePythonBindings.cpp diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp index 8f695c39ab..692bb92bf7 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.cpp @@ -46,9 +46,7 @@ #include #include -#include #include -#include #include #include #include @@ -1096,56 +1094,3 @@ void CComponentEntityObject::DrawAccent(DisplayContext& dc) dc.DrawWireBox(box.min, box.max); } } - -void CComponentEntityObject::SetMaterial(CMaterial* material) -{ - AZ::Entity* entity = nullptr; - EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, m_entityId); - if (entity) - { - if (material) - { - EBUS_EVENT_ID(m_entityId, LmbrCentral::MaterialOwnerRequestBus, SetMaterial, material->GetMatInfo()); - } - else - { - EBUS_EVENT_ID(m_entityId, LmbrCentral::MaterialOwnerRequestBus, SetMaterial, nullptr); - } - } - - ValidateMeshStatObject(); -} - -CMaterial* CComponentEntityObject::GetMaterial() const -{ - _smart_ptr material = nullptr; - EBUS_EVENT_ID_RESULT(material, m_entityId, LmbrCentral::MaterialOwnerRequestBus, GetMaterial); - return GetIEditor()->GetMaterialManager()->FromIMaterial(material); -} - -CMaterial* CComponentEntityObject::GetRenderMaterial() const -{ - AZ::Entity* entity = nullptr; - EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, m_entityId); - if (entity) - { - _smart_ptr material = nullptr; - EBUS_EVENT_ID_RESULT(material, m_entityId, LmbrCentral::MaterialOwnerRequestBus, GetMaterial); - - if (material) - { - return GetIEditor()->GetMaterialManager()->LoadMaterial(material->GetName(), false); - } - } - - return nullptr; -} - -void CComponentEntityObject::ValidateMeshStatObject() -{ - IStatObj* statObj = GetIStatObj(); - CMaterial* editorMaterial = GetMaterial(); - CStatObjValidator statValidator; - statValidator.Validate(statObj, editorMaterial); -} - diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h index 41619d75c5..b64bd6b3e1 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h @@ -79,9 +79,6 @@ public: CBaseObject* GetLinkParent() const override; XmlNodeRef Export(const QString& levelPath, XmlNodeRef& xmlNode) override; void DeleteEntity() override; - void SetMaterial(CMaterial* mtl) override; - CMaterial* GetMaterial() const override; - CMaterial* GetRenderMaterial() const override; void DrawDefault(DisplayContext& dc, const QColor& labelColor = QColor(255, 255, 255)) override; IStatObj* GetIStatObj() override; bool IsIsolated() const override; @@ -184,8 +181,6 @@ protected: void DrawAccent(DisplayContext& dc); - void ValidateMeshStatObject(); - class EditorActionGuard { public: diff --git a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequenceManager.cpp b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequenceManager.cpp index a65e220cbd..225f4e0b1a 100644 --- a/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequenceManager.cpp +++ b/Gems/LyShine/Code/Editor/Animation/UiAnimViewSequenceManager.cpp @@ -16,7 +16,6 @@ #include "UiEditorDLLBus.h" #include "UiAnimViewSequenceManager.h" #include "UiAnimViewUndo.h" -#include "Material/MaterialManager.h" #include "AnimationContext.h" #include "GameEngine.h" #include From 13c7b063085cbba2fed846aac9a957f1d8af319d Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 3 May 2021 15:00:40 -0700 Subject: [PATCH 050/185] Handle EMotionFX hotkeys with QActions instead of in `keyPressEvent` (#514) EMotionFX has user-customizable hotkeys. These hotkeys are registered by individual plugins, and then the user can set what they want the hotkey to be. The way this was implemented was by reimplementing `keyPressEvent` and `keyReleaseEvent` for each widget that used customizable hotkeys, and in there call `KeyboardShortcutManager::Check` to see if key press matched any existing hotkey mapping. However, the main Editor has behavior that prevents events from reaching EMotionFX's `keyPressEvent` method, if a keypress matches a hotkey that is also used by the main Editor. This is due to the global event filter defined in `ShortcutDispatcher::eventFilter`. This event filter takes a Qt `Shortcut` event, and will re-dispatch that event to all parent widgets of a given receiver. So if a parent widget, like the main Editor, *does* have a QAction that matches a given key sequence, that widget will receive the event, the event is marked as processed, and no `KeyPress` event is ever sent to the original widget where the event occurred. All this means that processing hotkeys in a `keyPressEvent` won't work reliably. The main editor defines a hotkey for the `delete` key, so that can never be received in a `keyPressEvent` by any child widget of the Editor. This change removes all the hotkey logic from the `keyPressEvent` methods, and replaces them with `QAction` instances. Hotkeys are defined with `QAction::setShortcut`, and added to each widget that they apply to. In addition, the `KeyboardShortcutManager` class had to be adjusted to suit this new way of defining the hotkeys. It now has a pointer to each `QAction*` that can have a customizable hotkey. It has also been greatly simplified, since it can use a `QKeySequence` instead of separate variables for `int key; bool hasCtrlModifier; bool hasAltModifier`. Applying user-defined hotkeys now has to be done after the hotkeys are registered from a plugin. It is the plugin's responsibility to reload the user-defined hotkeys after registering all of its actions. --- .../EMStudioSDK/Source/EMStudioPlugin.h | 2 - .../Source/KeyboardShortcutsWindow.cpp | 104 +--- .../Source/KeyboardShortcutsWindow.h | 8 +- .../EMStudioSDK/Source/MainWindow.cpp | 73 ++- .../EMStudioSDK/Source/MainWindow.h | 5 +- .../EMStudioSDK/Source/PluginManager.cpp | 1 - .../Source/RenderPlugin/RenderPlugin.cpp | 11 - .../Source/RenderPlugin/RenderPlugin.h | 8 +- .../Source/RenderPlugin/RenderViewWidget.cpp | 37 +- .../Source/RenderPlugin/RenderViewWidget.h | 2 + .../Source/RenderPlugin/RenderWidget.cpp | 68 --- .../Source/RenderPlugin/RenderWidget.h | 4 +- .../Source/OpenGLRender/GLWidget.h | 2 - .../AnimGraph/AnimGraphActionManager.cpp | 24 +- .../Source/AnimGraph/AnimGraphActionManager.h | 6 + .../Source/AnimGraph/AnimGraphPlugin.cpp | 32 +- .../Source/AnimGraph/AnimGraphPlugin.h | 24 +- .../Source/AnimGraph/BlendGraphViewWidget.cpp | 504 +++++++++++------- .../Source/AnimGraph/BlendGraphViewWidget.h | 57 +- .../Source/AnimGraph/BlendGraphWidget.cpp | 254 --------- .../Source/AnimGraph/BlendGraphWidget.h | 3 - .../Source/AnimGraph/ContextMenu.cpp | 55 +- .../Source/AnimGraph/NodeGraphWidget.cpp | 64 +-- .../Source/AnimGraph/NodeGraphWidget.h | 11 +- .../Source/KeyboardShortcutManager.cpp | 309 ++++------- .../MysticQt/Source/KeyboardShortcutManager.h | 96 ++-- .../Code/MysticQt/Source/MysticQtConfig.h | 9 +- .../AnimGraph/CanDeleteAnimGraphNode.cpp | 7 +- .../Transitions/RemoveTransition.cpp | 6 +- 29 files changed, 697 insertions(+), 1089 deletions(-) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioPlugin.h index 85fc9c8d56..e33a5f3f51 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/EMStudioPlugin.h @@ -78,8 +78,6 @@ namespace EMStudio virtual void OnBeforeRemovePlugin(uint32 classID) { MCORE_UNUSED(classID); } virtual void OnMainWindowClosed() {} - virtual void RegisterKeyboardShortcuts() {} - struct RenderInfo { MCORE_MEMORYOBJECTCATEGORY(EMStudioPlugin::RenderInfo, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_EMSTUDIOSDK) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.cpp index b8093d2115..d6fdb9128b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.cpp @@ -116,14 +116,6 @@ namespace EMStudio } - void KeyboardShortcutsWindow::hideEvent(QHideEvent* event) - { - MCORE_UNUSED(event); - //if (mShortcutReceiverDialog) - // mShortcutReceiverDialog->reject(); - } - - // reconstruct the whole interface void KeyboardShortcutsWindow::ReInit() { @@ -138,11 +130,11 @@ namespace EMStudio // add the groups to the left list widget MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - const uint32 numGroups = shortcutManager->GetNumGroups(); + const size_t numGroups = shortcutManager->GetNumGroups(); for (uint32 i = 0; i < numGroups; ++i) { MysticQt::KeyboardShortcutManager::Group* group = shortcutManager->GetGroup(i); - mListWidget->addItem(group->GetName()); + mListWidget->addItem(FromStdString(group->GetName())); } mTableWidget->blockSignals(false); @@ -183,10 +175,10 @@ namespace EMStudio // get access to the shortcut group and some data MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); MysticQt::KeyboardShortcutManager::Group* group = shortcutManager->GetGroup(mSelectedGroup); - const uint32 numActions = group->GetNumActions(); + const size_t numActions = group->GetNumActions(); // set the row count - mTableWidget->setRowCount(numActions); + mTableWidget->setRowCount(aznumeric_caster(numActions)); // fill the table with the media root folders for (uint32 i = 0; i < numActions; ++i) @@ -195,11 +187,11 @@ namespace EMStudio MysticQt::KeyboardShortcutManager::Action* action = group->GetAction(i); // add the item to the table and set the row height - QTableWidgetItem* item = new QTableWidgetItem(action->mName.c_str()); + QTableWidgetItem* item = new QTableWidgetItem(action->m_qaction->text()); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); mTableWidget->setItem(i, 0, item); - const QString keyText = ConstructStringFromShortcut(action->mKey, action->mCtrl, action->mAlt); + const QString keyText = ConstructStringFromShortcut(action->m_qaction->shortcut()); item = new QTableWidgetItem(keyText); item->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable); @@ -255,18 +247,14 @@ namespace EMStudio // handle conflicts if (shortcutWindow.mConflictDetected) { - shortcutWindow.mConflictAction->mKey = -1; - shortcutWindow.mConflictAction->mCtrl = false; - shortcutWindow.mConflictAction->mAlt = false; + shortcutWindow.mConflictAction->m_qaction->setShortcut({}); } // adjust the shortcut action - action->mKey = shortcutWindow.mKey; - action->mAlt = shortcutWindow.mAlt; - action->mCtrl = shortcutWindow.mCtrl; + action->m_qaction->setShortcut(shortcutWindow.mKey); // save the new shortcuts - QSettings settings(AZStd::string(GetManager()->GetAppDataFolder() + "EMStudioKeyboardShortcuts.cfg").c_str(), QSettings::IniFormat, this); + QSettings settings(FromStdString(AZStd::string(GetManager()->GetAppDataFolder() + "EMStudioKeyboardShortcuts.cfg")), QSettings::IniFormat, this); shortcutManager->Save(&settings); // reinit the window @@ -277,31 +265,14 @@ namespace EMStudio // construct a text version of a shortcut - QString KeyboardShortcutsWindow::ConstructStringFromShortcut(int key, bool ctrl, bool alt) + QString KeyboardShortcutsWindow::ConstructStringFromShortcut(QKeySequence key) { - if (key == -1) + if (key.isEmpty()) { return "not set"; } - QString keyText; - - if (ctrl) - { - #if AZ_TRAIT_OS_PLATFORM_APPLE - keyText += "COMMAND + "; - #else - keyText += "CTRL + "; - #endif - } - if (alt) - { - keyText += "ALT + "; - } - - keyText += QKeySequence(key).toString(QKeySequence::NativeText); - - return keyText; + return key.toString(QKeySequence::NativeText); } @@ -313,9 +284,7 @@ namespace EMStudio return; } - mContextMenuAction->mKey = mContextMenuAction->mDefaultKey; - mContextMenuAction->mCtrl = mContextMenuAction->mDefaultCtrl; - mContextMenuAction->mAlt = mContextMenuAction->mDefaultAlt; + mContextMenuAction->m_qaction->setShortcut(mContextMenuAction->m_defaultKeySequence); ReInit(); } @@ -378,19 +347,14 @@ namespace EMStudio setWindowTitle(" "); layout->addWidget(new QLabel("Press the new shortcut on the keyboard:")); - // find the initial shortcut - //MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - mOrgAction = action; mOrgGroup = group; mConflictAction = nullptr; mConflictDetected = false; - mKey = action->mKey; - mCtrl = action->mCtrl; - mAlt = action->mAlt; + mKey = action->m_qaction->shortcut(); - QString keyText = KeyboardShortcutsWindow::ConstructStringFromShortcut(mKey, mCtrl, mAlt); + QString keyText = KeyboardShortcutsWindow::ConstructStringFromShortcut(mKey); mLabel = new QLabel(keyText); mLabel->setAlignment(Qt::AlignHCenter); @@ -431,9 +395,7 @@ namespace EMStudio // reset the shortcut to its default value void ShortcutReceiverDialog::ResetToDefault() { - mKey = mOrgAction->mDefaultKey; - mCtrl = mOrgAction->mDefaultCtrl; - mAlt = mOrgAction->mDefaultAlt; + mKey = mOrgAction->m_defaultKeySequence; UpdateInterface(); } @@ -444,10 +406,8 @@ namespace EMStudio { MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - QString keyText = KeyboardShortcutsWindow::ConstructStringFromShortcut(mKey, mCtrl, mAlt); - // check if the currently assigned shortcut is already taken by another shortcut - mConflictAction = shortcutManager->FindShortcut(mKey, mCtrl, mAlt, mOrgGroup); + mConflictAction = shortcutManager->FindShortcut(mKey, mOrgGroup); if (mConflictAction == nullptr || mConflictAction == mOrgAction) { mOKButton->setToolTip(""); @@ -465,39 +425,25 @@ namespace EMStudio if (mConflictAction) { - AZStd::string tempString; - - tempString = AZStd::string::format("Assigning new shortcut will unassign '%s' automatically.", mConflictAction->mName.c_str()); - mOKButton->setToolTip(tempString.c_str()); + mOKButton->setToolTip(QString("Assigning new shortcut will unassign '%1' automatically.").arg(mConflictAction->m_qaction->text())); MysticQt::KeyboardShortcutManager::Group* conflictGroup = shortcutManager->FindGroupForShortcut(mConflictAction); if (conflictGroup) { - tempString = AZStd::string::format("Conflicts with: %s -> %s", conflictGroup->GetName(), mConflictAction->mName.c_str()); + mConflictKeyLabel->setText(QString("Conflicts with: %1 -> %2").arg(FromStdString(conflictGroup->GetName())).arg(mConflictAction->m_qaction->text())); } else { - tempString = AZStd::string::format("Conflicts with: %s", mConflictAction->mName.c_str()); + mConflictKeyLabel->setText(QString("Conflicts with: %1").arg(mConflictAction->m_qaction->text())); } - - mConflictKeyLabel->setText(tempString.c_str()); } } // adjust the label text to the new shortcut + const QString keyText = KeyboardShortcutsWindow::ConstructStringFromShortcut(mKey); mLabel->setText(keyText); } - - // close dialog as soon as it lost focus - void ShortcutReceiverDialog::focusOutEvent(QFocusEvent* event) - { - MCORE_UNUSED(event); - // if (event->reason() == Qt::ActiveWindowFocusReason) - // reject(); - } - - // called when the user pressed a new shortcut void ShortcutReceiverDialog::keyPressEvent(QKeyEvent* event) { @@ -513,18 +459,12 @@ namespace EMStudio if (event->key() == Qt::Key_Escape) { - //mKey = mOrgAction->mKey; - //mCtrl = mOrgAction->mCtrl; - //mAlt = mOrgAction->mAlt; - // close the dialog when pressing ESC reject(); } else { - mKey = event->key(); - mCtrl = event->modifiers() & Qt::ControlModifier; - mAlt = event->modifiers() & Qt::AltModifier; + mKey = event->key() | event->modifiers(); } UpdateInterface(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.h index 024479cc90..f6d4f43642 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/KeyboardShortcutsWindow.h @@ -41,12 +41,9 @@ namespace EMStudio virtual ~ShortcutReceiverDialog() {} void keyPressEvent(QKeyEvent* event) override; - void focusOutEvent(QFocusEvent* event) override; void UpdateInterface(); - int mKey; - bool mCtrl; - bool mAlt; + QKeySequence mKey; bool mConflictDetected; MysticQt::KeyboardShortcutManager::Action* mConflictAction; @@ -74,7 +71,7 @@ namespace EMStudio void Init(); void ReInit(); - static QString ConstructStringFromShortcut(int key, bool ctrl, bool alt); + static QString ConstructStringFromShortcut(QKeySequence key); MysticQt::KeyboardShortcutManager::Group* GetCurrentGroup() const; void setVisible(bool visible) override; @@ -95,6 +92,5 @@ namespace EMStudio ShortcutReceiverDialog* mShortcutReceiverDialog; void contextMenuEvent(QContextMenuEvent* event) override; - void hideEvent(QHideEvent* event) override; }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp index 496b6b8e94..950b63ff26 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.cpp @@ -66,6 +66,7 @@ #include #include #include +#include AZ_PUSH_DISABLE_WARNING(4267, "-Wconversion") #include AZ_POP_DISABLE_WARNING @@ -508,14 +509,33 @@ namespace EMStudio mShortcutManager = new MysticQt::KeyboardShortcutManager(); // load the old shortcuts - QSettings shortcutSettings(AZStd::string(GetManager()->GetAppDataFolder() + "EMStudioKeyboardShortcuts.cfg").c_str(), QSettings::IniFormat, this); - mShortcutManager->Load(&shortcutSettings); + LoadKeyboardShortcuts(); // add the application mode group - const char* layoutGroupName = "Layouts"; - mShortcutManager->RegisterKeyboardShortcut("AnimGraph", layoutGroupName, Qt::Key_1, false, true, false); - mShortcutManager->RegisterKeyboardShortcut("Animation", layoutGroupName, Qt::Key_2, false, true, false); - mShortcutManager->RegisterKeyboardShortcut("Character", layoutGroupName, Qt::Key_3, false, true, false); + constexpr AZStd::string_view layoutGroupName = "Layouts"; + QAction* animGraphLayoutAction = new QAction( + "AnimGraph", + this); + animGraphLayoutAction->setShortcut(Qt::Key_1 | Qt::AltModifier); + mShortcutManager->RegisterKeyboardShortcut(animGraphLayoutAction, layoutGroupName, false); + connect(animGraphLayoutAction, &QAction::triggered, [this]{ mApplicationMode->setCurrentIndex(0); }); + addAction(animGraphLayoutAction); + + QAction* animationLayoutAction = new QAction( + "Animation", + this); + animationLayoutAction->setShortcut(Qt::Key_2 | Qt::AltModifier); + mShortcutManager->RegisterKeyboardShortcut(animationLayoutAction, layoutGroupName, false); + connect(animationLayoutAction, &QAction::triggered, [this]{ mApplicationMode->setCurrentIndex(1); }); + addAction(animationLayoutAction); + + QAction* characterLayoutAction = new QAction( + "Character", + this); + characterLayoutAction->setShortcut(Qt::Key_1 | Qt::AltModifier); + mShortcutManager->RegisterKeyboardShortcut(characterLayoutAction, layoutGroupName, false); + connect(characterLayoutAction, &QAction::triggered, [this]{ mApplicationMode->setCurrentIndex(2); }); + addAction(characterLayoutAction); EMotionFX::ActorEditorRequestBus::Handler::BusConnect(); @@ -1267,6 +1287,12 @@ namespace EMStudio mRecentActors.AddRecentFile(fileName.toUtf8().data()); } + void MainWindow::LoadKeyboardShortcuts() + { + QSettings shortcutSettings(AZStd::string(GetManager()->GetAppDataFolder() + "EMStudioKeyboardShortcuts.cfg").c_str(), QSettings::IniFormat, this); + mShortcutManager->Load(&shortcutSettings); + } + void MainWindow::LoadActor(const char* fileName, bool replaceCurrentScene) { // create the final command @@ -2577,41 +2603,6 @@ namespace EMStudio QTimer::singleShot(0, this, &MainWindow::RaiseFloatingWidgets); } - void MainWindow::keyPressEvent(QKeyEvent* event) - { - const char* layoutGroupName = "Layouts"; - const uint32 numLayouts = GetMainWindow()->GetNumLayouts(); - for (uint32 i = 0; i < numLayouts; ++i) - { - if (mShortcutManager->Check(event, GetLayoutName(i), layoutGroupName)) - { - mApplicationMode->setCurrentIndex(i); - event->accept(); - return; - } - } - - event->ignore(); - } - - - void MainWindow::keyReleaseEvent(QKeyEvent* event) - { - const char* layoutGroupName = "Layouts"; - const uint32 numLayouts = GetNumLayouts(); - for (uint32 i = 0; i < numLayouts; ++i) - { - if (mShortcutManager->Check(event, layoutGroupName, GetLayoutName(i))) - { - event->accept(); - return; - } - } - - event->ignore(); - } - - // get the name of the currently active layout const char* MainWindow::GetCurrentLayoutName() const { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h index 15edaef144..850715b23f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/MainWindow.h @@ -152,9 +152,6 @@ namespace EMStudio FileManager* GetFileManager() const { return mFileManager; } PreferencesWindow* GetPreferencesWindow() const { return mPreferencesWindow; } - void keyPressEvent(QKeyEvent* event) override; - void keyReleaseEvent(QKeyEvent* event) override; - uint32 GetNumLayouts() const { return mLayoutNames.GetLength(); } const char* GetLayoutName(uint32 index) const { return mLayoutNames[index].c_str(); } const char* GetCurrentLayoutName() const; @@ -168,6 +165,8 @@ namespace EMStudio void AddRecentActorFile(const QString& fileName); + void LoadKeyboardShortcuts(); + public slots: void OnAutosaveTimeOut(); void LoadLayoutAfterShow(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.cpp index 214ed68367..ffe29ed691 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/PluginManager.cpp @@ -136,7 +136,6 @@ namespace EMStudio mActivePlugins.push_back(newPlugin); newPlugin->Init(); - newPlugin->RegisterKeyboardShortcuts(); return newPlugin; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.cpp index 47b88b1fa2..8e4c1bce37 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.cpp @@ -1020,17 +1020,6 @@ namespace EMStudio } - // register keyboard shortcuts used for the render plugin - void RenderPlugin::RegisterKeyboardShortcuts() - { - MysticQt::KeyboardShortcutManager* shortcutManger = GetMainWindow()->GetShortcutManager(); - - shortcutManger->RegisterKeyboardShortcut("Show Selected", "Render Window", Qt::Key_S, false, false, true); - shortcutManger->RegisterKeyboardShortcut("Show Entire Scene", "Render Window", Qt::Key_A, false, false, true); - shortcutManger->RegisterKeyboardShortcut("Toggle Selection Box Rendering", "Render Window", Qt::Key_J, false, false, true); - } - - // find the trajectory path for a given actor instance MCommon::RenderUtil::TrajectoryTracePath* RenderPlugin::FindTracePath(EMotionFX::ActorInstance* actorInstance) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.h index 43f237b89e..7dab0a5f95 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderPlugin.h @@ -124,9 +124,6 @@ namespace EMStudio void ViewCloseup(bool selectedInstancesOnly = true, RenderWidget* renderWidget = nullptr, float flightTime = DEFAULT_FLIGHT_TIME); void SetSkipFollowCalcs(bool skipFollowCalcs); - // keyboard shortcuts - void RegisterKeyboardShortcuts() override; - // manipulators void ReInitTransformationManipulators(); MCommon::TransformationManipulator* GetActiveManipulator(MCommon::Camera* camera, int32 mousePosX, int32 mousePosY); @@ -177,6 +174,11 @@ namespace EMStudio void SaveRenderOptions(); void LoadRenderOptions(); + inline static constexpr AZStd::string_view s_renderWindowShortcutGroupName = "Render Window"; + inline static constexpr AZStd::string_view s_showSelectedShortcutName = "Show Selected"; + inline static constexpr AZStd::string_view s_showEntireSceneShortcutName = "Show Entire Scene"; + inline static constexpr AZStd::string_view s_toggleSelectionBoxRenderingShortcutName = "Toggle Selection Box Rendering"; + public slots: void SetManipulatorMode(RenderOptions::ManipulatorMode mode); void SetSelectionMode() { SetManipulatorMode(RenderOptions::ManipulatorMode::SELECT); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderViewWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderViewWidget.cpp index f6c44980fe..9abb05ea2c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderViewWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderViewWidget.cpp @@ -16,7 +16,9 @@ #include "../PreferencesWindow.h" #include #include +#include #include +#include #include @@ -156,8 +158,17 @@ namespace EMStudio cameraMenu->addSeparator(); cameraMenu->addAction("Reset Camera", [this]() { this->OnResetCamera(); }); - cameraMenu->addAction("Show Selected", this, &RenderViewWidget::OnShowSelected); - cameraMenu->addAction("Show Entire Scene", this, &RenderViewWidget::OnShowEntireScene); + + QAction* showSelectedAction = cameraMenu->addAction("Show Selected", this, &RenderViewWidget::OnShowSelected); + showSelectedAction->setShortcut(Qt::Key_S); + GetMainWindow()->GetShortcutManager()->RegisterKeyboardShortcut(showSelectedAction, RenderPlugin::s_renderWindowShortcutGroupName, true); + addAction(showSelectedAction); + + QAction* showEntireSceneAction = cameraMenu->addAction("Show Entire Scene", this, &RenderViewWidget::OnShowEntireScene); + showEntireSceneAction->setShortcut(Qt::Key_A); + GetMainWindow()->GetShortcutManager()->RegisterKeyboardShortcut(showEntireSceneAction, RenderPlugin::s_renderWindowShortcutGroupName, true); + addAction(showEntireSceneAction); + cameraMenu->addSeparator(); mFollowCharacterAction = cameraMenu->addAction(tr("Follow Character")); @@ -181,8 +192,30 @@ namespace EMStudio connect(m_manipulatorModes[RenderOptions::ROTATE], &QAction::triggered, mPlugin, &RenderPlugin::SetRotationMode); connect(m_manipulatorModes[RenderOptions::SCALE], &QAction::triggered, mPlugin, &RenderPlugin::SetScaleMode); + QAction* toggleSelectionBoxRendering = new QAction( + "Toggle Selection Box Rendering", + this + ); + toggleSelectionBoxRendering->setShortcut(Qt::Key_J); + GetMainWindow()->GetShortcutManager()->RegisterKeyboardShortcut(toggleSelectionBoxRendering, RenderPlugin::s_renderWindowShortcutGroupName, true); + connect(toggleSelectionBoxRendering, &QAction::triggered, this, [this] + { + mPlugin->GetRenderOptions()->SetRenderSelectionBox(mPlugin->GetRenderOptions()->GetRenderSelectionBox() ^ true); + }); + addAction(toggleSelectionBoxRendering); + + QAction* deleteSelectedActorInstance = new QAction( + "Delete Selected Actor Instance", + this + ); + deleteSelectedActorInstance->setShortcut(Qt::Key_Delete); + connect(deleteSelectedActorInstance, &QAction::triggered, []{ CommandSystem::RemoveSelectedActorInstances(); }); + addAction(deleteSelectedActorInstance); + Reset(); UpdateInterface(); + + GetMainWindow()->LoadKeyboardShortcuts(); } void RenderViewWidget::SetManipulatorMode(RenderOptions::ManipulatorMode mode) diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderViewWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderViewWidget.h index 33b648f9c9..3ef48d0749 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderViewWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderViewWidget.h @@ -43,6 +43,8 @@ namespace EMStudio RenderViewWidget(RenderPlugin* parentPlugin, QWidget* parentWidget); virtual ~RenderViewWidget(); + void CreateActions(); + enum ERenderFlag { RENDER_SOLID = 0, diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.cpp index 6218194fc6..5ca912ef71 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.cpp @@ -25,7 +25,6 @@ #include "../EMStudioManager.h" #include "../MainWindow.h" #include -#include namespace EMStudio @@ -76,7 +75,6 @@ namespace EMStudio delete mAxisFakeCamera; } - // start view closeup flight void RenderWidget::ViewCloseup(const MCore::AABB& aabb, float flightTime, uint32 viewCloseupWaiting) { @@ -726,72 +724,6 @@ namespace EMStudio } - // called when a key got pressed - void RenderWidget::OnKeyPressEvent(QWidget* renderWidget, QKeyEvent* event) - { - MCORE_UNUSED(renderWidget); - MysticQt::KeyboardShortcutManager* shortcutManger = GetMainWindow()->GetShortcutManager(); - - if (shortcutManger->Check(event, "Show Selected", "Render Window")) - { - mPlugin->ViewCloseup(true, this); - event->accept(); - return; - } - - if (shortcutManger->Check(event, "Show Entire Scene", "Render Window")) - { - mPlugin->ViewCloseup(false, this); - event->accept(); - return; - } - - if (shortcutManger->Check(event, "Toggle Selection Box Rendering", "Render Window")) - { - mPlugin->GetRenderOptions()->SetRenderSelectionBox(mPlugin->GetRenderOptions()->GetRenderSelectionBox() ^ true); - event->accept(); - return; - } - - if (event->key() == Qt::Key_Delete) - { - CommandSystem::RemoveSelectedActorInstances(); - event->accept(); - return; - } - - event->ignore(); - } - - - // called when a key got released - void RenderWidget::OnKeyReleaseEvent(QWidget* renderWidget, QKeyEvent* event) - { - MCORE_UNUSED(renderWidget); - MysticQt::KeyboardShortcutManager* shortcutManger = GetMainWindow()->GetShortcutManager(); - - if (shortcutManger->Check(event, "Show Selected", "Render Window")) - { - event->accept(); - return; - } - - if (shortcutManger->Check(event, "Show Entire Scene", "Render Window")) - { - event->accept(); - return; - } - - if (event->key() == Qt::Key_Delete) - { - event->accept(); - return; - } - - event->ignore(); - } - - // handles context menu events void RenderWidget::OnContextMenuEvent(QWidget* renderWidget, bool shiftPressed, bool altPressed, int32 localMouseX, int32 localMouseY, QPoint globalMousePos) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.h index f376f10f84..99c1c38f70 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/EMStudioSDK/Source/RenderPlugin/RenderWidget.h @@ -96,6 +96,8 @@ namespace EMStudio RenderWidget(RenderPlugin* renderPlugin, RenderViewWidget* viewWidget); virtual ~RenderWidget(); + void CreateActions(); + // main render callback virtual void Render() = 0; virtual void Update() = 0; @@ -132,8 +134,6 @@ namespace EMStudio void OnMousePressEvent(QWidget* renderWidget, QMouseEvent* event); void OnMouseReleaseEvent(QWidget* renderWidget, QMouseEvent* event); void OnWheelEvent(QWidget* renderWidget, QWheelEvent* event); - void OnKeyPressEvent(QWidget* renderWidget, QKeyEvent* event); - void OnKeyReleaseEvent(QWidget* renderWidget, QKeyEvent* event); void OnContextMenuEvent(QWidget* renderWidget, bool shiftPressed, bool altPressed, int32 localMouseX, int32 localMouseY, QPoint globalMousePos); protected: diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.h index 107869de33..c81d7c61ae 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/RenderPlugins/Source/OpenGLRender/GLWidget.h @@ -72,8 +72,6 @@ namespace EMStudio void mousePressEvent(QMouseEvent* event) { RenderWidget::OnMousePressEvent(this, event); } void mouseReleaseEvent(QMouseEvent* event) { RenderWidget::OnMouseReleaseEvent(this, event); } void wheelEvent(QWheelEvent* event) { RenderWidget::OnWheelEvent(this, event); } - void keyPressEvent(QKeyEvent* event) { RenderWidget::OnKeyPressEvent(this, event); } - void keyReleaseEvent(QKeyEvent* event) { RenderWidget::OnKeyReleaseEvent(this, event); } void focusInEvent(QFocusEvent* event); void focusOutEvent(QFocusEvent* event); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.cpp index 9cbd654393..f76f684ea5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.cpp @@ -99,7 +99,7 @@ namespace EMStudio } if (!m_pasteItems.empty()) { - m_pasteOperation = PasteOperation::Copy; + SetPasteOperation(PasteOperation::Copy); } } @@ -126,7 +126,7 @@ namespace EMStudio } if (!m_pasteItems.empty()) { - m_pasteOperation = PasteOperation::Cut; + SetPasteOperation(PasteOperation::Cut); } } @@ -168,8 +168,8 @@ namespace EMStudio } } - m_pasteOperation = PasteOperation::None; m_pasteItems.clear(); + SetPasteOperation(PasteOperation::None); } void AnimGraphActionManager::SetEntryState() @@ -443,6 +443,18 @@ namespace EMStudio } } + void AnimGraphActionManager::NavigateToParent() + { + const QModelIndex parentFocus = m_plugin->GetAnimGraphModel().GetParentFocus(); + if (parentFocus.isValid()) + { + QModelIndex newParentFocus = parentFocus.model()->parent(parentFocus); + if (newParentFocus.isValid()) + { + m_plugin->GetAnimGraphModel().Focus(newParentFocus); + } + } + } void AnimGraphActionManager::OpenReferencedAnimGraph(EMotionFX::AnimGraphReferenceNode* referenceNode) { @@ -678,4 +690,10 @@ namespace EMStudio GetCommandManager()->ExecuteCommandGroup(commandGroup, outResult); } } + + void AnimGraphActionManager::SetPasteOperation(PasteOperation newOperation) + { + m_pasteOperation = newOperation; + emit PasteStateChanged(); + } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.h index 30b520d2a5..9182272875 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphActionManager.h @@ -72,6 +72,9 @@ namespace EMStudio Bottom }; + signals: + void PasteStateChanged(); + public slots: void Copy(); void Cut(); @@ -95,6 +98,7 @@ namespace EMStudio void DeleteSelectedNodes(); void NavigateToNode(); + void NavigateToParent(); void OpenReferencedAnimGraph(EMotionFX::AnimGraphReferenceNode* referenceNode); @@ -126,5 +130,7 @@ namespace EMStudio AnimGraphPlugin* m_plugin; AZStd::vector m_pasteItems; PasteOperation m_pasteOperation; + + void SetPasteOperation(PasteOperation newOperation); }; } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.cpp index 2669153dfd..d9b77ccf89 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.cpp @@ -461,10 +461,7 @@ namespace EMStudio { m_actionFilter = actionFilter; - if (mViewWidget) - { - mViewWidget->UpdateSelection(); - } + emit ActionFilterChanged(); } const AnimGraphActionFilter& AnimGraphPlugin::GetActionFilter() const @@ -1408,33 +1405,6 @@ namespace EMStudio } - // register keyboard shortcuts used for the render plugin - void AnimGraphPlugin::RegisterKeyboardShortcuts() - { - MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - - shortcutManager->RegisterKeyboardShortcut("Fit Entire Graph", "Anim Graph Window", Qt::Key_A, false, false, true); - shortcutManager->RegisterKeyboardShortcut("Zoom On Selected Nodes", "Anim Graph Window", Qt::Key_Z, false, false, true); - - shortcutManager->RegisterKeyboardShortcut("Open Parent Node", "Anim Graph Window", Qt::Key_Up, false, false, true); - shortcutManager->RegisterKeyboardShortcut("Open Selected Node", "Anim Graph Window", Qt::Key_Down, false, false, true); - shortcutManager->RegisterKeyboardShortcut("History Back", "Anim Graph Window", Qt::Key_Left, false, false, true); - shortcutManager->RegisterKeyboardShortcut("History Forward", "Anim Graph Window", Qt::Key_Right, false, false, true); - - shortcutManager->RegisterKeyboardShortcut("Align Left", "Anim Graph Window", Qt::Key_L, true, false, true); - shortcutManager->RegisterKeyboardShortcut("Align Right", "Anim Graph Window", Qt::Key_R, true, false, true); - shortcutManager->RegisterKeyboardShortcut("Align Top", "Anim Graph Window", Qt::Key_T, true, false, true); - shortcutManager->RegisterKeyboardShortcut("Align Bottom", "Anim Graph Window", Qt::Key_B, true, false, true); - - shortcutManager->RegisterKeyboardShortcut("Cut", "Anim Graph Window", Qt::Key_X, true, false, true); - shortcutManager->RegisterKeyboardShortcut("Copy", "Anim Graph Window", Qt::Key_C, true, false, true); - shortcutManager->RegisterKeyboardShortcut("Paste", "Anim Graph Window", Qt::Key_V, true, false, true); - shortcutManager->RegisterKeyboardShortcut("Select All", "Anim Graph Window", Qt::Key_A, true, false, true); - shortcutManager->RegisterKeyboardShortcut("Unselect All", "Anim Graph Window", Qt::Key_D, true, false, true); - shortcutManager->RegisterKeyboardShortcut("Delete Selected Nodes", "Anim Graph Window", Qt::Key_Delete, false, false, true); - } - - // double clicked a node history item in the timeview plugin void AnimGraphPlugin::OnDoubleClickedRecorderNodeHistoryItem(EMotionFX::Recorder::ActorInstanceData* actorInstanceData, EMotionFX::Recorder::NodeHistoryItem* historyItem) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.h index c1e2004aae..cb8e015429 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.h @@ -49,7 +49,6 @@ namespace EMotionFX class AnimGraphObjectFactory; } - namespace EMStudio { // forward declarations @@ -151,8 +150,6 @@ namespace EMStudio void LoadOptions(); void SaveOptions(); - void RegisterKeyboardShortcuts() override; - bool CheckIfCanCreateObject(EMotionFX::AnimGraphObject* parentObject, const EMotionFX::AnimGraphObject* object, EMotionFX::AnimGraphObject::ECategory category) const; void ProcessFrame(float timePassedInSeconds) override; @@ -171,6 +168,27 @@ namespace EMStudio /// Is the given anim graph running on any selected actor instance? bool IsAnimGraphActive(EMotionFX::AnimGraph* animGraph) const; + inline static constexpr AZStd::string_view s_animGraphWindowShortcutGroupName = "Anim Graph Window"; + inline static constexpr AZStd::string_view s_fitEntireGraphShortcutName = "Fit Entire Graph"; + inline static constexpr AZStd::string_view s_zoomOnSelectedNodesShortcutName = "Zoom On Selected Nodes"; + inline static constexpr AZStd::string_view s_openParentNodeShortcutName = "Open Parent Node"; + inline static constexpr AZStd::string_view s_openSelectedNodeShortcutName = "Open Selected Node"; + inline static constexpr AZStd::string_view s_historyBackShortcutName = "History Back"; + inline static constexpr AZStd::string_view s_historyForwardShortcutName = "History Forward"; + inline static constexpr AZStd::string_view s_alignLeftShortcutName = "Align Left"; + inline static constexpr AZStd::string_view s_alignRightShortcutName = "Align Right"; + inline static constexpr AZStd::string_view s_alignTopShortcutName = "Align Top"; + inline static constexpr AZStd::string_view s_alignBottomShortcutName = "Align Bottom"; + inline static constexpr AZStd::string_view s_cutShortcutName = "Cut"; + inline static constexpr AZStd::string_view s_copyShortcutName = "Copy"; + inline static constexpr AZStd::string_view s_pasteShortcutName = "Paste"; + inline static constexpr AZStd::string_view s_selectAllShortcutName = "Select All"; + inline static constexpr AZStd::string_view s_unselectAllShortcutName = "Unselect All"; + inline static constexpr AZStd::string_view s_deleteSelectedNodesShortcutName = "Delete Selected Nodes"; + + signals: + void ActionFilterChanged(); + public slots: void OnFileOpen(); void OnFileSave(); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.cpp index 4203271b58..eccabd37b5 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.cpp @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -40,74 +41,298 @@ namespace EMStudio : QWidget(parentWidget) , m_parentPlugin(plugin) { - for (uint32 i = 0; i < NUM_OPTIONS; ++i) + EMotionFX::ActorEditorRequestBus::Handler::BusConnect(); + } + + void BlendGraphViewWidget::CreateActions() + { + MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); + + m_actions[SELECTION_ALIGNLEFT] = new QAction( + QIcon(":/EMotionFX/AlignLeft.svg"), + FromStdString(AnimGraphPlugin::s_alignLeftShortcutName), + this); + m_actions[SELECTION_ALIGNLEFT]->setShortcut(Qt::Key_L | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[SELECTION_ALIGNLEFT], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[SELECTION_ALIGNLEFT], &QAction::triggered, &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::AlignLeft); + + m_actions[SELECTION_ALIGNRIGHT] = new QAction( + QIcon(":/EMotionFX/AlignRight.svg"), + FromStdString(AnimGraphPlugin::s_alignRightShortcutName), + this); + m_actions[SELECTION_ALIGNRIGHT]->setShortcut(Qt::Key_R | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[SELECTION_ALIGNRIGHT], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[SELECTION_ALIGNRIGHT], &QAction::triggered, &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::AlignRight); + + m_actions[SELECTION_ALIGNTOP] = new QAction( + QIcon(":/EMotionFX/AlignTop.svg"), + FromStdString(AnimGraphPlugin::s_alignTopShortcutName), + this); + m_actions[SELECTION_ALIGNTOP]->setShortcut(Qt::Key_T | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[SELECTION_ALIGNTOP], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[SELECTION_ALIGNTOP], &QAction::triggered, &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::AlignTop); + + m_actions[SELECTION_ALIGNBOTTOM] = new QAction( + QIcon(":/EMotionFX/AlignBottom.svg"), + FromStdString(AnimGraphPlugin::s_alignBottomShortcutName), + this); + m_actions[SELECTION_ALIGNBOTTOM]->setShortcut(Qt::Key_B | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[SELECTION_ALIGNBOTTOM], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[SELECTION_ALIGNBOTTOM], &QAction::triggered, &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::AlignBottom); + + m_actions[SELECTION_SELECTALL] = new QAction( + FromStdString(AnimGraphPlugin::s_selectAllShortcutName), + this + ); + m_actions[SELECTION_SELECTALL]->setShortcut(Qt::Key_A | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[SELECTION_SELECTALL], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[SELECTION_SELECTALL], &QAction::triggered, [this] + { + NodeGraph* activeGraph = m_parentPlugin->GetGraphWidget()->GetActiveGraph(); + if (activeGraph) + { + activeGraph->SelectAllNodes(); + } + }); + + m_actions[SELECTION_UNSELECTALL] = new QAction( + FromStdString(AnimGraphPlugin::s_unselectAllShortcutName), + this + ); + m_actions[SELECTION_UNSELECTALL]->setShortcut(Qt::Key_D | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[SELECTION_UNSELECTALL], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[SELECTION_UNSELECTALL], &QAction::triggered, [this] + { + NodeGraph* activeGraph = m_parentPlugin->GetGraphWidget()->GetActiveGraph(); + if (activeGraph) + { + activeGraph->UnselectAllNodes(); + } + }); + + m_actions[FILE_NEW] = new QAction( + QIcon(":/EMotionFX/Plus.svg"), + tr("Create a new anim graph"), + this); + m_actions[FILE_NEW]->setObjectName("EMFX.BlendGraphViewWidget.NewButton"); + connect(m_actions[FILE_NEW], &QAction::triggered, this, &BlendGraphViewWidget::OnCreateAnimGraph); + + m_actions[FILE_OPEN] = new QAction( + tr("Open..."), + this); + connect(m_actions[FILE_OPEN], &QAction::triggered, m_parentPlugin, &AnimGraphPlugin::OnFileOpen); + + m_actions[FILE_SAVE] = new QAction( + tr("Save"), + this); + connect(m_actions[FILE_SAVE], &QAction::triggered, m_parentPlugin, &AnimGraphPlugin::OnFileSave); + + m_actions[FILE_SAVEAS] = new QAction( + tr("Save as..."), + this); + connect(m_actions[FILE_SAVEAS], &QAction::triggered, m_parentPlugin, &AnimGraphPlugin::OnFileSaveAs); + + m_actions[NAVIGATION_FORWARD] = new QAction( + QIcon(":/EMotionFX/Forward.svg"), + FromStdString(AnimGraphPlugin::s_historyForwardShortcutName), + this); + m_actions[NAVIGATION_FORWARD]->setShortcut(Qt::Key_Right); + shortcutManager->RegisterKeyboardShortcut(m_actions[NAVIGATION_FORWARD], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[NAVIGATION_FORWARD], &QAction::triggered, [this] + { + m_parentPlugin->GetNavigationHistory()->StepForward(); + UpdateNavigation(); + }); + + m_actions[NAVIGATION_BACK] = new QAction( + QIcon(":/EMotionFX/Backward.svg"), + FromStdString(AnimGraphPlugin::s_historyBackShortcutName), + this); + m_actions[NAVIGATION_BACK]->setShortcut(Qt::Key_Left); + shortcutManager->RegisterKeyboardShortcut(m_actions[NAVIGATION_BACK], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[NAVIGATION_BACK], &QAction::triggered, [this] + { + m_parentPlugin->GetNavigationHistory()->StepBackward(); + UpdateNavigation(); + }); + + m_actions[NAVIGATION_NAVPANETOGGLE] = new QAction( + QIcon(":/EMotionFX/List.svg"), + tr("Show/hide navigation pane"), + this); + connect(m_actions[NAVIGATION_NAVPANETOGGLE], &QAction::triggered, this, &BlendGraphViewWidget::ToggleNavigationPane); + + m_actions[NAVIGATION_OPEN_SELECTED] = new QAction( + FromStdString(AnimGraphPlugin::s_openSelectedNodeShortcutName), + this); + m_actions[NAVIGATION_OPEN_SELECTED]->setShortcut(Qt::Key_Down); + shortcutManager->RegisterKeyboardShortcut(m_actions[NAVIGATION_OPEN_SELECTED], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[NAVIGATION_OPEN_SELECTED], &QAction::triggered, &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::NavigateToNode); + + m_actions[NAVIGATION_TO_PARENT] = new QAction( + FromStdString(AnimGraphPlugin::s_openParentNodeShortcutName), + this); + m_actions[NAVIGATION_TO_PARENT]->setShortcut(Qt::Key_Up); + shortcutManager->RegisterKeyboardShortcut(m_actions[NAVIGATION_TO_PARENT], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[NAVIGATION_TO_PARENT], &QAction::triggered, &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::NavigateToParent); + + m_actions[NAVIGATION_FRAME_ALL] = new QAction( + QIcon(":/EMotionFX/ZoomSelected.svg"), + FromStdString(AnimGraphPlugin::s_fitEntireGraphShortcutName), + this); + m_actions[NAVIGATION_FRAME_ALL]->setShortcut(Qt::Key_A); + shortcutManager->RegisterKeyboardShortcut(m_actions[NAVIGATION_FRAME_ALL], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[NAVIGATION_FRAME_ALL], &QAction::triggered, this, &BlendGraphViewWidget::ZoomToAll); + + m_actions[NAVIGATION_ZOOMSELECTION] = new QAction( + QIcon(":/EMotionFX/ZoomSelected.svg"), + FromStdString(AnimGraphPlugin::s_zoomOnSelectedNodesShortcutName), + this); + m_actions[NAVIGATION_ZOOMSELECTION]->setShortcut(Qt::Key_Z); + shortcutManager->RegisterKeyboardShortcut(m_actions[NAVIGATION_ZOOMSELECTION], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[NAVIGATION_ZOOMSELECTION], &QAction::triggered, this, &BlendGraphViewWidget::ZoomSelected); + + m_actions[ACTIVATE_ANIMGRAPH] = new QAction( + QIcon(":/EMotionFX/PlayForward.svg"), + tr("Activate Animgraph/State"), + this); + connect(m_actions[ACTIVATE_ANIMGRAPH], &QAction::triggered, &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::ActivateAnimGraph); + + m_actions[VISUALIZATION_PLAYSPEEDS] = new QAction( + tr("Display Play Speeds"), + this); + m_actions[VISUALIZATION_PLAYSPEEDS]->setCheckable(true); + connect(m_actions[VISUALIZATION_PLAYSPEEDS], &QAction::triggered, this, &BlendGraphViewWidget::OnDisplayPlaySpeeds); + + m_actions[VISUALIZATION_GLOBALWEIGHTS] = new QAction( + tr("Display Global Weights"), + this); + m_actions[VISUALIZATION_GLOBALWEIGHTS]->setCheckable(true); + connect(m_actions[VISUALIZATION_GLOBALWEIGHTS], &QAction::triggered, this, &BlendGraphViewWidget::OnDisplayGlobalWeights); + + m_actions[VISUALIZATION_SYNCSTATUS] = new QAction( + tr("Display Sync Status"), + this); + m_actions[VISUALIZATION_SYNCSTATUS]->setCheckable(true); + connect(m_actions[VISUALIZATION_SYNCSTATUS], &QAction::triggered, this, &BlendGraphViewWidget::OnDisplaySyncStatus); + + m_actions[VISUALIZATION_PLAYPOSITIONS] = new QAction( + tr("Display Play Positions"), + this); + m_actions[VISUALIZATION_PLAYPOSITIONS]->setCheckable(true); + connect(m_actions[VISUALIZATION_PLAYPOSITIONS], &QAction::triggered, this, &BlendGraphViewWidget::OnDisplayPlayPositions); + + m_actions[EDIT_CUT] = new QAction( + FromStdString(AnimGraphPlugin::s_cutShortcutName), + this + ); + m_actions[EDIT_CUT]->setShortcut(Qt::Key_X | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[EDIT_CUT], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[EDIT_CUT], &QAction::triggered, this, [this] + { + m_parentPlugin->GetActionManager().Cut(); + }); + + m_actions[EDIT_COPY] = new QAction( + FromStdString(AnimGraphPlugin::s_copyShortcutName), + this + ); + m_actions[EDIT_COPY]->setShortcut(Qt::Key_C | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[EDIT_COPY], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[EDIT_COPY], &QAction::triggered, this, [this] + { + m_parentPlugin->GetActionManager().Copy(); + }); + + m_actions[EDIT_PASTE] = new QAction( + FromStdString(AnimGraphPlugin::s_pasteShortcutName), + this + ); + m_actions[EDIT_PASTE]->setShortcut(Qt::Key_V | Qt::ControlModifier); + shortcutManager->RegisterKeyboardShortcut(m_actions[EDIT_PASTE], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[EDIT_PASTE], &QAction::triggered, this, [this] + { + const BlendGraphWidget* graphWidget = m_parentPlugin->GetGraphWidget(); + const NodeGraph* activeGraph = graphWidget->GetActiveGraph(); + if (!activeGraph) + { + return; + } + const QPoint pastePosition = graphWidget->underMouse() + ? graphWidget->SnapLocalToGrid(graphWidget->LocalToGlobal(graphWidget->mapFromGlobal(QCursor::pos()))) + : graphWidget->SnapLocalToGrid(graphWidget->LocalToGlobal(graphWidget->rect().center())); + m_parentPlugin->GetActionManager().Paste(activeGraph->GetModelIndex(), pastePosition); + }); + + m_actions[EDIT_DELETE] = new QAction( + FromStdString(AnimGraphPlugin::s_deleteSelectedNodesShortcutName), + this + ); + m_actions[EDIT_DELETE]->setShortcut(Qt::Key_Delete); + shortcutManager->RegisterKeyboardShortcut(m_actions[EDIT_DELETE], AnimGraphPlugin::s_animGraphWindowShortcutGroupName, true); + connect(m_actions[EDIT_DELETE], &QAction::triggered, this, [this] { - m_actions[i] = nullptr; + m_parentPlugin->GetGraphWidget()->DeleteSelectedItems(); + }); + + for (QAction* action : m_actions) + { + addAction(action); } - EMotionFX::ActorEditorRequestBus::Handler::BusConnect(); + GetMainWindow()->LoadKeyboardShortcuts(); } QToolBar* BlendGraphViewWidget::CreateTopToolBar() { QToolBar* toolBar = new QToolBar(this); toolBar->setObjectName("EMFX.BlendGraphViewWidget.TopToolBar"); - // Create new anim graph - { - QAction* action = toolBar->addAction(QIcon(":/EMotionFX/Plus.svg"), - tr("Create a new anim graph"), - this, &BlendGraphViewWidget::OnCreateAnimGraph); - action->setObjectName("EMFX.BlendGraphViewWidget.NewButton"); - - //action->setShortcut(QKeySequence::New); - m_actions[FILE_NEW] = action; - } + + toolBar->addAction(m_actions[FILE_NEW]); // Open anim graph { - QAction* action = toolBar->addAction( + m_openMenu = new QMenu(this); + connect(m_openMenu, &QMenu::aboutToShow, this, &BlendGraphViewWidget::BuildOpenMenu); + + QAction* action = new QAction( QIcon(":/EMotionFX/Open.svg"), - tr("Open anim graph asset")); - m_actions[FILE_OPEN] = action; + tr("Open")); + action->setMenu(m_openMenu); - QToolButton* toolButton = qobject_cast(toolBar->widgetForAction(action)); - AZ_Assert(toolButton, "The action widget must be a tool button."); - toolButton->setPopupMode(QToolButton::InstantPopup); + QToolButton* button = new QToolButton(); + button->setDefaultAction(action); + button->setPopupMode(QToolButton::InstantPopup); - m_openMenu = new QMenu(toolBar); - action->setMenu(m_openMenu); - BuildOpenMenu(); - connect(m_openMenu, &QMenu::aboutToShow, this, &BlendGraphViewWidget::BuildOpenMenu); + toolBar->addWidget(button); } + // Save anim graph { - QAction* saveMenuAction = toolBar->addAction( + QMenu* contextMenu = new QMenu(toolBar); + contextMenu->addAction(m_actions[FILE_SAVE]); + contextMenu->addAction(m_actions[FILE_SAVEAS]); + + QAction* saveMenuAction = new QAction( QIcon(":/EMotionFX/Save.svg"), tr("Save anim graph")); + saveMenuAction->setMenu(contextMenu); - QToolButton* toolButton = qobject_cast(toolBar->widgetForAction(saveMenuAction)); - AZ_Assert(toolButton, "The action widget must be a tool button."); - toolButton->setPopupMode(QToolButton::InstantPopup); - - QMenu* contextMenu = new QMenu(toolBar); - - m_actions[FILE_SAVE] = contextMenu->addAction(tr("Save"), m_parentPlugin, &AnimGraphPlugin::OnFileSave); - m_actions[FILE_SAVEAS] = contextMenu->addAction(tr("Save as..."), m_parentPlugin, &AnimGraphPlugin::OnFileSaveAs); + QToolButton* button = new QToolButton(); + button->setDefaultAction(saveMenuAction); + button->setPopupMode(QToolButton::InstantPopup); - saveMenuAction->setMenu(contextMenu); + toolBar->addWidget(button); } toolBar->addSeparator(); - m_actions[ACTIVATE_ANIMGRAPH] = toolBar->addAction(QIcon(":/EMotionFX/PlayForward.svg"), - tr("Activate Animgraph/State"), - &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::ActivateAnimGraph); + toolBar->addAction(m_actions[ACTIVATE_ANIMGRAPH]); + toolBar->addSeparator(); - m_actions[SELECTION_ZOOMSELECTION] = toolBar->addAction(QIcon(":/EMotionFX/ZoomSelected.svg"), - tr("Zoom Selection"), - this, &BlendGraphViewWidget::ZoomSelected); + toolBar->addAction(m_actions[NAVIGATION_ZOOMSELECTION]); // Visualization options { @@ -121,15 +346,10 @@ namespace EMStudio QMenu* contextMenu = new QMenu(toolBar); - m_actions[VISUALIZATION_PLAYSPEEDS] = contextMenu->addAction(tr("Display Play Speeds"), this, &BlendGraphViewWidget::OnDisplayPlaySpeeds); - m_actions[VISUALIZATION_GLOBALWEIGHTS] = contextMenu->addAction(tr("Display Global Weights"), this, &BlendGraphViewWidget::OnDisplayGlobalWeights); - m_actions[VISUALIZATION_SYNCSTATUS] = contextMenu->addAction(tr("Display Sync Status"), this, &BlendGraphViewWidget::OnDisplaySyncStatus); - m_actions[VISUALIZATION_PLAYPOSITIONS] = contextMenu->addAction(tr("Display Play Positions"), this, &BlendGraphViewWidget::OnDisplayPlayPositions); - - m_actions[VISUALIZATION_PLAYSPEEDS]->setCheckable(true); - m_actions[VISUALIZATION_GLOBALWEIGHTS]->setCheckable(true); - m_actions[VISUALIZATION_SYNCSTATUS]->setCheckable(true); - m_actions[VISUALIZATION_PLAYPOSITIONS]->setCheckable(true); + contextMenu->addAction(m_actions[VISUALIZATION_PLAYSPEEDS]); + contextMenu->addAction(m_actions[VISUALIZATION_GLOBALWEIGHTS]); + contextMenu->addAction(m_actions[VISUALIZATION_SYNCSTATUS]); + contextMenu->addAction(m_actions[VISUALIZATION_PLAYPOSITIONS]); menuAction->setMenu(contextMenu); } @@ -137,21 +357,10 @@ namespace EMStudio toolBar->addSeparator(); // Alignment Options - m_actions[SELECTION_ALIGNLEFT] = toolBar->addAction(QIcon(":/EMotionFX/AlignLeft.svg"), - tr("Align left"), - &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::AlignLeft); - - m_actions[SELECTION_ALIGNRIGHT] = toolBar->addAction(QIcon(":/EMotionFX/AlignRight.svg"), - tr("Align right"), - &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::AlignRight); - - m_actions[SELECTION_ALIGNTOP] = toolBar->addAction(QIcon(":/EMotionFX/AlignTop.svg"), - tr("Align top"), - &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::AlignTop); - - m_actions[SELECTION_ALIGNBOTTOM] = toolBar->addAction(QIcon(":/EMotionFX/AlignBottom.svg"), - tr("Align bottom"), - &m_parentPlugin->GetActionManager(), &AnimGraphActionManager::AlignBottom); + toolBar->addAction(m_actions[SELECTION_ALIGNLEFT]); + toolBar->addAction(m_actions[SELECTION_ALIGNRIGHT]); + toolBar->addAction(m_actions[SELECTION_ALIGNTOP]); + toolBar->addAction(m_actions[SELECTION_ALIGNBOTTOM]); return toolBar; } @@ -160,27 +369,15 @@ namespace EMStudio { QToolBar* toolBar = new QToolBar(this); - m_actions[NAVIGATION_BACK] = toolBar->addAction(QIcon(":/EMotionFX/Backward.svg"), - tr("Back"), - this, [=] { - m_parentPlugin->GetNavigationHistory()->StepBackward(); - UpdateNavigation(); - }); + toolBar->addAction(m_actions[NAVIGATION_BACK]); - m_actions[NAVIGATION_FORWARD] = toolBar->addAction(QIcon(":/EMotionFX/Forward.svg"), - tr("Forward"), - this, [=] { - m_parentPlugin->GetNavigationHistory()->StepForward(); - UpdateNavigation(); - }); + toolBar->addAction(m_actions[NAVIGATION_FORWARD]); mNavigationLink = new NavigationLinkWidget(m_parentPlugin, this); mNavigationLink->setMinimumHeight(28); toolBar->addWidget(mNavigationLink); - m_actions[NAVIGATION_NAVPANETOGGLE] = toolBar->addAction(QIcon(":/EMotionFX/List.svg"), - tr("Show/hide navigation pane"), - this, &BlendGraphViewWidget::ToggleNavigationPane); + toolBar->addAction(m_actions[NAVIGATION_NAVPANETOGGLE]); return toolBar; } @@ -188,8 +385,11 @@ namespace EMStudio void BlendGraphViewWidget::Init(BlendGraphWidget* blendGraphWidget) { connect(&m_parentPlugin->GetAnimGraphModel(), &AnimGraphModel::FocusChanged, this, &BlendGraphViewWidget::OnFocusChanged); - connect(&m_parentPlugin->GetAnimGraphModel().GetSelectionModel(), &QItemSelectionModel::selectionChanged, this, &BlendGraphViewWidget::UpdateSelection); + connect(&m_parentPlugin->GetAnimGraphModel().GetSelectionModel(), &QItemSelectionModel::selectionChanged, this, &BlendGraphViewWidget::UpdateEnabledActions); connect(m_parentPlugin->GetNavigationHistory(), &NavigationHistory::ChangedSteppingLimits, this, &BlendGraphViewWidget::UpdateNavigation); + connect(m_parentPlugin->GetGraphWidget(), &NodeGraphWidget::ActiveGraphChanged, this, &BlendGraphViewWidget::UpdateEnabledActions); + connect(m_parentPlugin, &AnimGraphPlugin::ActionFilterChanged, this, &BlendGraphViewWidget::UpdateEnabledActions); + connect(&m_parentPlugin->GetActionManager(), &AnimGraphActionManager::PasteStateChanged, this, &BlendGraphViewWidget::UpdateEnabledActions); // create the vertical layout with the menu and the graph widget as entries QVBoxLayout* verticalLayout = new QVBoxLayout(this); @@ -198,6 +398,7 @@ namespace EMStudio verticalLayout->setMargin(2); // Create toolbars + CreateActions(); verticalLayout->addWidget(CreateTopToolBar()); verticalLayout->addWidget(CreateNavigationToolBar()); @@ -217,7 +418,7 @@ namespace EMStudio UpdateNavigation(); UpdateAnimGraphOptions(); - UpdateSelection(); + UpdateEnabledActions(); } BlendGraphViewWidget::~BlendGraphViewWidget() @@ -252,47 +453,35 @@ namespace EMStudio } } - void BlendGraphViewWidget::UpdateSelection() + void BlendGraphViewWidget::UpdateEnabledActions() { // do we have any selection? const bool anySelection = m_parentPlugin->GetAnimGraphModel().GetSelectionModel().hasSelection(); - SetOptionEnabled(SELECTION_ZOOMSELECTION, anySelection); - - QModelIndex firstSelectedNode; - bool atLeastTwoNodes = false; - const QModelIndexList selectedIndexes = m_parentPlugin->GetAnimGraphModel().GetSelectionModel().selectedRows(); - for (const QModelIndex& selected : selectedIndexes) - { - const AnimGraphModel::ModelItemType itemType = selected.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value(); - if (itemType == AnimGraphModel::ModelItemType::NODE) - { - if (firstSelectedNode.isValid()) - { - atLeastTwoNodes = true; - break; - } - else - { - firstSelectedNode = selected; - } - } - } + SetOptionEnabled(NAVIGATION_ZOOMSELECTION, anySelection); - if (m_parentPlugin->GetActionFilter().m_editNodes && - atLeastTwoNodes) - { - SetOptionEnabled(SELECTION_ALIGNLEFT, true); - SetOptionEnabled(SELECTION_ALIGNRIGHT, true); - SetOptionEnabled(SELECTION_ALIGNTOP, true); - SetOptionEnabled(SELECTION_ALIGNBOTTOM, true); - } - else + const auto isNodeSelected = [](const QModelIndex& index) { - SetOptionEnabled(SELECTION_ALIGNLEFT, false); - SetOptionEnabled(SELECTION_ALIGNRIGHT, false); - SetOptionEnabled(SELECTION_ALIGNTOP, false); - SetOptionEnabled(SELECTION_ALIGNBOTTOM, false); - } + return index.isValid() + && index.data(AnimGraphModel::ROLE_MODEL_ITEM_TYPE).value() == AnimGraphModel::ModelItemType::NODE; + }; + const QModelIndexList selectedIndexes = m_parentPlugin->GetAnimGraphModel().GetSelectionModel().selectedRows(); + const auto firstSelectedNode = AZStd::find_if(selectedIndexes.begin(), selectedIndexes.end(), isNodeSelected); + const auto secondSelectedNode = AZStd::find_if(firstSelectedNode, selectedIndexes.end(), isNodeSelected); + const bool atLeastTwoNodes = secondSelectedNode != selectedIndexes.end(); + + const bool enableAlignActions = m_parentPlugin->GetActionFilter().m_editNodes && atLeastTwoNodes; + SetOptionEnabled(SELECTION_ALIGNLEFT, enableAlignActions); + SetOptionEnabled(SELECTION_ALIGNRIGHT, enableAlignActions); + SetOptionEnabled(SELECTION_ALIGNTOP, enableAlignActions); + SetOptionEnabled(SELECTION_ALIGNBOTTOM, enableAlignActions); + + const bool isEditable = m_parentPlugin->GetGraphWidget()->GetActiveGraph() && !m_parentPlugin->GetGraphWidget()->GetActiveGraph()->IsInReferencedGraph(); + const AnimGraphActionFilter& actionFilter = m_parentPlugin->GetActionFilter(); + + SetOptionEnabled(EDIT_CUT, actionFilter.m_copyAndPaste && anySelection && isEditable); + SetOptionEnabled(EDIT_COPY, actionFilter.m_copyAndPaste && anySelection); + SetOptionEnabled(EDIT_PASTE, actionFilter.m_copyAndPaste && isEditable && m_parentPlugin->GetActionManager().GetIsReadyForPaste()); + SetOptionEnabled(EDIT_DELETE, actionFilter.m_copyAndPaste && anySelection && isEditable); } AnimGraphNodeWidget* BlendGraphViewWidget::GetWidgetForNode(const EMotionFX::AnimGraphNode* node) @@ -375,19 +564,17 @@ namespace EMStudio void BlendGraphViewWidget::SetOptionFlag(EOptionFlag option, bool isEnabled) { - const uint32 optionIndex = (uint32)option; - if (m_actions[optionIndex]) + if (m_actions[option]) { - m_actions[optionIndex]->setChecked(isEnabled); + m_actions[option]->setChecked(isEnabled); } } void BlendGraphViewWidget::SetOptionEnabled(EOptionFlag option, bool isEnabled) { - const uint32 optionIndex = (uint32)option; - if (m_actions[optionIndex]) + if (m_actions[option]) { - m_actions[optionIndex]->setEnabled(isEnabled); + m_actions[option]->setEnabled(isEnabled); } } @@ -395,8 +582,7 @@ namespace EMStudio { m_openMenu->clear(); - m_actions[FILE_OPEN] = m_openMenu->addAction(tr("Open...")); - connect(m_actions[FILE_OPEN], &QAction::triggered, m_parentPlugin, &AnimGraphPlugin::OnFileOpen); + m_openMenu->addAction(m_actions[FILE_OPEN]); const uint32 numAnimGraphs = EMotionFX::GetAnimGraphManager().GetNumAnimGraphs(); if (numAnimGraphs > 0) @@ -521,6 +707,19 @@ namespace EMStudio } } + void BlendGraphViewWidget::ZoomToAll() + { + BlendGraphWidget* blendGraphWidget = m_parentPlugin->GetGraphWidget(); + if (blendGraphWidget) + { + NodeGraph* nodeGraph = blendGraphWidget->GetActiveGraph(); + if (nodeGraph) + { + nodeGraph->FitGraphOnScreen(geometry().width(), geometry().height(), blendGraphWidget->GetMousePos()); + } + } + } + void BlendGraphViewWidget::OnActivateState() { // Transition to the selected state. @@ -546,7 +745,6 @@ namespace EMStudio } } - void BlendGraphViewWidget::NavigateToRoot() { const QModelIndex nodeModelIndex = m_parentPlugin->GetGraphWidget()->GetActiveGraph()->GetModelIndex(); @@ -556,20 +754,6 @@ namespace EMStudio } } - - void BlendGraphViewWidget::NavigateToParent() - { - const QModelIndex parentFocus = m_parentPlugin->GetAnimGraphModel().GetParentFocus(); - if (parentFocus.isValid()) - { - QModelIndex newParentFocus = parentFocus.model()->parent(parentFocus); - if (newParentFocus.isValid()) - { - m_parentPlugin->GetAnimGraphModel().Focus(newParentFocus); - } - } - } - void BlendGraphViewWidget::ToggleNavigationPane() { QList sizes = m_viewportSplitter->sizes(); @@ -588,16 +772,6 @@ namespace EMStudio m_viewportSplitter->setSizes(sizes); } - void BlendGraphViewWidget::NavigateToNode() - { - const QModelIndexList currentModelIndexes = m_parentPlugin->GetAnimGraphModel().GetSelectionModel().selectedRows(); - if (!currentModelIndexes.empty()) - { - const QModelIndex currentModelIndex = currentModelIndexes.front(); - m_parentPlugin->GetAnimGraphModel().Focus(currentModelIndex); - } - } - // toggle playspeed viz void BlendGraphViewWidget::OnDisplayPlaySpeeds() { @@ -638,36 +812,4 @@ namespace EMStudio EMotionFX::AnimGraphEditorNotificationBus::Broadcast(&EMotionFX::AnimGraphEditorNotificationBus::Events::OnShow); } - void BlendGraphViewWidget::keyPressEvent(QKeyEvent* event) - { - switch (event->key()) - { - case Qt::Key_Backspace: - { - m_parentPlugin->GetNavigationHistory()->StepBackward(); - event->accept(); - break; - } - - default: - event->ignore(); - } - } - - - // on key release - void BlendGraphViewWidget::keyReleaseEvent(QKeyEvent* event) - { - switch (event->key()) - { - case Qt::Key_Backspace: - { - event->accept(); - break; - } - - default: - event->ignore(); - } - } } // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.h index dbc200856a..196fadb115 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphViewWidget.h @@ -53,25 +53,32 @@ namespace EMStudio public: enum EOptionFlag { - SELECTION_ALIGNLEFT = 0, - SELECTION_ALIGNRIGHT = 1, - SELECTION_ALIGNTOP = 2, - SELECTION_ALIGNBOTTOM = 3, - FILE_NEW = 4, - FILE_OPENFILE = 5, - FILE_OPEN = 6, - FILE_SAVE = 7, - FILE_SAVEAS = 8, - NAVIGATION_FORWARD = 9, - NAVIGATION_BACK = 10, - NAVIGATION_NAVPANETOGGLE = 11, - SELECTION_ZOOMSELECTION = 12, - ACTIVATE_ANIMGRAPH = 13, - WINDOWS_NODEGROUPWINDOW = 14, - VISUALIZATION_PLAYSPEEDS = 15, - VISUALIZATION_GLOBALWEIGHTS = 16, - VISUALIZATION_SYNCSTATUS = 17, - VISUALIZATION_PLAYPOSITIONS = 18, + SELECTION_ALIGNLEFT, + SELECTION_ALIGNRIGHT, + SELECTION_ALIGNTOP, + SELECTION_ALIGNBOTTOM, + SELECTION_SELECTALL, + SELECTION_UNSELECTALL, + FILE_NEW, + FILE_OPEN, + FILE_SAVE, + FILE_SAVEAS, + NAVIGATION_FORWARD, + NAVIGATION_BACK, + NAVIGATION_NAVPANETOGGLE, + NAVIGATION_OPEN_SELECTED, + NAVIGATION_TO_PARENT, + NAVIGATION_FRAME_ALL, + NAVIGATION_ZOOMSELECTION, + ACTIVATE_ANIMGRAPH, + VISUALIZATION_PLAYSPEEDS, + VISUALIZATION_GLOBALWEIGHTS, + VISUALIZATION_SYNCSTATUS, + VISUALIZATION_PLAYPOSITIONS, + EDIT_CUT, + EDIT_COPY, + EDIT_PASTE, + EDIT_DELETE, NUM_OPTIONS //automatically gets the next number assigned }; @@ -85,13 +92,12 @@ namespace EMStudio void Init(BlendGraphWidget* blendGraphWidget); void UpdateAnimGraphOptions(); - void UpdateSelection(); + void UpdateEnabledActions(); // If there is a specific widget to handle this node returns that. // Else, returns nullptr. AnimGraphNodeWidget* GetWidgetForNode(const EMotionFX::AnimGraphNode* node); - // Get Actions (used for testing purposes) QAction* GetAction(EOptionFlag option) const { return m_actions[option]; } public slots: @@ -100,11 +106,10 @@ namespace EMStudio void OnCreateAnimGraph(); void NavigateToRoot(); - void NavigateToNode(); - void NavigateToParent(); void ToggleNavigationPane(); void ZoomSelected(); + void ZoomToAll(); void OnActivateState(); @@ -122,17 +127,15 @@ namespace EMStudio void showEvent(QShowEvent* showEvent); - void keyReleaseEvent(QKeyEvent* event) override; - void keyPressEvent(QKeyEvent* event) override; - private: + void CreateActions(); QToolBar* CreateTopToolBar(); QToolBar* CreateNavigationToolBar(); QMenuBar* m_menu = nullptr; QMenu* m_openMenu = nullptr; QHBoxLayout* m_toolbarLayout = nullptr; - QAction* m_actions[NUM_OPTIONS]; + AZStd::array m_actions{}; AnimGraphPlugin* m_parentPlugin = nullptr; NavigationLinkWidget* mNavigationLink = nullptr; QStackedWidget m_viewportStack; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp index 7cd5a2d849..623f9f94a9 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp @@ -71,12 +71,6 @@ namespace EMStudio } - // destructor - BlendGraphWidget::~BlendGraphWidget() - { - } - - // when dropping stuff in our window void BlendGraphWidget::dropEvent(QDropEvent* event) { @@ -1555,254 +1549,6 @@ namespace EMStudio } - // on keypress - void BlendGraphWidget::keyPressEvent(QKeyEvent* event) - { - MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - const AnimGraphActionFilter& actionFilter = mPlugin->GetActionFilter(); - - if (shortcutManager->Check(event, "Open Parent Node", "Anim Graph Window")) - { - const QModelIndex parentFocus = mPlugin->GetAnimGraphModel().GetParentFocus(); - if (parentFocus.isValid()) - { - QModelIndex newParentFocus = parentFocus.model()->parent(parentFocus); - if (newParentFocus.isValid()) - { - mPlugin->GetAnimGraphModel().Focus(newParentFocus); - } - } - event->accept(); - return; - } - - if (shortcutManager->Check(event, "Open Selected Node", "Anim Graph Window")) - { - mPlugin->GetActionManager().NavigateToNode(); - event->accept(); - return; - } - - if (shortcutManager->Check(event, "History Back", "Anim Graph Window")) - { - mPlugin->GetNavigationHistory()->StepBackward(); - event->accept(); - return; - } - - if (shortcutManager->Check(event, "History Forward", "Anim Graph Window")) - { - mPlugin->GetNavigationHistory()->StepForward(); - event->accept(); - return; - } - - if (mActiveGraph && - !mActiveGraph->IsInReferencedGraph()) - { - if (actionFilter.m_editNodes) - { - if (shortcutManager->Check(event, "Align Left", "Anim Graph Window")) - { - mPlugin->GetActionManager().AlignLeft(); - event->accept(); - return; - } - - if (shortcutManager->Check(event, "Align Right", "Anim Graph Window")) - { - mPlugin->GetActionManager().AlignRight(); - event->accept(); - return; - } - - if (shortcutManager->Check(event, "Align Top", "Anim Graph Window")) - { - mPlugin->GetActionManager().AlignTop(); - event->accept(); - return; - } - - if (shortcutManager->Check(event, "Align Bottom", "Anim Graph Window")) - { - mPlugin->GetActionManager().AlignBottom(); - event->accept(); - return; - } - } - - if (actionFilter.m_copyAndPaste && - shortcutManager->Check(event, "Cut", "Anim Graph Window")) - { - mPlugin->GetActionManager().Cut(); - event->accept(); - return; - } - } - - if (actionFilter.m_copyAndPaste) - { - if (shortcutManager->Check(event, "Copy", "Anim Graph Window")) - { - mPlugin->GetActionManager().Copy(); - event->accept(); - return; - } - - if (shortcutManager->Check(event, "Paste", "Anim Graph Window")) - { - if (mActiveGraph && !mActiveGraph->IsInReferencedGraph()) - { - if (mPlugin->GetActionManager().GetIsReadyForPaste()) - { - QModelIndex modelIndex = GetActiveGraph()->GetModelIndex(); - if (modelIndex.isValid()) - { - if (rect().contains(mapFromGlobal(QCursor::pos())) == false) - { - mPlugin->GetActionManager().Paste(modelIndex, GetMousePos()); - event->accept(); - } - } - } - } - return; - } - } - - if (shortcutManager->Check(event, "Select All", "Anim Graph Window")) - { - if (mActiveGraph) - { - mActiveGraph->SelectAllNodes(); - event->accept(); - } - return; - } - - if (shortcutManager->Check(event, "Unselect All", "Anim Graph Window")) - { - if (mActiveGraph) - { - mActiveGraph->UnselectAllNodes(); - event->accept(); - } - return; - } - - if (mActiveGraph && - actionFilter.m_delete && - !mActiveGraph->IsInReferencedGraph() && - shortcutManager->Check(event, "Delete Selected Nodes", "Anim Graph Window")) - { - DeleteSelectedItems(); - event->accept(); - return; - } - - return NodeGraphWidget::keyPressEvent(event); - } - - - // on key release - void BlendGraphWidget::keyReleaseEvent(QKeyEvent* event) - { - MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - const AnimGraphActionFilter& actionFilter = mPlugin->GetActionFilter(); - - if (shortcutManager->Check(event, "Open Parent Node", "Anim Graph Window")) - { - event->accept(); - return; - } - if (shortcutManager->Check(event, "Open Selected Node", "Anim Graph Window")) - { - event->accept(); - return; - } - if (shortcutManager->Check(event, "History Back", "Anim Graph Window")) - { - event->accept(); - return; - } - if (shortcutManager->Check(event, "History Forward", "Anim Graph Window")) - { - event->accept(); - return; - } - - if (mActiveGraph && !mActiveGraph->IsInReferencedGraph()) - { - if (actionFilter.m_editNodes) - { - if (shortcutManager->Check(event, "Align Left", "Anim Graph Window")) - { - event->accept(); - return; - } - if (shortcutManager->Check(event, "Align Right", "Anim Graph Window")) - { - event->accept(); - return; - } - if (shortcutManager->Check(event, "Align Top", "Anim Graph Window")) - { - event->accept(); - return; - } - if (shortcutManager->Check(event, "Align Bottom", "Anim Graph Window")) - { - event->accept(); - return; - } - } - - if (actionFilter.m_copyAndPaste && - shortcutManager->Check(event, "Cut", "Anim Graph Window")) - { - event->accept(); - return; - } - } - - if (actionFilter.m_copyAndPaste) - { - if (shortcutManager->Check(event, "Copy", "Anim Graph Window")) - { - event->accept(); - return; - } - if (mActiveGraph && !mActiveGraph->IsInReferencedGraph() && shortcutManager->Check(event, "Paste", "Anim Graph Window")) - { - event->accept(); - return; - } - } - - if (shortcutManager->Check(event, "Select All", "Anim Graph Window")) - { - event->accept(); - return; - } - if (shortcutManager->Check(event, "Unselect All", "Anim Graph Window")) - { - event->accept(); - return; - } - - if (mActiveGraph && - actionFilter.m_delete && - !mActiveGraph->IsInReferencedGraph() && - shortcutManager->Check(event, "Delete Selected Nodes", "Anim Graph Window")) - { - event->accept(); - return; - } - - return NodeGraphWidget::keyReleaseEvent(event); - } - - void BlendGraphWidget::OnRowsInserted(const QModelIndex& parent, int first, int last) { // Here we could be receiving connections, transitions or nodes being inserted into diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.h index f5c5d4a5ea..7453e4cc53 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.h @@ -45,7 +45,6 @@ namespace EMStudio public: BlendGraphWidget(AnimGraphPlugin* plugin, QWidget* parent); - ~BlendGraphWidget(); // overloaded bool CheckIfIsCreateConnectionValid(uint32 portNr, GraphNode* portNode, NodePort* port, bool isInputPort) override; @@ -120,8 +119,6 @@ namespace EMStudio void OnSelectionModelChanged(const QItemSelection& selected, const QItemSelection& deselected); private: - void keyReleaseEvent(QKeyEvent* event) override; - void keyPressEvent(QKeyEvent* event) override; EMotionFX::AnimGraphStateTransition* FindTransitionForConnection(NodeConnection* connection) const; EMotionFX::BlendTreeConnection* FindBlendTreeConnection(NodeConnection* connection) const; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ContextMenu.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ContextMenu.cpp index 8866ec678e..80603c37bf 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ContextMenu.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/ContextMenu.cpp @@ -183,17 +183,11 @@ namespace EMStudio if (graphNode == nullptr) { QMenu* menu = new QMenu(parentWidget); - if (actionFilter.m_copyAndPaste && actionManager.GetIsReadyForPaste()) - { - const QModelIndex modelIndex = nodeGraph->GetModelIndex(); - if (modelIndex.isValid()) - { - localMousePos = SnapLocalToGrid(LocalToGlobal(localMousePos)); - QAction* pasteAction = menu->addAction("Paste"); - connect(pasteAction, &QAction::triggered, [&actionManager, modelIndex, localMousePos]() { actionManager.Paste(modelIndex, localMousePos); }); - menu->addSeparator(); - } + if (actionFilter.m_copyAndPaste && actionManager.GetIsReadyForPaste() && nodeGraph->GetModelIndex().isValid()) + { + menu->addAction(viewWidget->GetAction(BlendGraphViewWidget::EDIT_PASTE)); + menu->addSeparator(); } if (actionFilter.m_createNodes) @@ -324,8 +318,7 @@ namespace EMStudio // we can only go to the selected node in case the selected node has a visual graph (state machine / blend tree) if (animGraphNode->GetHasVisualGraph()) { - QAction* goToNodeAction = menu->addAction("Open Selected Node"); - connect(goToNodeAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::NavigateToNode); + menu->addAction(viewWidget->GetAction(BlendGraphViewWidget::NAVIGATION_OPEN_SELECTED)); menu->addSeparator(); } @@ -360,20 +353,17 @@ namespace EMStudio if (!inReferenceGraph) { // cut and copy actions - QAction* cutAction = menu->addAction("Cut"); - connect(cutAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::Cut); + menu->addAction(viewWidget->GetAction(BlendGraphViewWidget::EDIT_CUT)); } - QAction* ccopyAction = menu->addAction("Copy"); - connect(ccopyAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::Copy); + menu->addAction(viewWidget->GetAction(BlendGraphViewWidget::EDIT_COPY)); menu->addSeparator(); } if (actionFilter.m_delete && !inReferenceGraph) { - QAction* removeNodeAction = menu->addAction("Delete Node"); - connect(removeNodeAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::DeleteSelectedNodes); + menu->addAction(viewWidget->GetAction(BlendGraphViewWidget::EDIT_DELETE)); menu->addSeparator(); } } @@ -403,22 +393,14 @@ namespace EMStudio if (actionFilter.m_editNodes && !inReferenceGraph) { - QAction* alignLeftAction = menu.addAction("Align Left"); - QAction* alignRightAction = menu.addAction("Align Right"); - QAction* alignTopAction = menu.addAction("Align Top"); - QAction* alignBottomAction = menu.addAction("Align Bottom"); - - - connect(alignLeftAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::AlignLeft); - connect(alignRightAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::AlignRight); - connect(alignTopAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::AlignTop); - connect(alignBottomAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::AlignBottom); - + menu.addAction(viewWidget->GetAction(BlendGraphViewWidget::SELECTION_ALIGNLEFT)); + menu.addAction(viewWidget->GetAction(BlendGraphViewWidget::SELECTION_ALIGNRIGHT)); + menu.addAction(viewWidget->GetAction(BlendGraphViewWidget::SELECTION_ALIGNTOP)); + menu.addAction(viewWidget->GetAction(BlendGraphViewWidget::SELECTION_ALIGNBOTTOM)); menu.addSeparator(); } - QAction* zoomSelectionAction = menu.addAction("Zoom Selection"); - connect(zoomSelectionAction, &QAction::triggered, viewWidget, &BlendGraphViewWidget::ZoomSelected); + menu.addAction(viewWidget->GetAction(BlendGraphViewWidget::NAVIGATION_ZOOMSELECTION)); menu.addSeparator(); @@ -494,12 +476,10 @@ namespace EMStudio if (!inReferenceGraph) { - QAction* cutAction = menu.addAction("Cut"); - connect(cutAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::Cut); + menu.addAction(viewWidget->GetAction(BlendGraphViewWidget::EDIT_CUT)); } - QAction* ccopyAction = menu.addAction("Copy"); - connect(ccopyAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::Copy); + menu.addAction(viewWidget->GetAction(BlendGraphViewWidget::EDIT_COPY)); } menu.addSeparator(); @@ -507,8 +487,7 @@ namespace EMStudio if (actionFilter.m_delete && !inReferenceGraph) { - QAction* removeNodesAction = menu.addAction("Delete Nodes"); - connect(removeNodesAction, &QAction::triggered, &actionManager, &AnimGraphActionManager::DeleteSelectedNodes); + menu.addAction(viewWidget->GetAction(BlendGraphViewWidget::EDIT_DELETE)); menu.addSeparator(); } @@ -526,4 +505,4 @@ namespace EMStudio } } } -} +} // namespace EMStudio diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraphWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraphWidget.cpp index eae890c69d..f102cc5d96 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraphWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraphWidget.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include @@ -155,6 +154,11 @@ namespace EMStudio // set the active graph void NodeGraphWidget::SetActiveGraph(NodeGraph* graph) { + if (mActiveGraph == graph) + { + return; + } + if (mActiveGraph) { mActiveGraph->StopCreateConnection(); @@ -165,6 +169,8 @@ namespace EMStudio mActiveGraph = graph; mMoveNode = nullptr; + + emit ActiveGraphChanged(); } @@ -322,7 +328,7 @@ namespace EMStudio // convert to a global position - QPoint NodeGraphWidget::LocalToGlobal(const QPoint& inPoint) + QPoint NodeGraphWidget::LocalToGlobal(const QPoint& inPoint) const { if (mActiveGraph) { @@ -334,7 +340,7 @@ namespace EMStudio // convert to a local position - QPoint NodeGraphWidget::GlobalToLocal(const QPoint& inPoint) + QPoint NodeGraphWidget::GlobalToLocal(const QPoint& inPoint) const { if (mActiveGraph) { @@ -345,7 +351,7 @@ namespace EMStudio } - QPoint NodeGraphWidget::SnapLocalToGrid(const QPoint& inPoint, uint32 cellSize) + QPoint NodeGraphWidget::SnapLocalToGrid(const QPoint& inPoint, uint32 cellSize) const { MCORE_UNUSED(cellSize); @@ -1491,45 +1497,9 @@ namespace EMStudio } } - MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - - if (shortcutManager->Check(event, "Fit Entire Graph", "Anim Graph Window")) - { - // zoom to fit the entire graph in view - if (mActiveGraph) - { - mActiveGraph->FitGraphOnScreen(geometry().width(), geometry().height(), GetMousePos()); - } - - event->accept(); - return; - } - - if (shortcutManager->Check(event, "Zoom On Selected Nodes", "Anim Graph Window")) - { - if (mActiveGraph) - { - // try zooming on the selection rect - QRect selectionRect = mActiveGraph->CalcRectFromSelection(true); - if (selectionRect.isEmpty() == false) - { - mActiveGraph->ZoomOnRect(selectionRect, geometry().width(), geometry().height()); - //update(); - } - else // zoom on the full scene - { - mActiveGraph->FitGraphOnScreen(geometry().width(), geometry().height(), GetMousePos()); - } - } - - event->accept(); - return; - } - event->ignore(); } - // on key release void NodeGraphWidget::keyReleaseEvent(QKeyEvent* event) { @@ -1552,20 +1522,6 @@ namespace EMStudio } } - MysticQt::KeyboardShortcutManager* shortcutManager = GetMainWindow()->GetShortcutManager(); - - if (shortcutManager->Check(event, "Fit Entire Graph", "Anim Graph Window")) - { - event->accept(); - return; - } - - if (shortcutManager->Check(event, "Zoom On Selected Nodes", "Anim Graph Window")) - { - event->accept(); - return; - } - event->ignore(); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraphWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraphWidget.h index 68e9f72209..9b8d8c6ace 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraphWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGraphWidget.h @@ -65,9 +65,9 @@ namespace EMStudio uint32 CalcNumSelectedNodes() const; - QPoint LocalToGlobal(const QPoint& inPoint); - QPoint GlobalToLocal(const QPoint& inPoint); - QPoint SnapLocalToGrid(const QPoint& inPoint, uint32 cellSize = 10); + QPoint LocalToGlobal(const QPoint& inPoint) const; + QPoint GlobalToLocal(const QPoint& inPoint) const; + QPoint SnapLocalToGrid(const QPoint& inPoint, uint32 cellSize = 10) const; void CalcSelectRect(QRect& outRect); @@ -106,6 +106,9 @@ namespace EMStudio const QString& GetTitleBarText() const { return m_titleBarText; } void SetTitleBarText(const QString& text) { m_titleBarText = text; } + signals: + void ActiveGraphChanged(); + protected: //virtual void paintEvent(QPaintEvent* event); void mouseMoveEvent(QMouseEvent* event) override; @@ -160,4 +163,4 @@ namespace EMStudio float m_borderOverwriteWidth; QString m_titleBarText; }; -} // namespace EMStudio +} // namespace EMStudio diff --git a/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp b/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp index 202feb3d18..0d44330b34 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp +++ b/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.cpp @@ -12,6 +12,8 @@ // include required headers #include "KeyboardShortcutManager.h" +#include +#include #include #include @@ -19,52 +21,27 @@ #include #include - namespace MysticQt { - // find action by name - KeyboardShortcutManager::Action* KeyboardShortcutManager::Group::FindActionByName(const char* actionName, bool local) const + void KeyboardShortcutManager::Group::RemoveAction(QAction* qaction, bool local) { - const uint32 numActions = mActions.GetLength(); - for (uint32 i = 0; i < numActions; ++i) + m_actions.erase(AZStd::find_if(begin(m_actions), end(m_actions), [&qaction, local](const AZStd::unique_ptr& action) { - if (mActions[i]->mLocal == local && mActions[i]->mName == actionName) - { - return mActions[i]; - } - } - - return nullptr; + return action->m_local == local && action->m_qaction == qaction; + })); } - // constructor - KeyboardShortcutManager::KeyboardShortcutManager() + KeyboardShortcutManager::Action* KeyboardShortcutManager::Group::FindActionByName(const QString& actionName, bool local) const { - } - - - // destructor - KeyboardShortcutManager::~KeyboardShortcutManager() - { - Clear(); - } - - - // get rid of all groups including their actions - void KeyboardShortcutManager::Clear() - { - // get rid of the groups - const uint32 numGroups = mGroups.GetLength(); - for (uint32 i = 0; i < numGroups; ++i) + const auto found = AZStd::find_if(begin(m_actions), end(m_actions), [&actionName, local](const AZStd::unique_ptr& action) { - delete mGroups[i]; - } + return action->m_local == local && action->m_qaction->text() == actionName; + }); - mGroups.Clear(); + return found != end(m_actions) ? found->get() : nullptr; } - - void KeyboardShortcutManager::RegisterKeyboardShortcut(const char* actionName, const char* groupName, int defaultKey, bool defaultCtrl, bool defaultAlt, bool local) + void KeyboardShortcutManager::RegisterKeyboardShortcut(QAction* qaction, AZStd::string_view groupName, bool local) { // find the group with the given name Group* group = FindGroupByName(groupName); @@ -72,188 +49,112 @@ namespace MysticQt // if there is no group with the given name, create it if (group == nullptr) { - group = new Group(groupName); - mGroups.Add(group); + m_groups.emplace_back(AZStd::make_unique(groupName)); + group = m_groups.back().get(); } // check if the action is already there to avoid adding it twice - Action* action = group->FindActionByName(actionName, local); + Action* action = group->FindActionByName(qaction->text(), local); if (action) { - action->mDefaultKey = defaultKey; - action->mDefaultCtrl = defaultCtrl; - action->mDefaultAlt = defaultAlt; + action->m_defaultKeySequence = qaction->shortcut(); return; } // create the new action and add it to the group - action = new Action(actionName, defaultKey, defaultCtrl, defaultAlt, local); - group->AddAction(action); - } - + group->AddAction(AZStd::make_unique(qaction, local)); - // find the action with the given name in the given group - KeyboardShortcutManager::Action* KeyboardShortcutManager::FindAction(const char* actionName, const char* groupName) - { - const uint32 numGroups = mGroups.GetLength(); - - // first search global shortcuts - for (uint32 i = 0; i < numGroups; ++i) + QAction::connect(qaction, &QAction::destroyed, this, [this, groupName = AZStd::string(groupName), local](QObject* qaction) { - if (mGroups[i]->GetNameString() == groupName) - { - Action* action = mGroups[i]->FindActionByName(actionName, false); - if (action) - { - return action; - } - } - } - - // then local shortcuts - for (uint32 i = 0; i < numGroups; ++i) - { - if (mGroups[i]->GetNameString() == groupName) - { - Action* action = mGroups[i]->FindActionByName(actionName, true); - if (action) - { - return action; - } - } - } - - // failure, not found - return nullptr; + UnregisterKeyboardShortcut(static_cast(qaction), groupName, local); + }); } - - // find a group by name - KeyboardShortcutManager::Group* KeyboardShortcutManager::FindGroupByName(const char* groupName) const + void KeyboardShortcutManager::UnregisterKeyboardShortcut(QAction* qaction, AZStd::string_view groupName, bool local) { - // iterate through the groups and find the one with the given name - const uint32 numGroups = mGroups.GetLength(); - for (uint32 i = 0; i < numGroups; ++i) + Group* group = FindGroupByName(groupName); + + if (!group) { - if (mGroups[i]->GetNameString() == groupName) - { - return mGroups[i]; - } + return; } - // failure, a group with the given name hasn't been found - return nullptr; + group->RemoveAction(qaction, local); } - bool KeyboardShortcutManager::Check(QKeyEvent* event, const char* actionName, const char* groupName) + // find the action with the given name in the given group + KeyboardShortcutManager::Action* KeyboardShortcutManager::FindAction(const QString& actionName, AZStd::string_view groupName) const { - // find the corresponding action for the given strings - Action* action = FindAction(actionName, groupName); - if (action == nullptr) + const Group* group = FindGroupByName(groupName); + if (!group) { - //MCore::LogError("Action named '%s' in group '%s' not registered. Please register the shortcut before using it.", actionName, groupName); - return false; + return nullptr; } - const bool ctrlPressed = event->modifiers() & Qt::ControlModifier; - //const bool shiftPressed = event->modifiers() & Qt::ShiftModifier; - const bool altPressed = event->modifiers() & Qt::AltModifier; - - Group* group = FindGroupByName(groupName); - Action* conflictAction = FindShortcut(event->key(), ctrlPressed, altPressed, group); - - // check if they are equal, if yes this means they match - if (action == conflictAction) + Action* action = group->FindActionByName(actionName, false); + if (action) { - return true; + return action; } + return group->FindActionByName(actionName, true); + } - // check if the action and the key event are the same shortcut - /*if (event->key() == action->mKey && - ctrlPressed == action->mCtrl && - altPressed == action->mAlt) - return true;*/ - return false; + // find a group by name + KeyboardShortcutManager::Group* KeyboardShortcutManager::FindGroupByName(AZStd::string_view groupName) const + { + const auto found = AZStd::find_if(begin(m_groups), end(m_groups), [&groupName](const AZStd::unique_ptr& group) + { + return group->GetName() == groupName; + }); + return found != end(m_groups) ? found->get() : nullptr; } // find the correspondng group for the given action - KeyboardShortcutManager::Group* KeyboardShortcutManager::FindGroupForShortcut(Action* action) + KeyboardShortcutManager::Group* KeyboardShortcutManager::FindGroupForShortcut(Action* action) const { - // get the number of available groups - const uint32 numGroups = mGroups.GetLength(); - - // first check the global shortcuts - for (uint32 i = 0; i < numGroups; ++i) + const auto foundGroup = AZStd::find_if(begin(m_groups), end(m_groups), [action](const AZStd::unique_ptr& group) { - Group* group = mGroups[i]; - - // iterate through the actions and save them - const uint32 numActions = group->GetNumActions(); - for (uint32 j = 0; j < numActions; ++j) + const auto foundAction = AZStd::find_if(begin(group->GetActions()), end(group->GetActions()), [action](const AZStd::unique_ptr& actionInGroup) { - if (group->GetAction(j) == action) - { - return group; - } - } - } - - // failure, not found - return nullptr; + return action == actionInGroup.get(); + }); + return foundAction != end(group->GetActions()) ? foundAction->get() : nullptr; + }); + return foundGroup != end(m_groups) ? foundGroup->get() : nullptr; } - KeyboardShortcutManager::Action* KeyboardShortcutManager::FindShortcut(int key, bool ctrl, bool alt, Group* group) + KeyboardShortcutManager::Action* KeyboardShortcutManager::FindShortcut(QKeySequence keySequence, Group* group) const { - // get the number of available groups - const uint32 numGroups = mGroups.GetLength(); - - // first check the global shortcuts - for (uint32 i = 0; i < numGroups; ++i) + const auto findMatchingAction = [keySequence] (const Group* group, const bool local) { - Group* currentGroup = mGroups[i]; - - // iterate through the actions and save them - const uint32 numActions = currentGroup->GetNumActions(); - for (uint32 j = 0; j < numActions; ++j) + return AZStd::find_if(begin(group->GetActions()), end(group->GetActions()), [keySequence, local] (const AZStd::unique_ptr& action) { - // get the shortcut action - KeyboardShortcutManager::Action* action = currentGroup->GetAction(j); - if (action->mLocal) + if (action->m_local != local) { - continue; + return false; } - // check if the action and shortcut are the same - if (key == action->mKey && - ctrl == action->mCtrl && - alt == action->mAlt) - { - return action; - } - } - } + return action->m_qaction->shortcut().matches(keySequence) == QKeySequence::ExactMatch; + }); + }; - // iterate through the actions and save them - const uint32 numActions = group->GetNumActions(); - for (uint32 j = 0; j < numActions; ++j) + // first check the global shortcuts + const auto globalAction = findMatchingAction(group, false); + if (globalAction != end(group->GetActions())) { - // get the shortcut action - KeyboardShortcutManager::Action* action = group->GetAction(j); + return globalAction->get(); + } - // check if the action and shortcut are the same - if (key == action->mKey && - ctrl == action->mCtrl && - alt == action->mAlt) - { - return action; - } + const auto localAction = findMatchingAction(group, true); + if (localAction != end(group->GetActions())) + { + return localAction->get(); } - // failure, shortcut not found return nullptr; } @@ -264,24 +165,16 @@ namespace MysticQt settings->clear(); // iterate through the groups and save all actions for them - const uint32 numGroups = mGroups.GetLength(); - for (uint32 i = 0; i < numGroups; ++i) + for (const AZStd::unique_ptr& group : m_groups) { - Group* group = mGroups[i]; - settings->beginGroup(group->GetName()); + settings->beginGroup(QString::fromUtf8(group->GetName().data(), group->GetName().size())); // iterate through the actions and save them - const uint32 numActions = group->GetNumActions(); - for (uint32 j = 0; j < numActions; ++j) + for (const AZStd::unique_ptr& action : group->GetActions()) { - // get the shortcut action - KeyboardShortcutManager::Action* action = group->GetAction(j); - - settings->beginGroup(action->mName.c_str()); - settings->setValue("Key", action->mKey); - settings->setValue("Ctrl", action->mCtrl); - settings->setValue("Alt", action->mAlt); - settings->setValue("Local", action->mLocal); + settings->beginGroup(action->m_qaction->text()); + settings->setValue("Key", action->m_qaction->shortcut()); + settings->setValue("Local", action->m_local); settings->endGroup(); } @@ -292,33 +185,49 @@ namespace MysticQt void KeyboardShortcutManager::Load(QSettings* settings) { - // clear the shortcut manager before loading - Clear(); - // iterate through the groups and load all actions - QStringList groupNames = settings->childGroups(); - const uint32 numGroups = groupNames.count(); - for (uint32 i = 0; i < numGroups; ++i) + const QStringList groupNames = settings->childGroups(); + for (const QString& groupName : groupNames) { - QString groupName = groupNames[i]; - settings->beginGroup(groupNames[i]); - QStringList actionNames = settings->childGroups(); + Group* group = FindGroupByName(FromQtString(groupName)); + if (!group) + { + continue; + } + + settings->beginGroup(groupName); + const QStringList actionNames = settings->childGroups(); // iterate through the actions and save them - const uint32 numActions = actionNames.count(); - for (uint32 j = 0; j < numActions; ++j) + for (const QString& actionName : actionNames) { - QString actionName = actionNames[j]; settings->beginGroup(actionName); - int key = settings->value("Key", "").toInt(); - bool ctrlPressed = settings->value("Ctrl", false).toBool(); - bool altPressed = settings->value("Alt", false).toBool(); - bool local = settings->value("Local", false).toBool(); - RegisterKeyboardShortcut(FromQtString(actionName).c_str(), FromQtString(groupName).c_str(), key, ctrlPressed, altPressed, local); + const bool local = settings->value("Local", false).toBool(); + + Action* action = group->FindActionByName(actionName, local); + if (!action) + { + continue; + } + + const QVariant keyValue = settings->value("Key", ""); + if (keyValue.canConvert()) + { + const QKeySequence key = keyValue.value(); + action->m_qaction->setShortcut(key); + } + else if (keyValue.canConvert()) + { + const int key = keyValue.value(); + const bool ctrlModifier = settings->value("Ctrl", false).value(); + const bool altModifier = settings->value("Alt", false).value(); + action->m_qaction->setShortcut(key | (ctrlModifier ? Qt::ControlModifier : 0) | (altModifier ? Qt::AltModifier : 0)); + } + settings->endGroup(); } settings->endGroup(); } } -} // namespace MysticQt +} // namespace MysticQt diff --git a/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.h b/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.h index 9bd1b58812..ce989767e0 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.h +++ b/Gems/EMotionFX/Code/MysticQt/Source/KeyboardShortcutManager.h @@ -10,12 +10,14 @@ * */ -#ifndef __MYSTICQT_KEYBOARDSHORTCUTMANAGER_H -#define __MYSTICQT_KEYBOARDSHORTCUTMANAGER_H +#pragma once #if !defined(Q_MOC_RUN) +#include +#include +#include #include -#include +#include #include #include "MysticQtConfig.h" #endif @@ -26,86 +28,58 @@ class QSettings; namespace MysticQt { class MYSTICQT_API KeyboardShortcutManager + : public QObject { - MCORE_MEMORYOBJECTCATEGORY(KeyboardShortcutManager, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MYSTICQT); - public: - KeyboardShortcutManager(); - virtual ~KeyboardShortcutManager(); - struct Action { - MCORE_MEMORYOBJECTCATEGORY(KeyboardShortcutManager::Action, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MYSTICQT); - - AZStd::string mName; - int mKey; - bool mCtrl; - bool mAlt; - bool mLocal; - - int mDefaultKey; - bool mDefaultCtrl; - bool mDefaultAlt; - - Action(const char* name, int defaultKey, bool defaultCtrl, bool defaultAlt, bool local) + QAction* m_qaction; + QKeySequence m_defaultKeySequence; + bool m_local; + + Action(QAction* qaction, bool local) + : m_qaction(qaction) + , m_defaultKeySequence(qaction->shortcut()) + , m_local(local) { - mName = name; - mLocal = local; - - mKey = defaultKey; - mCtrl = defaultCtrl; - mAlt = defaultAlt; - - mDefaultKey = defaultKey; - mDefaultCtrl = defaultCtrl; - mDefaultAlt = defaultAlt; } }; class Group { - MCORE_MEMORYOBJECTCATEGORY(KeyboardShortcutManager::Group, MCore::MCORE_DEFAULT_ALIGNMENT, MEMCATEGORY_MYSTICQT); public: - Group(const char* groupName) { mName = groupName; } - virtual ~Group() + Group(AZStd::string_view groupName) + : m_name(groupName) { - const uint32 numActions = mActions.GetLength(); - for (uint32 i = 0; i < numActions; ++i) - { - delete mActions[i]; - } - mActions.Clear(); } - void AddAction(Action* action) { mActions.Add(action); } - uint32 GetNumActions() const { return mActions.GetLength(); } - Action* GetAction(uint32 index) { return mActions[index]; } - const char* GetName() const { return mName.c_str(); } - const AZStd::string& GetNameString() const { return mName; } - Action* FindActionByName(const char* actionName, bool local) const; + + void AddAction(AZStd::unique_ptr action) { m_actions.emplace_back(AZStd::move(action)); } + void RemoveAction(QAction* action, bool local); + size_t GetNumActions() const { return m_actions.size(); } + Action* GetAction(size_t index) { return m_actions[index].get(); } + const AZStd::vector>& GetActions() const { return m_actions; } + const AZStd::string& GetName() const { return m_name; } + Action* FindActionByName(const QString& actionName, bool local) const; private: - AZStd::string mName; - MCore::Array mActions; + AZStd::string m_name; + AZStd::vector> m_actions; }; - void RegisterKeyboardShortcut(const char* actionName, const char* groupName, int defaultKey, bool defaultCtrl, bool defaultAlt, bool local); - bool Check(QKeyEvent* event, const char* actionName, const char* groupName); - Action* FindShortcut(int key, bool ctrl, bool alt, Group* group); - Action* FindAction(const char* actionName, const char* groupName); - Group* FindGroupForShortcut(Action* action); - uint32 GetNumGroups() const { return mGroups.GetLength(); } - Group* GetGroup(uint32 index) const { return mGroups[index]; } - void Clear(); + void RegisterKeyboardShortcut(QAction* qaction, AZStd::string_view groupName, bool local); + void UnregisterKeyboardShortcut(QAction* qaction, AZStd::string_view groupName, bool local); + Action* FindShortcut(QKeySequence keySequence, Group* group) const; + Action* FindAction(const QString& actionName, AZStd::string_view groupName) const; + Group* FindGroupForShortcut(Action* action) const; + size_t GetNumGroups() const { return m_groups.size(); } + Group* GetGroup(size_t index) const { return m_groups[index].get(); } void Save(QSettings* settings); void Load(QSettings* settings); private: - MCore::Array mGroups; + AZStd::vector> m_groups; - Group* FindGroupByName(const char* groupName) const; + Group* FindGroupByName(AZStd::string_view groupName) const; }; } // namespace MysticQt - - -#endif diff --git a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtConfig.h b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtConfig.h index 54d2fddb54..90df0bf418 100644 --- a/Gems/EMotionFX/Code/MysticQt/Source/MysticQtConfig.h +++ b/Gems/EMotionFX/Code/MysticQt/Source/MysticQtConfig.h @@ -39,14 +39,19 @@ enum // convert from a QString into an AZStd::string MCORE_INLINE AZStd::string FromQtString(const QString& s) { - return s.toUtf8().data(); + return {s.toUtf8().data(), static_cast(s.size())}; } // convert from a QString into an AZStd::string MCORE_INLINE void FromQtString(const QString& s, AZStd::string* result) { - *result = s.toUtf8().data(); + *result = AZStd::string{s.toUtf8().data(), static_cast(s.size())}; +} + +inline QString FromStdString(AZStd::string_view s) +{ + return QString::fromUtf8(s.data(), static_cast(s.size())); } // forward declare a MysticQt class diff --git a/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/CanDeleteAnimGraphNode.cpp b/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/CanDeleteAnimGraphNode.cpp index a7f9ae228f..c7b2363ad4 100644 --- a/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/CanDeleteAnimGraphNode.cpp +++ b/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/CanDeleteAnimGraphNode.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include @@ -64,8 +65,10 @@ namespace EMotionFX { m_blendGraphWidget->OnContextMenuEvent(m_blendGraphWidget, localPoint, m_blendGraphWidget->LocalToGlobal(localPoint), m_animGraphPlugin, m_blendGraphWidget->GetActiveGraph()->GetSelectedAnimGraphNodes(), true, false, m_animGraphPlugin->GetActionFilter()); // Find Action for deleting node - QAction* deleteAction = GetNamedAction(m_blendGraphWidget, "Delete Node"); - ASSERT_TRUE(deleteAction) << "Could not find the 'Delete Node' action in the context menu"; + QAction* deleteAction = GetNamedAction(m_animGraphPlugin->GetViewWidget(), FromStdString(EMStudio::AnimGraphPlugin::s_deleteSelectedNodesShortcutName)); + ASSERT_TRUE(deleteAction) << "Could not find the '" << + std::string(EMStudio::AnimGraphPlugin::s_deleteSelectedNodesShortcutName.data(), EMStudio::AnimGraphPlugin::s_deleteSelectedNodesShortcutName.size()) + << "' action in the context menu"; // Trigger delete const size_t nodeCount = activeAnimGraph->GetNumNodes(); diff --git a/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/Transitions/RemoveTransition.cpp b/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/Transitions/RemoveTransition.cpp index 819c24baa7..98fec0fe13 100644 --- a/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/Transitions/RemoveTransition.cpp +++ b/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/Transitions/RemoveTransition.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include "qtestsystem.h" @@ -80,9 +81,8 @@ namespace EMotionFX ASSERT_TRUE(modelIndex.isValid()) << "Anim graph transition has an invalid model index."; animGraphModel.GetSelectionModel().select(QItemSelection(modelIndex, modelIndex), QItemSelectionModel::Current | QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); - // Delete key pressed. - EMStudio::BlendGraphWidget* blendGraphWidget = animGraphPlugin->GetGraphWidget(); - QTest::keyClick((QWidget*)blendGraphWidget, Qt::Key_Delete); + EMStudio::BlendGraphViewWidget* blendGraphViewWidget = animGraphPlugin->GetViewWidget(); + blendGraphViewWidget->GetAction(EMStudio::BlendGraphViewWidget::EDIT_DELETE)->trigger(); // Check if the transition get deleted. ASSERT_EQ(0, m_animGraph->GetRootStateMachine()->GetNumTransitions()) << " Anim Graph transition should be removed"; From 55f2b24302dfb2fb22eca1b8f05903b764b90714 Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Mon, 3 May 2021 17:17:18 -0500 Subject: [PATCH 051/185] Legacy Mesh component removal * Removed legacy components * More legacy render component removal * Starting removal of legacy mesh component dependencies * Removed old light components that were allowing Atom test to succeed * Testing increasing the timeout to see if it lets it pass in Jenkins * put original timeout back * reordered components to test if it is component specific or not * Testing disabiling the test to see if we get a green * Fixed the removal of the test to sandbox * Removed Legacy Mesh Component and associated tendrils * Removed some missed references * Fixed some issues with unity builds and ambiguous naming * Addressed review feedback --- Code/CryEngine/CryCommon/CREVolumeObject.h | 2 +- Code/CryEngine/CryCommon/CREWaterOcean.h | 2 +- Code/CryEngine/CryCommon/CREWaterVolume.h | 4 +- Code/CryEngine/CryCommon/Cry_Camera.h | 18 +- Code/CryEngine/CryCommon/Cry_GeoDistance.h | 11 - Code/CryEngine/CryCommon/Cry_GeoIntersect.h | 4 +- Code/CryEngine/CryCommon/Cry_GeoOverlap.h | 27 +- Code/CryEngine/CryCommon/I3DEngine.h | 2 +- Code/CryEngine/CryCommon/IEntityRenderState.h | 4 +- Code/CryEngine/CryCommon/RendElement.h | 4 +- Code/Sandbox/Editor/CryEdit.cpp | 3 - .../Source/Animation/AttachmentComponent.cpp | 355 +++++ .../Source/Animation/AttachmentComponent.h | 189 +++ .../Animation/EditorAttachmentComponent.cpp | 242 ++++ .../Animation/EditorAttachmentComponent.h | 104 ++ .../CommonFeatures/Code/Source/Module.cpp | 4 + ...egration_commonfeatures_editor_files.cmake | 2 + ...omlyintegration_commonfeatures_files.cmake | 2 + .../Code/Source/AtomActorInstance.h | 2 +- .../Integration/Components/ActorComponent.cpp | 9 - .../Components/AnimAudioComponent.cpp | 2 +- .../Components/EditorActorComponent.cpp | 15 - .../LYCommonMenu/ImGuiLYAssetExplorer.cpp | 334 +---- .../LYCommonMenu/ImGuiLYAssetExplorer.h | 8 - .../Source/Animation/AttachmentComponent.cpp | 349 ----- .../Source/Animation/AttachmentComponent.h | 186 --- .../Animation/EditorAttachmentComponent.cpp | 238 ---- .../Animation/EditorAttachmentComponent.h | 101 -- Gems/LmbrCentral/Code/Source/LmbrCentral.cpp | 25 - .../Code/Source/LmbrCentralEditor.cpp | 11 - .../Code/Source/LmbrCentralEditor.h | 10 - .../Source/Rendering/EditorMeshComponent.cpp | 580 -------- .../Source/Rendering/EditorMeshComponent.h | 175 --- .../Code/Source/Rendering/MaterialHandle.cpp | 399 ------ .../Source/Rendering/MeshAssetHandler.cpp | 265 ---- .../Code/Source/Rendering/MeshAssetHandler.h | 97 -- .../Code/Source/Rendering/MeshComponent.cpp | 1228 ----------------- .../Code/Source/Rendering/MeshComponent.h | 393 ------ .../Code/Tests/EditorMeshComponentTests.cpp | 293 ---- .../Animation/SkeletalHierarchyRequestBus.h | 54 + .../LmbrCentral/Rendering/EditorMeshBus.h | 28 - .../LmbrCentral/Rendering/MeshComponentBus.h | 164 --- .../MaterialOwnerRequestBusHandlerImpl.h | 24 +- .../Code/lmbrcentral_editor_files.cmake | 5 - .../Code/lmbrcentral_editor_tests_files.cmake | 1 - Gems/LmbrCentral/Code/lmbrcentral_files.cmake | 9 +- .../Code/Source/EditorColliderComponent.cpp | 22 +- .../Code/Source/EditorColliderComponent.h | 6 - 48 files changed, 981 insertions(+), 5031 deletions(-) create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.cpp create mode 100644 Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.h delete mode 100644 Gems/LmbrCentral/Code/Source/Animation/AttachmentComponent.cpp delete mode 100644 Gems/LmbrCentral/Code/Source/Animation/AttachmentComponent.h delete mode 100644 Gems/LmbrCentral/Code/Source/Animation/EditorAttachmentComponent.cpp delete mode 100644 Gems/LmbrCentral/Code/Source/Animation/EditorAttachmentComponent.h delete mode 100644 Gems/LmbrCentral/Code/Source/Rendering/EditorMeshComponent.cpp delete mode 100644 Gems/LmbrCentral/Code/Source/Rendering/EditorMeshComponent.h delete mode 100644 Gems/LmbrCentral/Code/Source/Rendering/MaterialHandle.cpp delete mode 100644 Gems/LmbrCentral/Code/Source/Rendering/MeshAssetHandler.cpp delete mode 100644 Gems/LmbrCentral/Code/Source/Rendering/MeshAssetHandler.h delete mode 100644 Gems/LmbrCentral/Code/Source/Rendering/MeshComponent.cpp delete mode 100644 Gems/LmbrCentral/Code/Source/Rendering/MeshComponent.h delete mode 100644 Gems/LmbrCentral/Code/Tests/EditorMeshComponentTests.cpp create mode 100644 Gems/LmbrCentral/Code/include/LmbrCentral/Animation/SkeletalHierarchyRequestBus.h delete mode 100644 Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/EditorMeshBus.h delete mode 100644 Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/MeshComponentBus.h diff --git a/Code/CryEngine/CryCommon/CREVolumeObject.h b/Code/CryEngine/CryCommon/CREVolumeObject.h index d84c7b3e50..2137053a8e 100644 --- a/Code/CryEngine/CryCommon/CREVolumeObject.h +++ b/Code/CryEngine/CryCommon/CREVolumeObject.h @@ -55,7 +55,7 @@ public: Matrix34 m_matInv; Vec3 m_eyePosInWS; Vec3 m_eyePosInOS; - Plane m_volumeTraceStartPlane; + Plane_tpl m_volumeTraceStartPlane; AABB m_renderBoundsOS; bool m_viewerInsideVolume; bool m_nearPlaneIntersectsVolume; diff --git a/Code/CryEngine/CryCommon/CREWaterOcean.h b/Code/CryEngine/CryCommon/CREWaterOcean.h index 784588309f..e8ca310d41 100644 --- a/Code/CryEngine/CryCommon/CREWaterOcean.h +++ b/Code/CryEngine/CryCommon/CREWaterOcean.h @@ -25,7 +25,7 @@ public: virtual void mfPrepare(bool bCheckOverflow); virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - virtual void mfGetPlane(Plane& pl); + virtual void mfGetPlane(Plane_tpl& pl); virtual void Create(uint32 nVerticesCount, SVF_P3F_C4B_T2F* pVertices, uint32 nIndicesCount, const void* pIndices, uint32 nIndexSizeof); void ReleaseOcean(); diff --git a/Code/CryEngine/CryCommon/CREWaterVolume.h b/Code/CryEngine/CryCommon/CREWaterVolume.h index 3e7a0636e6..89102e3097 100644 --- a/Code/CryEngine/CryCommon/CREWaterVolume.h +++ b/Code/CryEngine/CryCommon/CREWaterVolume.h @@ -27,7 +27,7 @@ public: virtual ~CREWaterVolume(); virtual void mfPrepare(bool bCheckOverflow); virtual bool mfDraw(CShader* ef, SShaderPass* sfm); - virtual void mfGetPlane(Plane& pl); + virtual void mfGetPlane(Plane_tpl& pl); virtual void mfCenter(Vec3& vCenter, CRenderObject* pObj); virtual void GetMemoryUsage(ICrySizer* pSizer) const @@ -69,7 +69,7 @@ public: Vec3 m_center; AABB m_WSBBox; - Plane m_fogPlane; + Plane_tpl m_fogPlane; float m_fogDensity; Vec3 m_fogColor; bool m_fogColorAffectedBySun; diff --git a/Code/CryEngine/CryCommon/Cry_Camera.h b/Code/CryEngine/CryCommon/Cry_Camera.h index a744d7335f..56a764d897 100644 --- a/Code/CryEngine/CryCommon/Cry_Camera.h +++ b/Code/CryEngine/CryCommon/Cry_Camera.h @@ -594,7 +594,7 @@ public: ILINE const Vec3& GetFPVertex(int nId) const; //get far-plane vertices ILINE const Vec3& GetPPVertex(int nId) const; //get projection-plane vertices - ILINE const Plane* GetFrustumPlane(int numplane) const { return &m_fp[numplane]; } + ILINE const Plane_tpl* GetFrustumPlane(int numplane) const { return &m_fp[numplane]; } ////////////////////////////////////////////////////////////////////////// // Z-Buffer ranges. @@ -720,7 +720,7 @@ private: Vec3 m_cltn, m_crtn, m_clbn, m_crbn; //this are the 4 vertices of the near-plane in cam-space Vec3 m_cltf, m_crtf, m_clbf, m_crbf; //this are the 4 vertices of the farclip-plane in cam-space - Plane m_fp [FRUSTUM_PLANES]; // + Plane_tpl m_fp [FRUSTUM_PLANES]; // uint32 m_idx1[FRUSTUM_PLANES], m_idy1[FRUSTUM_PLANES], m_idz1[FRUSTUM_PLANES]; // uint32 m_idx2[FRUSTUM_PLANES], m_idy2[FRUSTUM_PLANES], m_idz2[FRUSTUM_PLANES]; // @@ -742,7 +742,7 @@ public: m_crtp = arrvVerts[2]; m_crbp = arrvVerts[3]; } - inline void SetFrustumPlane(int i, const Plane& plane) + inline void SetFrustumPlane(int i, const Plane_tpl& plane) { m_fp[i] = plane; //do not break strict aliasing rules, use union instead of reinterpret_casts @@ -1180,12 +1180,12 @@ inline void CCamera::UpdateFrustum() //------------------------------------------------------------------------------- //--- calculate the six frustum-planes using the frustum edges in world-space --- //------------------------------------------------------------------------------- - m_fp[FR_PLANE_NEAR ] = Plane::CreatePlane(m_crtn + GetPosition(), m_cltn + GetPosition(), m_crbn + GetPosition()); - m_fp[FR_PLANE_RIGHT ] = Plane::CreatePlane(m_crbf + GetPosition(), m_crtf + GetPosition(), GetPosition()); - m_fp[FR_PLANE_LEFT ] = Plane::CreatePlane(m_cltf + GetPosition(), m_clbf + GetPosition(), GetPosition()); - m_fp[FR_PLANE_TOP ] = Plane::CreatePlane(m_crtf + GetPosition(), m_cltf + GetPosition(), GetPosition()); - m_fp[FR_PLANE_BOTTOM] = Plane::CreatePlane(m_clbf + GetPosition(), m_crbf + GetPosition(), GetPosition()); - m_fp[FR_PLANE_FAR ] = Plane::CreatePlane(m_crtf + GetPosition(), m_crbf + GetPosition(), m_cltf + GetPosition()); //clip-plane + m_fp[FR_PLANE_NEAR ] = Plane_tpl::CreatePlane(m_crtn + GetPosition(), m_cltn + GetPosition(), m_crbn + GetPosition()); + m_fp[FR_PLANE_RIGHT ] = Plane_tpl::CreatePlane(m_crbf + GetPosition(), m_crtf + GetPosition(), GetPosition()); + m_fp[FR_PLANE_LEFT ] = Plane_tpl::CreatePlane(m_cltf + GetPosition(), m_clbf + GetPosition(), GetPosition()); + m_fp[FR_PLANE_TOP ] = Plane_tpl::CreatePlane(m_crtf + GetPosition(), m_cltf + GetPosition(), GetPosition()); + m_fp[FR_PLANE_BOTTOM] = Plane_tpl::CreatePlane(m_clbf + GetPosition(), m_crbf + GetPosition(), GetPosition()); + m_fp[FR_PLANE_FAR ] = Plane_tpl::CreatePlane(m_crtf + GetPosition(), m_crbf + GetPosition(), m_cltf + GetPosition()); //clip-plane uint32 rh = m_Matrix.IsOrthonormalRH(); if (rh == 0) diff --git a/Code/CryEngine/CryCommon/Cry_GeoDistance.h b/Code/CryEngine/CryCommon/Cry_GeoDistance.h index 92c1f65d87..47794c7671 100644 --- a/Code/CryEngine/CryCommon/Cry_GeoDistance.h +++ b/Code/CryEngine/CryCommon/Cry_GeoDistance.h @@ -1168,17 +1168,6 @@ namespace Distance { return fDist2; } - // Compute both the min and max distances of a box to a plane, in the sense of the plane normal. - inline void AABB_Plane(float* pfDistMin, float* pfDistMax, const AABB& box, const Plane& pl) - { - float fDist0 = pl.DistFromPlane(box.min), - fDistX = (box.max.x - box.min.x) * pl.n.x, - fDistY = (box.max.y - box.min.y) * pl.n.y, - fDistZ = (box.max.z - box.min.z) * pl.n.z; - *pfDistMin = fDist0 + min(fDistX, 0.f) + min(fDistY, 0.f) + min(fDistZ, 0.f); - *pfDistMax = fDist0 + max(fDistX, 0.f) + max(fDistY, 0.f) + max(fDistZ, 0.f); - } - //---------------------------------------------------------------------------------- // Distance: Sphere_Triangle //---------------------------------------------------------------------------------- diff --git a/Code/CryEngine/CryCommon/Cry_GeoIntersect.h b/Code/CryEngine/CryCommon/Cry_GeoIntersect.h index c2f556c4b7..89f6d8ebaf 100644 --- a/Code/CryEngine/CryCommon/Cry_GeoIntersect.h +++ b/Code/CryEngine/CryCommon/Cry_GeoIntersect.h @@ -22,7 +22,7 @@ #include namespace Intersect { - inline bool Ray_Plane(const Ray& ray, const Plane& plane, Vec3& output, bool bSingleSidePlane = true) + inline bool Ray_Plane(const Ray& ray, const Plane_tpl& plane, Vec3& output, bool bSingleSidePlane = true) { float cosine = plane.n | ray.direction; @@ -49,7 +49,7 @@ namespace Intersect { return true; //intersection occurred } - inline bool Line_Plane(const Line& line, const Plane& plane, Vec3& output, bool bSingleSidePlane = true) + inline bool Line_Plane(const Line& line, const Plane_tpl& plane, Vec3& output, bool bSingleSidePlane = true) { float cosine = plane.n | line.direction; diff --git a/Code/CryEngine/CryCommon/Cry_GeoOverlap.h b/Code/CryEngine/CryCommon/Cry_GeoOverlap.h index 3f2c7081d7..ab560b7518 100644 --- a/Code/CryEngine/CryCommon/Cry_GeoOverlap.h +++ b/Code/CryEngine/CryCommon/Cry_GeoOverlap.h @@ -945,29 +945,6 @@ namespace Overlap { } } - - /*! - * - * we use the SEPARATING-AXIS-TEST for OBB/Plane overlap. - * - * Example: - * bool result=Overlap::OBB_Plane( pos,obb, plane ); - * - */ - inline bool OBB_Plane(const Vec3& pos, const OBB& obb, const Plane& plane) - { - //the new center-position in world-space - Vec3 p = obb.m33 * obb.c + pos; - //extract the orientation-vectors from the columns of the 3x3 matrix - //and scale them by the half-lengths - Vec3 ax = Vec3(obb.m33.m00, obb.m33.m10, obb.m33.m20) * obb.h.x; - Vec3 ay = Vec3(obb.m33.m01, obb.m33.m11, obb.m33.m21) * obb.h.y; - Vec3 az = Vec3(obb.m33.m02, obb.m33.m12, obb.m33.m22) * obb.h.z; - //check OBB against Plane, using the plane-normal as separating axis - return fabsf(plane | p) < (fabsf(plane.n | ax) + fabsf(plane.n | ay) + fabsf(plane.n | az)); - } - - /*! * * we use the SEPARATING AXIS TEST to check if a triangle and AABB overlap. @@ -1214,7 +1191,7 @@ namespace Overlap { //test if the box intersects the plane of the triangle //compute plane equation of triangle: normal*x+d=0 - Plane plane = Plane::CreatePlane((e0 % e1), v0); + Plane_tpl plane = Plane_tpl::CreatePlane((e0 % e1), v0); Vec3 vmin, vmax; if (plane.n.x > 0.0f) @@ -1505,7 +1482,7 @@ namespace Overlap { //test if the box overlaps the plane of the triangle //compute plane equation of triangle: normal*x+d=0 - Plane plane = Plane::CreatePlane((e0 % e1), v0); + Plane_tpl plane = Plane_tpl::CreatePlane((e0 % e1), v0); Vec3 vmin, vmax; if (plane.n.x > 0.0f) diff --git a/Code/CryEngine/CryCommon/I3DEngine.h b/Code/CryEngine/CryCommon/I3DEngine.h index 8d3801ecb4..883b0a6d3b 100644 --- a/Code/CryEngine/CryCommon/I3DEngine.h +++ b/Code/CryEngine/CryCommon/I3DEngine.h @@ -458,7 +458,7 @@ struct SClipVolumeBlendInfo { static const int BlendPlaneCount = 2; - Plane blendPlanes[BlendPlaneCount]; + Plane_tpl blendPlanes[BlendPlaneCount]; struct IClipVolume* blendVolumes[BlendPlaneCount]; }; diff --git a/Code/CryEngine/CryCommon/IEntityRenderState.h b/Code/CryEngine/CryCommon/IEntityRenderState.h index 912f4632ab..92ff354eff 100644 --- a/Code/CryEngine/CryCommon/IEntityRenderState.h +++ b/Code/CryEngine/CryCommon/IEntityRenderState.h @@ -731,8 +731,8 @@ struct IWaterVolumeRenderNode virtual void SetAuxPhysParams(pe_params_area*) = 0; virtual void CreateOcean(uint64 volumeID, /* TBD */ bool keepSerializationParams = false) = 0; - virtual void CreateArea(uint64 volumeID, const Vec3* pVertices, unsigned int numVertices, const Vec2& surfUVScale, const Plane& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0; - virtual void CreateRiver(uint64 volumeID, const Vec3* pVertices, unsigned int numVertices, float uTexCoordBegin, float uTexCoordEnd, const Vec2& surfUVScale, const Plane& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0; + virtual void CreateArea(uint64 volumeID, const Vec3* pVertices, unsigned int numVertices, const Vec2& surfUVScale, const Plane_tpl& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0; + virtual void CreateRiver(uint64 volumeID, const Vec3* pVertices, unsigned int numVertices, float uTexCoordBegin, float uTexCoordEnd, const Vec2& surfUVScale, const Plane_tpl& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0; virtual void CreateRiver(uint64 volumeID, const AZStd::vector& verticies, const AZ::Transform& transform, float uTexCoordBegin, float uTexCoordEnd, const AZ::Vector2& surfUVScale, const AZ::Plane& fogPlane, bool keepSerializationParams = false, int nSID = -1) = 0; virtual void SetAreaPhysicsArea(const Vec3* pVertices, unsigned int numVertices, bool keepSerializationParams = false) = 0; diff --git a/Code/CryEngine/CryCommon/RendElement.h b/Code/CryEngine/CryCommon/RendElement.h index c3dc1c080d..41bcf2bf67 100644 --- a/Code/CryEngine/CryCommon/RendElement.h +++ b/Code/CryEngine/CryCommon/RendElement.h @@ -119,7 +119,7 @@ struct IRenderElement virtual void mfCenter(Vec3& centr, CRenderObject* pObj) = 0; virtual void mfGetBBox(Vec3& vMins, Vec3& vMaxs) = 0; virtual void mfReset() = 0; - virtual void mfGetPlane(Plane& pl) = 0; + virtual void mfGetPlane(Plane_tpl& pl) = 0; virtual void mfExport(struct SShaderSerializeContext& SC) = 0; virtual void mfImport(struct SShaderSerializeContext& SC, uint32& offset) = 0; virtual void mfPrecache(const SShaderItem& SH) = 0; @@ -265,7 +265,7 @@ public: void mfPrecache([[maybe_unused]] const SShaderItem& SH) override {} void mfExport([[maybe_unused]] struct SShaderSerializeContext& SC) override { CryFatalError("mfExport has not been implemented for this render element type"); } void mfImport([[maybe_unused]] struct SShaderSerializeContext& SC, [[maybe_unused]] uint32& offset) override { CryFatalError("mfImport has not been implemented for this render element type"); } - void mfGetPlane(Plane& pl) override; + void mfGetPlane(Plane_tpl& pl) override; void* mfGetPointer([[maybe_unused]] ESrcPointer ePT, [[maybe_unused]] int* Stride, [[maybe_unused]] EParamType Type, [[maybe_unused]] ESrcPointer Dst, [[maybe_unused]] int Flags) override { return nullptr; } uint16 mfGetFlags() override { return m_Flags; } diff --git a/Code/Sandbox/Editor/CryEdit.cpp b/Code/Sandbox/Editor/CryEdit.cpp index e118104687..f2e8f1eb4a 100644 --- a/Code/Sandbox/Editor/CryEdit.cpp +++ b/Code/Sandbox/Editor/CryEdit.cpp @@ -157,9 +157,6 @@ AZ_POP_DISABLE_WARNING #include "Plugins/ComponentEntityEditorPlugin/Objects/ComponentEntityObject.h" -// LmbrCentral -#include - // AWSNativeSDK #include #include diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.cpp new file mode 100644 index 0000000000..138d619d97 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.cpp @@ -0,0 +1,355 @@ +/* +* 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 "AttachmentComponent.h" +#include +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + /// Behavior Context handler for AttachmentComponentNotificationBus + class BehaviorAttachmentComponentNotificationBusHandler : public LmbrCentral::AttachmentComponentNotificationBus::Handler, + public AZ::BehaviorEBusHandler + { + public: + AZ_EBUS_BEHAVIOR_BINDER( + BehaviorAttachmentComponentNotificationBusHandler, "{636B95A0-5C7D-4EE7-8645-955665315451}", AZ::SystemAllocator, + OnAttached, OnDetached); + + void OnAttached(AZ::EntityId id) override + { + Call(FN_OnAttached, id); + } + + void OnDetached(AZ::EntityId id) override + { + Call(FN_OnDetached, id); + } + }; + + void AttachmentConfiguration::Reflect(AZ::ReflectContext* context) + { + AZ::SerializeContext* serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class() + ->Version(1) + ->Field("Target ID", &AttachmentConfiguration::m_targetId) + ->Field("Target Bone Name", &AttachmentConfiguration::m_targetBoneName) + ->Field("Target Offset", &AttachmentConfiguration::m_targetOffset) + ->Field("Attached Initially", &AttachmentConfiguration::m_attachedInitially) + ->Field("Scale Source", &AttachmentConfiguration::m_scaleSource); + } + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->EBus("AttachmentComponentRequestBus") + ->Event("Attach", &LmbrCentral::AttachmentComponentRequestBus::Events::Attach) + ->Event("Detach", &LmbrCentral::AttachmentComponentRequestBus::Events::Detach) + ->Event("SetAttachmentOffset", &LmbrCentral::AttachmentComponentRequestBus::Events::SetAttachmentOffset); + + behaviorContext->EBus("AttachmentComponentNotificationBus") + ->Handler(); + } + } + + void AttachmentComponent::Reflect(AZ::ReflectContext* context) + { + AttachmentConfiguration::Reflect(context); + + AZ::SerializeContext* serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class()->Version(1)->Field( + "Configuration", &AttachmentComponent::m_initialConfiguration); + } + } + + //========================================================================= + // BoneFollower + //========================================================================= + + void BoneFollower::Activate(AZ::Entity* owner, const AttachmentConfiguration& configuration, bool targetCanAnimate) + { + AZ_Assert(owner, "owner is required"); + AZ_Assert(!m_ownerId.IsValid(), "BoneFollower is already Activated"); + + m_ownerId = owner->GetId(); + m_targetCanAnimate = targetCanAnimate; + m_isUpdatingOwnerTransform = false; + m_scaleSource = configuration.m_scaleSource; + + m_cachedOwnerTransform = AZ::Transform::CreateIdentity(); + EBUS_EVENT_ID_RESULT(m_cachedOwnerTransform, m_ownerId, AZ::TransformBus, GetWorldTM); + + if (configuration.m_attachedInitially) + { + Attach(configuration.m_targetId, configuration.m_targetBoneName.c_str(), configuration.m_targetOffset); + } + + LmbrCentral::AttachmentComponentRequestBus::Handler::BusConnect(m_ownerId); + } + + void BoneFollower::Deactivate() + { + AZ_Assert(m_ownerId.IsValid(), "BoneFollower was never Activated"); + + LmbrCentral::AttachmentComponentRequestBus::Handler::BusDisconnect(); + Detach(); + m_ownerId.SetInvalid(); + } + + AZ::EntityId BoneFollower::GetTargetEntityId() + { + return m_targetId; + } + + AZ::Transform BoneFollower::GetOffset() + { + return m_targetOffset; + } + + void BoneFollower::Attach(AZ::EntityId targetId, const char* targetBoneName, const AZ::Transform& offset) + { + AZ_Assert(m_ownerId.IsValid(), "BoneFollower must be Activated to use.") + + // safe to try and detach, even if we weren't attached + Detach(); + + if (!targetId.IsValid()) + { + return; + } + + if (targetId == m_ownerId) + { + AZ_Error("Attachment Component", false, "AttachmentComponent cannot target itself"); + return; + } + + // Note: the target entity may not be activated yet. That's ok. + // When mesh is ready we are notified via MeshComponentEvents::OnModelReady + // When transform is ready we are notified via TransformNotificationBus::OnTransformChanged + + m_targetId = targetId; + m_targetBoneName = targetBoneName; + m_targetOffset = offset; + + BindTargetBone(); + + m_targetBoneTransform = AZ::Transform::Identity(); + + m_isTargetEntityTransformKnown = false; // target's transform may not be available yet + + AZ::TransformBus::EventResult( + m_cachedOwnerTransform, m_ownerId, &AZ::TransformBus::Events::GetWorldTM); // owner query will always succeed + + MeshComponentNotificationBus::Handler::BusConnect(m_targetId); // fires OnModelReady if asset is already ready + AZ::TransformNotificationBus::Handler::BusConnect(m_targetId); + if (m_targetCanAnimate) + { + // Only register for per-frame updates when target can animate + AZ::TickBus::Handler::BusConnect(); + } + + // update owner's transform + UpdateOwnerTransformIfNecessary(); + + // alert others that we've attached + LmbrCentral::AttachmentComponentNotificationBus::Event(m_targetId, &LmbrCentral::AttachmentComponentNotificationBus::Events::OnAttached, m_ownerId); + } + + void BoneFollower::Detach() + { + AZ_Assert(m_ownerId.IsValid(), "BoneFollower must be Activated to use."); + + if (m_targetId.IsValid()) + { + // alert others that we're detaching + EBUS_EVENT_ID(m_targetId, LmbrCentral::AttachmentComponentNotificationBus, OnDetached, m_ownerId); + + MeshComponentNotificationBus::Handler::BusDisconnect(); + AZ::TransformNotificationBus::Handler::BusDisconnect(m_targetId); + AZ::TickBus::Handler::BusDisconnect(); + + m_targetId.SetInvalid(); + } + } + + const char* BoneFollower::GetJointName() + { + return m_targetBoneName.c_str(); + } + + void BoneFollower::SetAttachmentOffset(const AZ::Transform& offset) + { + AZ_Assert(m_ownerId.IsValid(), "BoneFollower must be Activated to use."); + + if (m_targetId.IsValid()) + { + m_targetOffset = offset; + UpdateOwnerTransformIfNecessary(); + } + } + + void BoneFollower::OnModelReady([[maybe_unused]] const AZ::Data::Asset& modelAsset, [[maybe_unused]] const AZ::Data::Instance& model) + { + // reset character values + BindTargetBone(); + m_targetBoneTransform = QueryBoneTransform(); + + // move owner if necessary + UpdateOwnerTransformIfNecessary(); + } + + void BoneFollower::BindTargetBone() + { + m_targetBoneId = -1; + LmbrCentral::SkeletalHierarchyRequestBus::EventResult( + m_targetBoneId, m_targetId, &LmbrCentral::SkeletalHierarchyRequests::GetJointIndexByName, m_targetBoneName.c_str()); + } + + void BoneFollower::UpdateOwnerTransformIfNecessary() + { + // Can't update until target entity's transform is known + if (!m_isTargetEntityTransformKnown) + { + if (AZ::TransformBus::GetNumOfEventHandlers(m_targetId) == 0) + { + return; + } + + AZ::TransformBus::EventResult(m_targetEntityTransform, m_targetId, &AZ::TransformBus::Events::GetWorldTM); + m_isTargetEntityTransformKnown = true; + } + + AZ::Transform finalTransform; + if (m_scaleSource == AttachmentConfiguration::ScaleSource::WorldScale) + { + // apply offset in world-space + finalTransform = m_targetEntityTransform * m_targetBoneTransform; + finalTransform.SetScale(AZ::Vector3::CreateOne()); + finalTransform *= m_targetOffset; + } + else if (m_scaleSource == AttachmentConfiguration::ScaleSource::TargetEntityScale) + { + // apply offset in target-entity-space (ignoring bone scale) + AZ::Transform boneNoScale = m_targetBoneTransform; + boneNoScale.SetScale(AZ::Vector3::CreateOne()); + + finalTransform = m_targetEntityTransform * boneNoScale * m_targetOffset; + } + else // AttachmentConfiguration::ScaleSource::TargetEntityScale + { + // apply offset in target-bone-space + finalTransform = m_targetEntityTransform * m_targetBoneTransform * m_targetOffset; + } + + if (m_cachedOwnerTransform != finalTransform) + { + AZ_Warning( + "Attachment Component", !m_isUpdatingOwnerTransform, + "AttachmentComponent detected a cycle when updating transform, do not target child entities."); + if (!m_isUpdatingOwnerTransform) + { + m_cachedOwnerTransform = finalTransform; + m_isUpdatingOwnerTransform = true; + EBUS_EVENT_ID(m_ownerId, AZ::TransformBus, SetWorldTM, finalTransform); + m_isUpdatingOwnerTransform = false; + } + } + } + + AZ::Transform BoneFollower::QueryBoneTransform() const + { + AZ::Transform boneTransform = AZ::Transform::CreateIdentity(); + + if (m_targetBoneId >= 0) + { + LmbrCentral::SkeletalHierarchyRequestBus::EventResult( + boneTransform, m_targetId, &LmbrCentral::SkeletalHierarchyRequests::GetJointTransformCharacterRelative, m_targetBoneId); + } + + return boneTransform; + } + + // fires when target's transform changes + void BoneFollower::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) + { + m_targetEntityTransform = world; + m_isTargetEntityTransformKnown = true; + UpdateOwnerTransformIfNecessary(); + } + + void BoneFollower::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) + { + m_targetBoneTransform = QueryBoneTransform(); + UpdateOwnerTransformIfNecessary(); + } + + int BoneFollower::GetTickOrder() + { + return AZ::TICK_ATTACHMENT; + } + + void BoneFollower::Reattach(bool detachFirst) + { +#ifdef AZ_ENABLE_TRACING + AZ::Entity* ownerEntity = nullptr; + AZ::Entity* targetEntity = nullptr; + AZ::ComponentApplicationBus::BroadcastResult(ownerEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_ownerId); + AZ::ComponentApplicationBus::BroadcastResult(targetEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_targetId); + AZ_TracePrintf( + "BoneFollower", "Reattaching entity '%s' to entity '%s'", ownerEntity ? ownerEntity->GetName().c_str() : "", + targetEntity ? targetEntity->GetName().c_str() : ""); +#endif + + if (m_targetId.IsValid() && detachFirst) + { + LmbrCentral::AttachmentComponentNotificationBus::Event(m_targetId, &LmbrCentral::AttachmentComponentNotificationBus::Events::OnDetached, m_ownerId); + } + + if (m_targetId != m_ownerId) + { + LmbrCentral::AttachmentComponentNotificationBus::Event(m_targetId, &LmbrCentral::AttachmentComponentNotificationBus::Events::OnAttached, m_ownerId); + } + } + + //========================================================================= + // AttachmentComponent + //========================================================================= + + void AttachmentComponent::Activate() + { +#ifdef AZ_ENABLE_TRACING + bool isStaticTransform = false; + AZ::TransformBus::EventResult(isStaticTransform, GetEntityId(), &AZ::TransformBus::Events::IsStaticTransform); + AZ_Warning( + "Attachment Component", !isStaticTransform, "Attachment needs to move, but entity '%s' %s has a static transform.", + GetEntity()->GetName().c_str(), GetEntityId().ToString().c_str()); +#endif + + m_boneFollower.Activate(GetEntity(), m_initialConfiguration, true); + } + + void AttachmentComponent::Deactivate() + { + m_boneFollower.Deactivate(); + } + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h new file mode 100644 index 0000000000..ac03663f22 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/AttachmentComponent.h @@ -0,0 +1,189 @@ +/* +* 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 +#include +#include + +struct ISkeletonPose; + +namespace AZ +{ + namespace Render + { + /*! + * Configuration data for AttachmentComponent. + */ + struct AttachmentConfiguration + { + AZ_TYPE_INFO(AttachmentConfiguration, "{74B5DC69-DE44-4640-836A-55339E116795}"); + + virtual ~AttachmentConfiguration() = default; + + static void Reflect(AZ::ReflectContext* context); + + //! Attach to this entity. + AZ::EntityId m_targetId; + + //! Attach to this bone on target entity. + AZStd::string m_targetBoneName; + + //! Offset from target. + AZ::Transform m_targetOffset = AZ::Transform::Identity(); + + //! Whether to attach to target upon activation. + //! If false, the entity remains detached until Attach() is called. + bool m_attachedInitially = true; + + //! Source from which to retrieve scale information. + enum class ScaleSource : AZ::u8 + { + WorldScale, // Scaled in world space. + TargetEntityScale, // Adopt scaling of attachment target entity. + TargetBoneScale, // Adopt scaling of attachment target entity/joint. + }; + ScaleSource m_scaleSource = ScaleSource::WorldScale; + }; + + /* + * Common functionality for game and editor attachment components. + * The BoneFollower tracks movement of the target's bone and + * updates the owning entity's TransformComponent to follow. + * This class should be a member within the attachment component + * and be activated/deactivated along with the component. + * \ref AttachmentComponent + */ + class BoneFollower + : public LmbrCentral::AttachmentComponentRequestBus::Handler + , public AZ::TransformNotificationBus::Handler + , public AZ::Render::MeshComponentNotificationBus::Handler + , public AZ::Data::AssetBus::Handler + , public AZ::TickBus::Handler + { + public: + void Activate(AZ::Entity* owner, const AttachmentConfiguration& initialConfiguration, bool targetCanAnimate); + void Deactivate(); + + //////////////////////////////////////////////////////////////////////// + // AttachmentComponentRequests + void Reattach(bool detachFirst); + void Attach(AZ::EntityId targetId, const char* targetBoneName, const AZ::Transform& offset) override; + void Detach() override; + void SetAttachmentOffset(const AZ::Transform& offset) override; + const char* GetJointName() override; + AZ::EntityId GetTargetEntityId() override; + AZ::Transform GetOffset() override; + //////////////////////////////////////////////////////////////////////// + + private: + + //////////////////////////////////////////////////////////////////////// + // AZ::TickBus + //! Check target bone transform every frame. + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + //! Make sure target bone transform updates after animation update. + int GetTickOrder() override; + //////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////// + // AZ::TransformNotificationBus + //! When target's transform changes + void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; + //////////////////////////////////////////////////////////////////////// + + //////////////////////////////////////////////////////////////////////// + // MeshComponentEvents + //! When target's mesh changes + void OnModelReady(const AZ::Data::Asset& modelAsset, const AZ::Data::Instance& model) override; + //////////////////////////////////////////////////////////////////////// + + void BindTargetBone(); + + AZ::Transform QueryBoneTransform() const; + + void UpdateOwnerTransformIfNecessary(); + + //! Entity which which is being attached. + AZ::EntityId m_ownerId; + + //! Whether to query bone position per-frame (false while in editor) + bool m_targetCanAnimate = false; + + AZ::EntityId m_targetId; + AZStd::string m_targetBoneName; + AZ::Transform m_targetOffset; //!< local transform + AZ::Transform m_targetBoneTransform; //!< local transform of bone + AZ::Transform m_targetEntityTransform; //!< world transform of target + bool m_isTargetEntityTransformKnown = false; + + //! Cached value, so we don't update owner's position unnecessarily. + AZ::Transform m_cachedOwnerTransform; + bool m_isUpdatingOwnerTransform = false; //!< detect infinite loops when updating owner's transform + + // Cached character values to avoid repeated lookup. + // These are set by calling ResetCharacter() + int m_targetBoneId; //!< negative when bone not found + + AttachmentConfiguration::ScaleSource m_scaleSource; + }; + + /*! + * The AttachmentComponent lets an entity stick to a particular bone on + * a target entity. This is achieved by tracking movement of the target's + * bone and updating the entity's TransformComponent accordingly. + */ + class AttachmentComponent + : public AZ::Component + { + public: + AZ_COMPONENT(AttachmentComponent, "{2D17A64A-7AC5-4C02-AC36-C5E8141FFDDF}"); + + friend class EditorAttachmentComponent; + + static void Reflect(AZ::ReflectContext* context); + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + provided.push_back(AZ_CRC("AttachmentService", 0x5aaa7b63)); + } + + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + incompatible.push_back(AZ_CRC("AttachmentService", 0x5aaa7b63)); + } + + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); + } + + ~AttachmentComponent() override = default; + + private: + //////////////////////////////////////////////////////////////////////// + // AZ::Component + void Activate() override; + void Deactivate() override; + //////////////////////////////////////////////////////////////////////// + + //! Initial configuration for m_attachment + AttachmentConfiguration m_initialConfiguration; + + //! Implements actual attachment functionality + BoneFollower m_boneFollower; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.cpp new file mode 100644 index 0000000000..3b50c0a48c --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.cpp @@ -0,0 +1,242 @@ +/* +* 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 "EditorAttachmentComponent.h" +#include +#include +#include +#include +#include + +namespace AZ +{ + namespace Render + { + void EditorAttachmentComponent::Reflect(AZ::ReflectContext* context) + { + AZ::SerializeContext* serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class() + ->Version(1) + ->Field("Target ID", &EditorAttachmentComponent::m_targetId) + ->Field("Target Bone Name", &EditorAttachmentComponent::m_targetBoneName) + ->Field("Position Offset", &EditorAttachmentComponent::m_positionOffset) + ->Field("Rotation Offset", &EditorAttachmentComponent::m_rotationOffset) + ->Field("Scale Offset", &EditorAttachmentComponent::m_scaleOffset) + ->Field("Attached Initially", &EditorAttachmentComponent::m_attachedInitially) + ->Field("Scale Source", &EditorAttachmentComponent::m_scaleSource); + + AZ::EditContext* editContext = serializeContext->GetEditContext(); + if (editContext) + { + editContext + ->Class( + "Attachment", "The Attachment component lets an entity attach to a bone on the skeleton of another entity") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->Attribute(AZ::Edit::Attributes::Category, "Animation") + ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Attachment.svg") + ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Attachment.png") + ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) + ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute( + AZ::Edit::Attributes::HelpPageURL, + "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-attachment.html") + ->DataElement(0, &EditorAttachmentComponent::m_targetId, "Target entity", "Attach to this entity.") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetIdChanged) + ->DataElement( + AZ::Edit::UIHandlers::ComboBox, &EditorAttachmentComponent::m_targetBoneName, "Joint name", + "Attach to this joint on target entity.") + ->Attribute(AZ::Edit::Attributes::StringList, &EditorAttachmentComponent::GetTargetBoneOptions) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetBoneChanged) + ->DataElement( + 0, &EditorAttachmentComponent::m_positionOffset, "Position offset", "Local position offset from target bone") + ->Attribute(AZ::Edit::Attributes::Suffix, "m") + ->Attribute(AZ::Edit::Attributes::Step, 0.01f) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetOffsetChanged) + ->DataElement( + 0, &EditorAttachmentComponent::m_rotationOffset, "Rotation offset", "Local rotation offset from target bone") + ->Attribute(AZ::Edit::Attributes::Suffix, "deg") + ->Attribute(AZ::Edit::Attributes::Step, 0.01f) + ->Attribute(AZ::Edit::Attributes::Min, -AZ::RadToDeg(AZ::Constants::TwoPi)) + ->Attribute(AZ::Edit::Attributes::Max, AZ::RadToDeg(AZ::Constants::TwoPi)) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetOffsetChanged) + ->DataElement(0, &EditorAttachmentComponent::m_scaleOffset, "Scale offset", "Local scale offset from target entity") + ->Attribute(AZ::Edit::Attributes::Step, 0.1f) + ->Attribute(AZ::Edit::Attributes::Min, 0.001f) + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetOffsetChanged) + ->DataElement( + 0, &EditorAttachmentComponent::m_attachedInitially, "Attached initially", + "Whether to attach to target upon activation.") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnAttachedInitiallyChanged) + ->DataElement( + AZ::Edit::UIHandlers::ComboBox, &EditorAttachmentComponent::m_scaleSource, "Scaling", + "How object scale should be determined. " + "Use world scale = Attached object is scaled in world space, Use target entity scale = Attached object adopts " + "scale of target entity., Use target bone scale = Attached object adopts scale of target entity/joint.") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnScaleSourceChanged) + ->EnumAttribute(AttachmentConfiguration::ScaleSource::WorldScale, "Use world scale") + ->EnumAttribute(AttachmentConfiguration::ScaleSource::TargetEntityScale, "Use target entity scale") + ->EnumAttribute(AttachmentConfiguration::ScaleSource::TargetBoneScale, "Use target bone scale"); + } + } + } + + void EditorAttachmentComponent::Activate() + { + Base::Activate(); + m_boneFollower.Activate(GetEntity(), CreateAttachmentConfiguration(), + false); // Entity's don't animate in Editor + } + + void EditorAttachmentComponent::Deactivate() + { + m_boneFollower.Deactivate(); + Base::Deactivate(); + } + + void EditorAttachmentComponent::BuildGameEntity(AZ::Entity* gameEntity) + { + AttachmentComponent* component = gameEntity->CreateComponent(); + if (component) + { + component->m_initialConfiguration = CreateAttachmentConfiguration(); + } + } + + AttachmentConfiguration EditorAttachmentComponent::CreateAttachmentConfiguration() const + { + AttachmentConfiguration configuration; + configuration.m_targetId = m_targetId; + configuration.m_targetBoneName = m_targetBoneName; + configuration.m_targetOffset = GetTargetOffset(); + configuration.m_attachedInitially = m_attachedInitially; + configuration.m_scaleSource = m_scaleSource; + return configuration; + } + + AZ::Transform EditorAttachmentComponent::GetTargetOffset() const + { + AZ::Transform offset = AZ::ConvertEulerDegreesToTransform(m_rotationOffset); + offset.SetTranslation(m_positionOffset); + offset.MultiplyByScale(m_scaleOffset); + return offset; + } + + AZStd::vector EditorAttachmentComponent::GetTargetBoneOptions() const + { + AZStd::vector names; + + // insert blank entry, so user may choose to bind to NO bone. + names.push_back(""); + + // track whether currently-set bone is found + bool currentTargetBoneFound = false; + + // Get character and iterate over bones + AZ::u32 jointCount = 0; + LmbrCentral::SkeletalHierarchyRequestBus::EventResult(jointCount, m_targetId, &LmbrCentral::SkeletalHierarchyRequests::GetJointCount); + for (AZ::u32 jointIndex = 0; jointIndex < jointCount; ++jointIndex) + { + const char* name = nullptr; + LmbrCentral::SkeletalHierarchyRequestBus::EventResult(name, m_targetId, &LmbrCentral::SkeletalHierarchyRequests::GetJointNameByIndex, jointIndex); + if (name) + { + names.push_back(name); + + if (!currentTargetBoneFound) + { + currentTargetBoneFound = (m_targetBoneName == names.back()); + } + } + } + + // If we never found currently-set bone name, + // stick it at top of list, just in case user wants to keep it anyway + if (!currentTargetBoneFound && !m_targetBoneName.empty()) + { + names.insert(names.begin(), m_targetBoneName); + } + + return names; + } + + AZ::u32 EditorAttachmentComponent::OnTargetIdChanged() + { + // Warn about bad setups (it won't crash, but it's nice to handle this early) + if (m_targetId == GetEntityId()) + { + AZ_Warning(GetEntity()->GetName().c_str(), false, "AttachmentComponent cannot target self.") m_targetId.SetInvalid(); + } + + // Warn about children attaching to a parent + AZ::EntityId parentOfTarget; + AZ::TransformBus::EventResult(parentOfTarget, m_targetId, &AZ::TransformBus::Events::GetParentId); + while (parentOfTarget.IsValid()) + { + if (parentOfTarget == GetEntityId()) + { + AZ_Warning( + GetEntity()->GetName().c_str(), parentOfTarget != GetEntityId(), "AttachmentComponent cannot target child entity"); + m_targetId.SetInvalid(); + break; + } + + AZ::EntityId currentParentId = parentOfTarget; + parentOfTarget.SetInvalid(); + AZ::TransformBus::EventResult(parentOfTarget, currentParentId, &AZ::TransformBus::Events::GetParentId); + } + + AttachOrDetachAsNecessary(); + + return AZ::Edit::PropertyRefreshLevels::AttributesAndValues; // refresh bone options + } + + AZ::u32 EditorAttachmentComponent::OnTargetBoneChanged() + { + AttachOrDetachAsNecessary(); + return AZ::Edit::PropertyRefreshLevels::None; + } + + AZ::u32 EditorAttachmentComponent::OnTargetOffsetChanged() + { + EBUS_EVENT_ID(GetEntityId(), LmbrCentral::AttachmentComponentRequestBus, SetAttachmentOffset, GetTargetOffset()); + return AZ::Edit::PropertyRefreshLevels::None; + } + + AZ::u32 EditorAttachmentComponent::OnAttachedInitiallyChanged() + { + AttachOrDetachAsNecessary(); + return AZ::Edit::PropertyRefreshLevels::None; + } + + AZ::u32 EditorAttachmentComponent::OnScaleSourceChanged() + { + m_boneFollower.Deactivate(); + m_boneFollower.Activate(GetEntity(), CreateAttachmentConfiguration(), false); + return AZ::Edit::PropertyRefreshLevels::None; + } + + void EditorAttachmentComponent::AttachOrDetachAsNecessary() + { + if (m_attachedInitially && m_targetId.IsValid()) + { + EBUS_EVENT_ID( + GetEntityId(), LmbrCentral::AttachmentComponentRequestBus, Attach, m_targetId, m_targetBoneName.c_str(), GetTargetOffset()); + } + else + { + EBUS_EVENT_ID(GetEntityId(), LmbrCentral::AttachmentComponentRequestBus, Detach); + } + } + } // namespace Render + } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.h new file mode 100644 index 0000000000..cac8a71a94 --- /dev/null +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Animation/EditorAttachmentComponent.h @@ -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. +* +*/ +#pragma once + +#include +#include "AttachmentComponent.h" + +namespace AZ +{ + namespace Render + { + /*! + * In-editor attachment component. + * \ref AttachmentComponent + */ + class EditorAttachmentComponent + : public AzToolsFramework::Components::EditorComponentBase + { + private: + using Base = AzToolsFramework::Components::EditorComponentBase; + public: + AZ_COMPONENT(EditorAttachmentComponent, "{DA6072FD-E696-47D8-81D9-1F77D3464200}", Base); + static void Reflect(AZ::ReflectContext* context); + + static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) + { + AttachmentComponent::GetProvidedServices(provided); + } + + static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) + { + AttachmentComponent::GetIncompatibleServices(incompatible); + } + + static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + { + AttachmentComponent::GetRequiredServices(required); + } + + ~EditorAttachmentComponent() override = default; + void BuildGameEntity(AZ::Entity* gameEntity) override; + + protected: + + ////////////////////////////////////////////////////////////////////////// + // AZ::Component interface implementation + void Activate() override; + void Deactivate() override; + ////////////////////////////////////////////////////////////////////////// + + AZ::u32 OnTargetIdChanged(); + AZ::u32 OnTargetBoneChanged(); + AZ::u32 OnTargetOffsetChanged(); + AZ::u32 OnAttachedInitiallyChanged(); + AZ::u32 OnScaleSourceChanged(); + + //! Invoked when an attachment property changes + void AttachOrDetachAsNecessary(); + + //! For populating ComboBox + AZStd::vector GetTargetBoneOptions() const; + + //! Create runtime configuration from editor configuration + AttachmentConfiguration CreateAttachmentConfiguration() const; + + //! Create AZ::Transform from position and rotation + AZ::Transform GetTargetOffset() const; + + //! Attach to this entity. + AZ::EntityId m_targetId; + + //! Attach to this bone on target entity. + AZStd::string m_targetBoneName; + + //! Offset from target bone's position. + AZ::Vector3 m_positionOffset = AZ::Vector3::CreateZero(); + + //! Offset from target bone's rotation. + AZ::Vector3 m_rotationOffset = AZ::Vector3::CreateZero(); + + //! Offset from target entity's scale. + AZ::Vector3 m_scaleOffset = AZ::Vector3::CreateOne(); + + //! Observe scale information from the specified source. + AttachmentConfiguration::ScaleSource m_scaleSource = AttachmentConfiguration::ScaleSource::WorldScale; + + //! Whether to attach to target upon activation. + //! If false, the entity remains detached until Attach() is called. + bool m_attachedInitially = true; + + //! Implements actual attachment functionality + AZ::Render::BoneFollower m_boneFollower; + }; + } // namespace Render +} // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp index b33dd7f165..2ef4e1e229 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Module.cpp @@ -39,6 +39,7 @@ #include #include #include +#include #ifdef ATOMLYINTEGRATION_FEATURE_COMMON_EDITOR #include @@ -69,6 +70,7 @@ #include #include #include +#include #endif namespace AZ @@ -111,6 +113,7 @@ namespace AZ DiffuseProbeGridComponent::CreateDescriptor(), DeferredFogComponent::CreateDescriptor(), SurfaceData::SurfaceDataMeshComponent::CreateDescriptor(), + AttachmentComponent::CreateDescriptor(), #ifdef ATOMLYINTEGRATION_FEATURE_COMMON_EDITOR EditorAreaLightComponent::CreateDescriptor(), @@ -141,6 +144,7 @@ namespace AZ EditorDiffuseProbeGridComponent::CreateDescriptor(), EditorDeferredFogComponent::CreateDescriptor(), SurfaceData::EditorSurfaceDataMeshComponent::CreateDescriptor(), + EditorAttachmentComponent::CreateDescriptor(), #endif }); } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake index ff8f33e06e..e58f72a121 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_editor_files.cmake @@ -11,6 +11,8 @@ set(FILES Source/Module.cpp + Source/Animation/EditorAttachmentComponent.h + Source/Animation/EditorAttachmentComponent.cpp Include/AtomLyIntegration/CommonFeatures/Material/EditorMaterialSystemComponentRequestBus.h Include/AtomLyIntegration/CommonFeatures/ReflectionProbe/EditorReflectionProbeBus.h Source/EditorCommonFeaturesSystemComponent.h diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake index b26ebc60a6..e13d1d37d6 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/atomlyintegration_commonfeatures_files.cmake @@ -10,6 +10,8 @@ # set(FILES + Source/Animation/AttachmentComponent.h + Source/Animation/AttachmentComponent.cpp Source/CoreLights/AreaLightComponent.h Source/CoreLights/AreaLightComponent.cpp Source/CoreLights/AreaLightComponentConfig.cpp diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h index b31091681e..1002fcbde1 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h @@ -18,7 +18,7 @@ #include -#include +#include #include #include diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp index e3de713b3c..8ef87af9a7 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/ActorComponent.cpp @@ -24,7 +24,6 @@ #include #include -#include #include #include @@ -414,9 +413,6 @@ namespace EMotionFX CheckAttachToEntity(); - // Send general mesh creation notification to interested parties. - LmbrCentral::MeshComponentNotificationBus::Event(entityId, &LmbrCentral::MeshComponentNotifications::OnMeshCreated, m_configuration.m_actorAsset); - Physics::RagdollConfiguration ragdollConfiguration; [[maybe_unused]] bool ragdollConfigValid = GetRagdollConfiguration(ragdollConfiguration); AZ_Assert(ragdollConfigValid, "Ragdoll Configuration is not valid"); @@ -460,11 +456,6 @@ namespace EMotionFX m_attachmentTargetActor = nullptr; - // Send general mesh destruction notification to interested parties. - LmbrCentral::MeshComponentNotificationBus::Event( - GetEntityId(), - &LmbrCentral::MeshComponentNotifications::OnMeshDestroyed); - ActorComponentNotificationBus::Event( GetEntityId(), &ActorComponentNotificationBus::Events::OnActorInstanceDestroyed, diff --git a/Gems/EMotionFX/Code/Source/Integration/Components/AnimAudioComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Components/AnimAudioComponent.cpp index 6958710b1a..eee9896dee 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Components/AnimAudioComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Components/AnimAudioComponent.cpp @@ -22,7 +22,7 @@ #include #include -#include // for SkeletalHierarchyRequestBus +#include #include diff --git a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp index bcb1e3f300..f45fe43f4e 100644 --- a/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/Editor/Components/EditorActorComponent.cpp @@ -26,8 +26,6 @@ #include #include -#include - #include #include #include @@ -255,11 +253,6 @@ namespace EMotionFX { if (m_actorInstance) { - // Send general mesh destruction notification to interested parties. - LmbrCentral::MeshComponentNotificationBus::Event( - GetEntityId(), - &LmbrCentral::MeshComponentNotifications::OnMeshDestroyed); - ActorComponentNotificationBus::Event( GetEntityId(), &ActorComponentNotificationBus::Events::OnActorInstanceDestroyed, @@ -848,11 +841,6 @@ namespace EMotionFX if (m_actorInstance) { - // Send general mesh destruction notification to interested parties. - LmbrCentral::MeshComponentNotificationBus::Event( - GetEntityId(), - &LmbrCentral::MeshComponentNotifications::OnMeshDestroyed); - ActorComponentNotificationBus::Event( GetEntityId(), &ActorComponentNotificationBus::Events::OnActorInstanceDestroyed, @@ -941,9 +929,6 @@ namespace EMotionFX { LmbrCentral::AttachmentComponentRequestBus::Event(attachment, &LmbrCentral::AttachmentComponentRequestBus::Events::Reattach, true); } - - // Send general mesh creation notification to interested parties. - LmbrCentral::MeshComponentNotificationBus::Event(GetEntityId(), &LmbrCentral::MeshComponentNotifications::OnMeshCreated, m_actorAsset); } } //namespace Integration } // namespace EMotionFX diff --git a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYAssetExplorer.cpp b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYAssetExplorer.cpp index 770e1190be..7b15d6680d 100644 --- a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYAssetExplorer.cpp +++ b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYAssetExplorer.cpp @@ -21,7 +21,6 @@ #include #include #include -#include #include #include #include @@ -518,18 +517,6 @@ namespace ImGui ImGui::EndChild(); // End the "Meshes in Scene" Child } } - - // Check to make sure the Tick Bus Connection status matches the debug enabled flag - if (m_meshDebugEnabled && !AZ::TickBus::Handler::BusIsConnected()) - { - // Connect to the Tick Bus - AZ::TickBus::Handler::BusConnect(); - } - else if (!m_meshDebugEnabled && AZ::TickBus::Handler::BusIsConnected()) - { - // Disconnect from the Tick Bus - AZ::TickBus::Handler::BusDisconnect(); - } } // Mesh Mouse Over Helper function @@ -597,81 +584,6 @@ namespace ImGui instanceOptions.m_mousedOverForDraw |= ImGui::IsItemHovered(); } - void ImGuiLYAssetExplorer::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) - { - // Search through all entities for Asset Components - OnTick_FindAssets(); - - // Check for all relevant pointers here. ( Actually requires checking all of these for different edge cases! :( - if (gEnv && gEnv->pRenderer && gEnv->pSystem && - gEnv->pSystem->GetIViewSystem() && gEnv->pSystem->GetIViewSystem()->GetActiveView() && - gEnv->pSystem->GetIViewSystem()->GetActiveView()->GetCurrentParams()) - { - // Get the Camera View Position from the view system. - const Vec3& cameraPosVec3 = gEnv->pSystem->GetIViewSystem()->GetActiveView()->GetCurrentParams()->position; - const AZ::Vector3 cameraPos(cameraPosVec3.x, cameraPosVec3.y, cameraPosVec3.z); - - // Loop through all Meshes to draw the appropriate ones! - for (const MeshInstanceDisplayList& meshInstanceList : m_meshInstanceDisplayList) - { - // bunch of different ways to filter results. First check for Mesh and Instance Name Filters... - bool displayMesh = true; - if (m_meshNameFilter) - { - displayMesh &= meshInstanceList.m_passesFilter; - } - if (m_entityNameFilter) - { - displayMesh &= meshInstanceList.m_childrenPassFilter; - } - - // ..Mouse Overs and Selection Filters should override other filters, so do it after.. Mouse Over THEN Selection Filter for precedence. - if (m_anyMousedOverForDraw) - { - displayMesh = meshInstanceList.m_mousedOverForDraw || meshInstanceList.m_childMousedOverForDraw; - } - else if (m_selectionFilter) - { - displayMesh = meshInstanceList.m_selectedForDraw; - for (const auto& meshInstance : meshInstanceList.m_instanceOptionMap) - { - displayMesh |= meshInstance.second.m_selectedForDraw; - } - } - - if (displayMesh) - { - for (const auto& meshInstance : meshInstanceList.m_instanceOptionMap) - { - AZ::Data::Asset meshAsset; - LmbrCentral::MeshComponentRequestBus::EventResult(meshAsset, meshInstance.first, &LmbrCentral::MeshComponentRequests::GetMeshAsset); - // See if we pass name filter first.. - bool displayEntity = true; - if (m_entityNameFilter) - { - displayEntity = meshInstance.second.m_passesFilter; - } - - // ..Mouse Overs and Selection Filters should override other filters, so do it after.. Mouse Over THEN Selection Filter for precedence. - if (m_anyMousedOverForDraw) - { - displayEntity = meshInstance.second.m_mousedOverForDraw || meshInstanceList.m_mousedOverForDraw; - } - else if (m_selectionFilter) - { - displayEntity = meshInstance.second.m_selectedForDraw | meshInstanceList.m_selectedForDraw; - } - - if (displayEntity) - { - OnTick_DrawEntity(meshInstance.first, meshAsset.GetId(), gEnv->pRenderer, cameraPos); - } - } - } - } - } - } - MeshInstanceDisplayList& ImGuiLYAssetExplorer::FindOrCreateMeshInstanceList(const char* meshName) { // Walk the list and see if an entry for this mesh exists already. If we find one, return it! @@ -696,250 +608,6 @@ namespace ImGui m_meshInstanceDisplayList.push_back(meshList); return m_meshInstanceDisplayList.back(); } - - // Scan the scene for Meshes! - void ImGuiLYAssetExplorer::OnTick_FindAssets() - { - // Retrieve Id map from game entity context (editor->runtime). - AzFramework::EntityContextId gameContextId = AzFramework::EntityContextId::CreateNull(); - AzFramework::GameEntityContextRequestBus::BroadcastResult(gameContextId, &AzFramework::GameEntityContextRequests::GetGameEntityContextId); - - // Get the Root Slice Component - AZ::SliceComponent* rootSliceComponent; - AzFramework::SliceEntityOwnershipServiceRequestBus::EventResult(rootSliceComponent, gameContextId, - &AzFramework::SliceEntityOwnershipServiceRequests::GetRootSlice); - - if (rootSliceComponent) - { - // Get an unordered_set of all EntityIds in the slice - AZ::SliceComponent::EntityIdSet entityIds; - rootSliceComponent->GetEntityIds(entityIds); - - // Loop through Mesh Map and "un-verify" them - for (MeshInstanceDisplayList& meshInstanceList : m_meshInstanceDisplayList) - { - for (auto& meshInstance : meshInstanceList.m_instanceOptionMap) - { - meshInstance.second.m_verifiedThisFrame = false; - } - } - - for (auto it = entityIds.begin(); it != entityIds.end(); it++) - { - AZ::Data::Asset meshAsset; - LmbrCentral::MeshComponentRequestBus::EventResult(meshAsset, *it, &LmbrCentral::MeshComponentRequests::GetMeshAsset); - - if (meshAsset.IsReady()) - { - // Get the Asset Info so we can get the mesh path - AZ::Data::AssetInfo assetInfo; - AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetInfo, &AZ::Data::AssetCatalogRequests::GetAssetInfoById, meshAsset.GetId()); - - AZStd::string meshPath = assetInfo.m_relativePath; - AZStd::to_lower(meshPath.begin(), meshPath.end()); - // Save off this mesh instance into the instance map - MeshInstanceDisplayList& displayList = FindOrCreateMeshInstanceList(meshPath.c_str()); - if (!displayList.m_instanceOptionMap.count(*it)) - { - // Get the Entity Name, for easy searching later - AZStd::string entityName; - AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationBus::Events::GetEntityName, *it); - - // Init the instance entry and options - MeshInstanceOptions& meshOptions = displayList.m_instanceOptionMap[*it]; - meshOptions.m_verifiedThisFrame = true; - meshOptions.m_passesFilter = true; - meshOptions.m_selectedForDraw = false; - meshOptions.m_mousedOverForDraw = false; - meshOptions.m_instanceLabel = AZStd::string::format("%s%s", (*it).ToString().c_str(), entityName.c_str()); - AZStd::to_lower(meshOptions.m_instanceLabel.begin(), meshOptions.m_instanceLabel.end()); - } - else - { - displayList.m_instanceOptionMap[*it].m_verifiedThisFrame = true; - } - } - } - - // Loop through Mesh Map again and remove any "un-verify"-ed entries! - for (auto meshInstanceListIter = m_meshInstanceDisplayList.begin(); meshInstanceListIter != m_meshInstanceDisplayList.end();) - { - for (auto meshInstanceIter = (*meshInstanceListIter).m_instanceOptionMap.begin(); meshInstanceIter != (*meshInstanceListIter).m_instanceOptionMap.end();) - { - if (!(*meshInstanceIter).second.m_verifiedThisFrame) - { - // erase this instance from the map and set the iterator correctly. - meshInstanceIter = (*meshInstanceListIter).m_instanceOptionMap.erase(meshInstanceIter); - } - else - { - // increment the iterator - meshInstanceIter++; - } - } - - // Remove the Mesh Entry if there are no instances remaining - if ((*meshInstanceListIter).m_instanceOptionMap.empty()) - { - meshInstanceListIter = m_meshInstanceDisplayList.erase(meshInstanceListIter); - } - else - { - // increment the iterator - meshInstanceListIter++; - } - } - } - } - - // We know we want to draw this Entity/Mesh ( depending on distance from Cam ).. so draw! - void ImGuiLYAssetExplorer::OnTick_DrawEntity(const AZ::EntityId& entity, const AZ::Data::AssetId& assetId, IRenderer* renderer, const AZ::Vector3& cameraPos) - { - // Get the Entity Position so we can see how far from the camera we are. - AZ::Vector3 worldPos = AZ::Vector3::CreateZero(); - AZ::TransformBus::EventResult(worldPos, entity, &AZ::TransformBus::Events::GetWorldTranslation); - - // Get Our Distance From The Camera! ( Used just for draw alpha value ) - float distFromCamera = m_distanceFilter_far + 1.0f; // Default to just outside camera view ( i.e. Don't draw ) - if (m_anyMousedOverForDraw || m_selectionFilter || !m_distanceFilter) - { - // If we have either the Selection Filter or Mouse Over state on or the distance filter is off, and we made it this far, we are the lucky selected one! Draw ourselves by setting dist to 0.0f - distFromCamera = 0.0; - } - else if (m_distanceFilter) - { - // Distance filter is on and we aren't selected, so actually find the distance from the camera - distFromCamera = worldPos.GetDistance(cameraPos); - } - - // Only draw things within view distance ( cheese it to zero above to force drawing far things ) - if (distFromCamera <= m_distanceFilter_far) - { - // Find an interpolated Alpha.. 1.0f while inside near radius, interp 1.0 -> 0.0 while heading toward far radius - float alpha = (distFromCamera <= m_distanceFilter_near) ? 1.0f : (1.0f - ((distFromCamera - m_distanceFilter_near) / (m_distanceFilter_far - m_distanceFilter_near))); - - // The string to hold label text we will build. - AZStd::string entityLabel; - - // Grab the Asset Info to get the mesh path name. - AZ::Data::AssetInfo assetInfo; - AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetInfo, &AZ::Data::AssetCatalogRequests::GetAssetInfoById, assetId); - - // Start the label with either the EntName and Mesh, or just Mesh - if (m_inWorld_label_entityName) - { - AZ::ComponentApplicationBus::BroadcastResult(entityLabel, &AZ::ComponentApplicationBus::Events::GetEntityName, entity); - entityLabel = AZStd::string::format("Entity: %s %s\nMesh: %s", entity.ToString().c_str(), entityLabel.c_str(), assetInfo.m_relativePath.c_str()); - } - else - { - entityLabel = AZStd::string::format("Mesh: %s", assetInfo.m_relativePath.c_str()); - } - - // See if we should add the Material! - if (m_inWorld_label_materialName) - { - _smart_ptr material; - LmbrCentral::MaterialOwnerRequestBus::EventResult(material, entity, &LmbrCentral::MaterialOwnerRequests::GetMaterial); - if (material) - { - entityLabel.append(AZStd::string::format("\nMaterial: %s", material->GetName())); - } - } - - // Get The Render Node for mesh debug draw and Lod Info - IRenderNode* renderNode = nullptr; - LmbrCentral::RenderNodeRequestBus::EventResult(renderNode, entity, &LmbrCentral::RenderNodeRequests::GetRenderNode); - - if (renderNode != nullptr && renderNode->GetEntityStatObj()) - { - // Debug Draw Mesh - if (m_inWorld_debugDrawMesh) - { - SGeometryDebugDrawInfo dd; - dd.color.Set(0.0f, 0.0f, 255.0f, 0.5f * alpha); - dd.lineColor.Set(255.0f, 0.0f, 0.0f, 0.75f * alpha); - renderNode->GetEntityStatObj()->DebugDraw(dd, 0.2f); - } - // Draw Total Lods info - if (m_inWorld_label_totalLods) - { - entityLabel.append(AZStd::string::format("\nTotal Lods: %d", renderNode->GetEntityStatObj()->GetLoadedLodsNum())); - } - // Draw Misc Lod Info - if (m_inWorld_label_miscLod) - { - entityLabel.append(AZStd::string::format("\nFirst Lod Distance: %f", renderNode->GetFirstLodDistance())); - float distances[SMeshLodInfo::s_nMaxLodCount]; - renderNode->GetLodDistances(gEnv->p3DEngine->GetFrameLodInfo(), distances); - for (int i = 0; i < SMeshLodInfo::s_nMaxLodCount; i++) - { - entityLabel.append(AZStd::string::format("\n frameLod: %d - %f", i, distances[i])); - } - } - } - - // Draw the label in the world - if (m_inWorld_drawLabel) - { - SDrawTextInfo ti; - ti.xscale = ti.yscale = m_inWorld_labelTextSize * alpha; - ti.flags = eDrawText_FixedSize | eDrawText_Center | eDrawText_800x600; - if (m_inWorld_label_framed) - { - ti.flags |= eDrawText_Framed; - } - if (m_inWorld_label_monoSpace) - { - ti.flags |= eDrawText_Monospace; - } - - { - ti.color[0] = m_inWorld_label_textColor.Value.x; - ti.color[1] = m_inWorld_label_textColor.Value.y; - ti.color[2] = m_inWorld_label_textColor.Value.z; - ti.color[3] = alpha; - } - Vec3 labelPos(worldPos.GetX(), worldPos.GetY(), worldPos.GetZ() - m_inWorld_originSphereRadius); - renderer->DrawTextQueued(labelPos, ti, entityLabel.c_str()); - } - - // Draw the sphere and/or AABB in the world - if (m_inWorld_drawOriginSphere || m_inWorld_drawAABB) - { - IRenderAuxGeom* pAuxGeom = renderer->GetIRenderAuxGeom(); - if (pAuxGeom) - { - const ColorF sphereColor(m_inWorld_label_textColor.Value.x, m_inWorld_label_textColor.Value.y, m_inWorld_label_textColor.Value.z, alpha); - Vec3 spherePos(worldPos.GetX(), worldPos.GetY(), worldPos.GetZ()); - - // draw a sample sphere - SAuxGeomRenderFlags oldFlags = pAuxGeom->GetRenderFlags(); - SAuxGeomRenderFlags flags = oldFlags; - flags.SetDepthWriteFlag(e_DepthWriteOff); - flags.SetDepthTestFlag(e_DepthTestOff); - flags.SetDrawInFrontMode(e_DrawInFrontOn); - flags.SetFillMode(e_FillModeSolid); - flags.SetCullMode(e_CullModeNone); - pAuxGeom->SetRenderFlags(flags); - - if ( m_inWorld_drawOriginSphere) - { - pAuxGeom->DrawSphere(spherePos, m_inWorld_originSphereRadius, sphereColor, false); - } - - if (m_inWorld_drawAABB && renderNode) - { - pAuxGeom->DrawAABB(renderNode->GetBBox(), false, sphereColor, EBoundingBoxDrawStyle::eBBD_Extremes_Color_Encoded); - } - - // Restore rendering state - pAuxGeom->SetRenderFlags(oldFlags); - } - } - } - } - -} // namespace ImGui + } // namespace ImGui #endif // IMGUI_ENABLED diff --git a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYAssetExplorer.h b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYAssetExplorer.h index 29584c84d3..b5f8ea576c 100644 --- a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYAssetExplorer.h +++ b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYAssetExplorer.h @@ -43,7 +43,6 @@ namespace ImGui class ImGuiLYAssetExplorer : public ImGuiAssetExplorerRequestBus::Handler - , public AZ::TickBus::Handler { public: @@ -61,10 +60,6 @@ namespace ImGui void SetEnabled(bool enabled) override { m_enabled = enabled; m_meshDebugEnabled = enabled; } // -- ImGuiAssetExplorerRequestBus::Handler Interface ---------------------- - // -- AZ::TickBus::Handler Interface --------------------------------------- - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - // -- AZ::TickBus::Handler Interface --------------------------------------- - // Toggle the menu on and off void ToggleEnabled() { m_enabled = !m_enabled; } @@ -117,9 +112,6 @@ namespace ImGui void ImGuiUpdate_DrawMeshMouseOver(MeshInstanceDisplayList& meshDisplayList); void ImGuiUpdate_DrawEntityInstanceMouseOver(MeshInstanceDisplayList& meshDisplayList, AZ::EntityId& entityInstance, AZStd::string& entityName, MeshInstanceOptions& instanceOptions); - // Helper functions for the OnTick callback - void OnTick_DrawEntity(const AZ::EntityId& entity, const AZ::Data::AssetId& assetId, IRenderer* renderer, const AZ::Vector3& cameraPos); - void OnTick_FindAssets(); }; } #endif // IMGUI_ENABLED diff --git a/Gems/LmbrCentral/Code/Source/Animation/AttachmentComponent.cpp b/Gems/LmbrCentral/Code/Source/Animation/AttachmentComponent.cpp deleted file mode 100644 index 537585f48c..0000000000 --- a/Gems/LmbrCentral/Code/Source/Animation/AttachmentComponent.cpp +++ /dev/null @@ -1,349 +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 "LmbrCentral_precompiled.h" -#include "AttachmentComponent.h" -#include -#include -#include -#include -#include -#include - -namespace LmbrCentral -{ - /// Behavior Context handler for AttachmentComponentNotificationBus - class BehaviorAttachmentComponentNotificationBusHandler : public AttachmentComponentNotificationBus::Handler, public AZ::BehaviorEBusHandler - { - public: - AZ_EBUS_BEHAVIOR_BINDER(BehaviorAttachmentComponentNotificationBusHandler, "{636B95A0-5C7D-4EE7-8645-955665315451}", AZ::SystemAllocator - , OnAttached, OnDetached); - - void OnAttached(AZ::EntityId id) override - { - Call(FN_OnAttached, id); - } - - void OnDetached(AZ::EntityId id) override - { - Call(FN_OnDetached, id); - } - }; - - void AttachmentConfiguration::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field("Target ID", &AttachmentConfiguration::m_targetId) - ->Field("Target Bone Name", &AttachmentConfiguration::m_targetBoneName) - ->Field("Target Offset", &AttachmentConfiguration::m_targetOffset) - ->Field("Attached Initially", &AttachmentConfiguration::m_attachedInitially) - ->Field("Scale Source", &AttachmentConfiguration::m_scaleSource) - ; - } - AZ::BehaviorContext* behaviorContext = azrtti_cast(context); - if (behaviorContext) - { - behaviorContext->EBus("AttachmentComponentRequestBus") - ->Event("Attach", &AttachmentComponentRequestBus::Events::Attach) - ->Event("Detach", &AttachmentComponentRequestBus::Events::Detach) - ->Event("SetAttachmentOffset", &AttachmentComponentRequestBus::Events::SetAttachmentOffset); - - behaviorContext->EBus("AttachmentComponentNotificationBus") - ->Handler(); - } - } - - void AttachmentComponent::Reflect(AZ::ReflectContext* context) - { - AttachmentConfiguration::Reflect(context); - - AZ::SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field("Configuration", &AttachmentComponent::m_initialConfiguration) - ; - } - } - - //========================================================================= - // BoneFollower - //========================================================================= - - void BoneFollower::Activate(AZ::Entity* owner, const AttachmentConfiguration& configuration, bool targetCanAnimate) - { - AZ_Assert(owner, "owner is required"); - AZ_Assert(!m_ownerId.IsValid(), "BoneFollower is already Activated"); - - m_ownerId = owner->GetId(); - m_targetCanAnimate = targetCanAnimate; - m_isUpdatingOwnerTransform = false; - m_scaleSource = configuration.m_scaleSource; - - m_cachedOwnerTransform = AZ::Transform::CreateIdentity(); - EBUS_EVENT_ID_RESULT(m_cachedOwnerTransform, m_ownerId, AZ::TransformBus, GetWorldTM); - - if (configuration.m_attachedInitially) - { - Attach(configuration.m_targetId, configuration.m_targetBoneName.c_str(), configuration.m_targetOffset); - } - - AttachmentComponentRequestBus::Handler::BusConnect(m_ownerId); - } - - void BoneFollower::Deactivate() - { - AZ_Assert(m_ownerId.IsValid(), "BoneFollower was never Activated"); - - AttachmentComponentRequestBus::Handler::BusDisconnect(); - Detach(); - m_ownerId.SetInvalid(); - } - - AZ::EntityId BoneFollower::GetTargetEntityId() - { - return m_targetId; - } - - AZ::Transform BoneFollower::GetOffset() - { - return m_targetOffset; - } - - void BoneFollower::Attach(AZ::EntityId targetId, const char* targetBoneName, const AZ::Transform& offset) - { - AZ_Assert(m_ownerId.IsValid(), "BoneFollower must be Activated to use.") - - // safe to try and detach, even if we weren't attached - Detach(); - - if (!targetId.IsValid()) - { - return; - } - - if (targetId == m_ownerId) - { - AZ_Error("Attachment Component", false, "AttachmentComponent cannot target itself"); - return; - } - - // Note: the target entity may not be activated yet. That's ok. - // When mesh is ready we are notified via MeshComponentEvents::OnMeshCreated - // When transform is ready we are notified via TransformNotificationBus::OnTransformChanged - - m_targetId = targetId; - m_targetBoneName = targetBoneName; - m_targetOffset = offset; - - BindTargetBone(); - - m_targetBoneTransform = AZ::Transform::Identity(); - - m_isTargetEntityTransformKnown = false; // target's transform may not be available yet - - AZ::TransformBus::EventResult(m_cachedOwnerTransform, m_ownerId, &AZ::TransformBus::Events::GetWorldTM); // owner query will always succeed - - MeshComponentNotificationBus::Handler::BusConnect(m_targetId); // fires OnMeshCreated if asset is already ready - AZ::TransformNotificationBus::Handler::BusConnect(m_targetId); - if (m_targetCanAnimate) - { - // Only register for per-frame updates when target can animate - AZ::TickBus::Handler::BusConnect(); - } - - // update owner's transform - UpdateOwnerTransformIfNecessary(); - - // alert others that we've attached - AttachmentComponentNotificationBus::Event(m_targetId, &AttachmentComponentNotificationBus::Events::OnAttached, m_ownerId); - } - - void BoneFollower::Detach() - { - AZ_Assert(m_ownerId.IsValid(), "BoneFollower must be Activated to use."); - - if (m_targetId.IsValid()) - { - // alert others that we're detaching - EBUS_EVENT_ID(m_targetId, AttachmentComponentNotificationBus, OnDetached, m_ownerId); - - MeshComponentNotificationBus::Handler::BusDisconnect(); - AZ::TransformNotificationBus::Handler::BusDisconnect(m_targetId); - AZ::TickBus::Handler::BusDisconnect(); - - m_targetId.SetInvalid(); - } - } - - const char* BoneFollower::GetJointName() - { - return m_targetBoneName.c_str(); - } - - void BoneFollower::SetAttachmentOffset(const AZ::Transform& offset) - { - AZ_Assert(m_ownerId.IsValid(), "BoneFollower must be Activated to use."); - - if (m_targetId.IsValid()) - { - m_targetOffset = offset; - UpdateOwnerTransformIfNecessary(); - } - } - - void BoneFollower::OnMeshCreated(const AZ::Data::Asset& asset) - { - (void)asset; - - // reset character values - BindTargetBone(); - m_targetBoneTransform = QueryBoneTransform(); - - // move owner if necessary - UpdateOwnerTransformIfNecessary(); - } - - void BoneFollower::BindTargetBone() - { - m_targetBoneId = -1; - SkeletalHierarchyRequestBus::EventResult(m_targetBoneId, m_targetId, &SkeletalHierarchyRequests::GetJointIndexByName, m_targetBoneName.c_str()); - } - - void BoneFollower::UpdateOwnerTransformIfNecessary() - { - // Can't update until target entity's transform is known - if (!m_isTargetEntityTransformKnown) - { - if (AZ::TransformBus::GetNumOfEventHandlers(m_targetId) == 0) - { - return; - } - - AZ::TransformBus::EventResult(m_targetEntityTransform, m_targetId, &AZ::TransformBus::Events::GetWorldTM); - m_isTargetEntityTransformKnown = true; - } - - AZ::Transform finalTransform; - if (m_scaleSource == AttachmentConfiguration::ScaleSource::WorldScale) - { - // apply offset in world-space - finalTransform = m_targetEntityTransform * m_targetBoneTransform; - finalTransform.SetScale(AZ::Vector3::CreateOne()); - finalTransform *= m_targetOffset; - } - else if (m_scaleSource == AttachmentConfiguration::ScaleSource::TargetEntityScale) - { - // apply offset in target-entity-space (ignoring bone scale) - AZ::Transform boneNoScale = m_targetBoneTransform; - boneNoScale.SetScale(AZ::Vector3::CreateOne()); - - finalTransform = m_targetEntityTransform * boneNoScale * m_targetOffset; - } - else // AttachmentConfiguration::ScaleSource::TargetEntityScale - { - // apply offset in target-bone-space - finalTransform = m_targetEntityTransform * m_targetBoneTransform * m_targetOffset; - } - - if (m_cachedOwnerTransform != finalTransform) - { - AZ_Warning("Attachment Component", !m_isUpdatingOwnerTransform, "AttachmentComponent detected a cycle when updating transform, do not target child entities."); - if (!m_isUpdatingOwnerTransform) - { - m_cachedOwnerTransform = finalTransform; - m_isUpdatingOwnerTransform = true; - EBUS_EVENT_ID(m_ownerId, AZ::TransformBus, SetWorldTM, finalTransform); - m_isUpdatingOwnerTransform = false; - } - } - } - - AZ::Transform BoneFollower::QueryBoneTransform() const - { - AZ::Transform boneTransform = AZ::Transform::CreateIdentity(); - - if (m_targetBoneId >= 0) - { - SkeletalHierarchyRequestBus::EventResult(boneTransform, m_targetId, &SkeletalHierarchyRequests::GetJointTransformCharacterRelative, m_targetBoneId); - } - - return boneTransform; - } - - // fires when target's transform changes - void BoneFollower::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) - { - m_targetEntityTransform = world; - m_isTargetEntityTransformKnown = true; - UpdateOwnerTransformIfNecessary(); - } - - void BoneFollower::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) - { - m_targetBoneTransform = QueryBoneTransform(); - UpdateOwnerTransformIfNecessary(); - } - - int BoneFollower::GetTickOrder() - { - return AZ::TICK_ATTACHMENT; - } - - void BoneFollower::Reattach(bool detachFirst) - { -#ifdef AZ_ENABLE_TRACING - AZ::Entity* ownerEntity = nullptr; - AZ::Entity* targetEntity = nullptr; - AZ::ComponentApplicationBus::BroadcastResult(ownerEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_ownerId); - AZ::ComponentApplicationBus::BroadcastResult(targetEntity, &AZ::ComponentApplicationBus::Events::FindEntity, m_targetId); - AZ_TracePrintf("BoneFollower", "Reattaching entity '%s' to entity '%s'", ownerEntity ? ownerEntity->GetName().c_str() : "", - targetEntity ? targetEntity->GetName().c_str() : ""); -#endif - - if (m_targetId.IsValid() && detachFirst) - { - AttachmentComponentNotificationBus::Event(m_targetId, &AttachmentComponentNotificationBus::Events::OnDetached, m_ownerId); - } - - if (m_targetId != m_ownerId) - { - AttachmentComponentNotificationBus::Event(m_targetId, &AttachmentComponentNotificationBus::Events::OnAttached, m_ownerId); - } - } - - //========================================================================= - // AttachmentComponent - //========================================================================= - - void AttachmentComponent::Activate() - { -#ifdef AZ_ENABLE_TRACING - bool isStaticTransform = false; - AZ::TransformBus::EventResult(isStaticTransform, GetEntityId(), &AZ::TransformBus::Events::IsStaticTransform); - AZ_Warning("Attachment Component", !isStaticTransform, - "Attachment needs to move, but entity '%s' %s has a static transform.", GetEntity()->GetName().c_str(), GetEntityId().ToString().c_str()); -#endif - - m_boneFollower.Activate(GetEntity(), m_initialConfiguration, true); - } - - - void AttachmentComponent::Deactivate() - { - m_boneFollower.Deactivate(); - } -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Animation/AttachmentComponent.h b/Gems/LmbrCentral/Code/Source/Animation/AttachmentComponent.h deleted file mode 100644 index f2ef428ac2..0000000000 --- a/Gems/LmbrCentral/Code/Source/Animation/AttachmentComponent.h +++ /dev/null @@ -1,186 +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 -#include -#include - -struct ISkeletonPose; - -namespace LmbrCentral -{ - /*! - * Configuration data for AttachmentComponent. - */ - struct AttachmentConfiguration - { - AZ_TYPE_INFO(AttachmentConfiguration, "{74B5DC69-DE44-4640-836A-55339E116795}"); - - virtual ~AttachmentConfiguration() = default; - - static void Reflect(AZ::ReflectContext* context); - - //! Attach to this entity. - AZ::EntityId m_targetId; - - //! Attach to this bone on target entity. - AZStd::string m_targetBoneName; - - //! Offset from target. - AZ::Transform m_targetOffset = AZ::Transform::Identity(); - - //! Whether to attach to target upon activation. - //! If false, the entity remains detached until Attach() is called. - bool m_attachedInitially = true; - - //! Source from which to retrieve scale information. - enum class ScaleSource : AZ::u8 - { - WorldScale, // Scaled in world space. - TargetEntityScale, // Adopt scaling of attachment target entity. - TargetBoneScale, // Adopt scaling of attachment target entity/joint. - }; - ScaleSource m_scaleSource = ScaleSource::WorldScale; - }; - - /* - * Common functionality for game and editor attachment components. - * The BoneFollower tracks movement of the target's bone and - * updates the owning entity's TransformComponent to follow. - * This class should be a member within the attachment component - * and be activated/deactivated along with the component. - * \ref AttachmentComponent - */ - class BoneFollower - : public AttachmentComponentRequestBus::Handler - , public AZ::TransformNotificationBus::Handler - , public MeshComponentNotificationBus::Handler - , public AZ::Data::AssetBus::Handler - , public AZ::TickBus::Handler - { - public: - void Activate(AZ::Entity* owner, const AttachmentConfiguration& initialConfiguration, bool targetCanAnimate); - void Deactivate(); - - //////////////////////////////////////////////////////////////////////// - // AttachmentComponentRequests - void Reattach(bool detachFirst); - void Attach(AZ::EntityId targetId, const char* targetBoneName, const AZ::Transform& offset) override; - void Detach() override; - void SetAttachmentOffset(const AZ::Transform& offset) override; - const char* GetJointName() override; - AZ::EntityId GetTargetEntityId() override; - AZ::Transform GetOffset() override; - //////////////////////////////////////////////////////////////////////// - - private: - - //////////////////////////////////////////////////////////////////////// - // AZ::TickBus - //! Check target bone transform every frame. - void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - //! Make sure target bone transform updates after animation update. - int GetTickOrder() override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // AZ::TransformNotificationBus - //! When target's transform changes - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - //////////////////////////////////////////////////////////////////////// - - //////////////////////////////////////////////////////////////////////// - // MeshComponentEvents - //! When target's mesh changes - void OnMeshCreated(const AZ::Data::Asset& asset) override; - //////////////////////////////////////////////////////////////////////// - - void BindTargetBone(); - - AZ::Transform QueryBoneTransform() const; - - void UpdateOwnerTransformIfNecessary(); - - //! Entity which which is being attached. - AZ::EntityId m_ownerId; - - //! Whether to query bone position per-frame (false while in editor) - bool m_targetCanAnimate = false; - - AZ::EntityId m_targetId; - AZStd::string m_targetBoneName; - AZ::Transform m_targetOffset; //!< local transform - AZ::Transform m_targetBoneTransform; //!< local transform of bone - AZ::Transform m_targetEntityTransform; //!< world transform of target - bool m_isTargetEntityTransformKnown = false; - - //! Cached value, so we don't update owner's position unnecessarily. - AZ::Transform m_cachedOwnerTransform; - bool m_isUpdatingOwnerTransform = false; //!< detect infinite loops when updating owner's transform - - // Cached character values to avoid repeated lookup. - // These are set by calling ResetCharacter() - int m_targetBoneId; //!< negative when bone not found - - AttachmentConfiguration::ScaleSource m_scaleSource; - }; - - /*! - * The AttachmentComponent lets an entity stick to a particular bone on - * a target entity. This is achieved by tracking movement of the target's - * bone and updating the entity's TransformComponent accordingly. - */ - class AttachmentComponent - : public AZ::Component - { - public: - AZ_COMPONENT(AttachmentComponent, "{2D17A64A-7AC5-4C02-AC36-C5E8141FFDDF}"); - - friend class EditorAttachmentComponent; - - static void Reflect(AZ::ReflectContext* context); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("AttachmentService", 0x5aaa7b63)); - } - - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("AttachmentService", 0x5aaa7b63)); - } - - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); - } - - ~AttachmentComponent() override = default; - - private: - //////////////////////////////////////////////////////////////////////// - // AZ::Component - void Activate() override; - void Deactivate() override; - //////////////////////////////////////////////////////////////////////// - - //! Initial configuration for m_attachment - AttachmentConfiguration m_initialConfiguration; - - //! Implements actual attachment functionality - BoneFollower m_boneFollower; - }; -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Animation/EditorAttachmentComponent.cpp b/Gems/LmbrCentral/Code/Source/Animation/EditorAttachmentComponent.cpp deleted file mode 100644 index 265f4ad864..0000000000 --- a/Gems/LmbrCentral/Code/Source/Animation/EditorAttachmentComponent.cpp +++ /dev/null @@ -1,238 +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 "LmbrCentral_precompiled.h" -#include "EditorAttachmentComponent.h" -#include -#include -#include -#include - -namespace LmbrCentral -{ - void EditorAttachmentComponent::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serializeContext = azrtti_cast(context); - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field("Target ID", &EditorAttachmentComponent::m_targetId) - ->Field("Target Bone Name", &EditorAttachmentComponent::m_targetBoneName) - ->Field("Position Offset", &EditorAttachmentComponent::m_positionOffset) - ->Field("Rotation Offset", &EditorAttachmentComponent::m_rotationOffset) - ->Field("Scale Offset", &EditorAttachmentComponent::m_scaleOffset) - ->Field("Attached Initially", &EditorAttachmentComponent::m_attachedInitially) - ->Field("Scale Source", &EditorAttachmentComponent::m_scaleSource) - ; - - AZ::EditContext* editContext = serializeContext->GetEditContext(); - if (editContext) - { - editContext->Class( - "Attachment", "The Attachment component lets an entity attach to a bone on the skeleton of another entity") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Animation") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Attachment.svg") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Attachment.png") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-attachment.html") - ->DataElement(0, &EditorAttachmentComponent::m_targetId, - "Target entity", "Attach to this entity.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetIdChanged) - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorAttachmentComponent::m_targetBoneName, - "Joint name", "Attach to this joint on target entity.") - ->Attribute(AZ::Edit::Attributes::StringList, &EditorAttachmentComponent::GetTargetBoneOptions) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetBoneChanged) - ->DataElement(0, &EditorAttachmentComponent::m_positionOffset, - "Position offset", "Local position offset from target bone") - ->Attribute(AZ::Edit::Attributes::Suffix, "m") - ->Attribute(AZ::Edit::Attributes::Step, 0.01f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetOffsetChanged) - ->DataElement(0, &EditorAttachmentComponent::m_rotationOffset, - "Rotation offset", "Local rotation offset from target bone") - ->Attribute(AZ::Edit::Attributes::Suffix, "deg") - ->Attribute(AZ::Edit::Attributes::Step, 0.01f) - ->Attribute(AZ::Edit::Attributes::Min, -AZ::RadToDeg(AZ::Constants::TwoPi)) - ->Attribute(AZ::Edit::Attributes::Max, AZ::RadToDeg(AZ::Constants::TwoPi)) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetOffsetChanged) - ->DataElement(0, &EditorAttachmentComponent::m_scaleOffset, - "Scale offset", "Local scale offset from target entity") - ->Attribute(AZ::Edit::Attributes::Step, 0.1f) - ->Attribute(AZ::Edit::Attributes::Min, 0.001f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnTargetOffsetChanged) - ->DataElement(0, &EditorAttachmentComponent::m_attachedInitially, - "Attached initially", "Whether to attach to target upon activation.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnAttachedInitiallyChanged) - ->DataElement(AZ::Edit::UIHandlers::ComboBox, &EditorAttachmentComponent::m_scaleSource, - "Scaling", "How object scale should be determined. " - "Use world scale = Attached object is scaled in world space, Use target entity scale = Attached object adopts scale of target entity., Use target bone scale = Attached object adopts scale of target entity/joint.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorAttachmentComponent::OnScaleSourceChanged) - ->EnumAttribute(AttachmentConfiguration::ScaleSource::WorldScale, "Use world scale") - ->EnumAttribute(AttachmentConfiguration::ScaleSource::TargetEntityScale, "Use target entity scale") - ->EnumAttribute(AttachmentConfiguration::ScaleSource::TargetBoneScale, "Use target bone scale") - ; - } - } - } - - void EditorAttachmentComponent::Activate() - { - Base::Activate(); - m_boneFollower.Activate(GetEntity(), - CreateAttachmentConfiguration(), - false); // Entity's don't animate in Editor - } - - void EditorAttachmentComponent::Deactivate() - { - m_boneFollower.Deactivate(); - Base::Deactivate(); - } - - void EditorAttachmentComponent::BuildGameEntity(AZ::Entity* gameEntity) - { - AttachmentComponent* component = gameEntity->CreateComponent(); - if (component) - { - component->m_initialConfiguration = CreateAttachmentConfiguration(); - } - } - - AttachmentConfiguration EditorAttachmentComponent::CreateAttachmentConfiguration() const - { - AttachmentConfiguration configuration; - configuration.m_targetId = m_targetId; - configuration.m_targetBoneName = m_targetBoneName; - configuration.m_targetOffset = GetTargetOffset(); - configuration.m_attachedInitially = m_attachedInitially; - configuration.m_scaleSource = m_scaleSource; - return configuration; - } - - AZ::Transform EditorAttachmentComponent::GetTargetOffset() const - { - AZ::Transform offset = AZ::ConvertEulerDegreesToTransform(m_rotationOffset); - offset.SetTranslation(m_positionOffset); - offset.MultiplyByScale(m_scaleOffset); - return offset; - } - - AZStd::vector EditorAttachmentComponent::GetTargetBoneOptions() const - { - AZStd::vector names; - - // insert blank entry, so user may choose to bind to NO bone. - names.push_back(""); - - // track whether currently-set bone is found - bool currentTargetBoneFound = false; - - // Get character and iterate over bones - AZ::u32 jointCount = 0; - SkeletalHierarchyRequestBus::EventResult(jointCount, m_targetId, &SkeletalHierarchyRequests::GetJointCount); - for (AZ::u32 jointIndex = 0; jointIndex < jointCount; ++jointIndex) - { - const char* name = nullptr; - SkeletalHierarchyRequestBus::EventResult(name, m_targetId, &SkeletalHierarchyRequests::GetJointNameByIndex, jointIndex); - if (name) - { - names.push_back(name); - - if (!currentTargetBoneFound) - { - currentTargetBoneFound = (m_targetBoneName == names.back()); - } - } - } - - // If we never found currently-set bone name, - // stick it at top of list, just in case user wants to keep it anyway - if (!currentTargetBoneFound && !m_targetBoneName.empty()) - { - names.insert(names.begin(), m_targetBoneName); - } - - return names; - } - - AZ::u32 EditorAttachmentComponent::OnTargetIdChanged() - { - // Warn about bad setups (it won't crash, but it's nice to handle this early) - if (m_targetId == GetEntityId()) - { - AZ_Warning(GetEntity()->GetName().c_str(), false, "AttachmentComponent cannot target self.") - m_targetId.SetInvalid(); - } - - // Warn about children attaching to a parent - AZ::EntityId parentOfTarget; - AZ::TransformBus::EventResult(parentOfTarget, m_targetId, &AZ::TransformBus::Events::GetParentId); - while (parentOfTarget.IsValid()) - { - if (parentOfTarget == GetEntityId()) - { - AZ_Warning(GetEntity()->GetName().c_str(), parentOfTarget != GetEntityId(), "AttachmentComponent cannot target child entity"); - m_targetId.SetInvalid(); - break; - } - - AZ::EntityId currentParentId = parentOfTarget; - parentOfTarget.SetInvalid(); - AZ::TransformBus::EventResult(parentOfTarget, currentParentId, &AZ::TransformBus::Events::GetParentId); - } - - AttachOrDetachAsNecessary(); - - return AZ::Edit::PropertyRefreshLevels::AttributesAndValues; // refresh bone options - } - - AZ::u32 EditorAttachmentComponent::OnTargetBoneChanged() - { - AttachOrDetachAsNecessary(); - return AZ::Edit::PropertyRefreshLevels::None; - } - - AZ::u32 EditorAttachmentComponent::OnTargetOffsetChanged() - { - EBUS_EVENT_ID(GetEntityId(), AttachmentComponentRequestBus, SetAttachmentOffset, GetTargetOffset()); - return AZ::Edit::PropertyRefreshLevels::None; - } - - AZ::u32 EditorAttachmentComponent::OnAttachedInitiallyChanged() - { - AttachOrDetachAsNecessary(); - return AZ::Edit::PropertyRefreshLevels::None; - } - - AZ::u32 EditorAttachmentComponent::OnScaleSourceChanged() - { - m_boneFollower.Deactivate(); - m_boneFollower.Activate(GetEntity(), - CreateAttachmentConfiguration(), - false); - return AZ::Edit::PropertyRefreshLevels::None; - } - - void EditorAttachmentComponent::AttachOrDetachAsNecessary() - { - if (m_attachedInitially && m_targetId.IsValid()) - { - EBUS_EVENT_ID(GetEntityId(), AttachmentComponentRequestBus, Attach, m_targetId, m_targetBoneName.c_str(), GetTargetOffset()); - } - else - { - EBUS_EVENT_ID(GetEntityId(), AttachmentComponentRequestBus, Detach); - } - } -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Animation/EditorAttachmentComponent.h b/Gems/LmbrCentral/Code/Source/Animation/EditorAttachmentComponent.h deleted file mode 100644 index 808ffd393e..0000000000 --- a/Gems/LmbrCentral/Code/Source/Animation/EditorAttachmentComponent.h +++ /dev/null @@ -1,101 +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 "AttachmentComponent.h" - -namespace LmbrCentral -{ - /*! - * In-editor attachment component. - * \ref AttachmentComponent - */ - class EditorAttachmentComponent - : public AzToolsFramework::Components::EditorComponentBase - { - private: - using Base = AzToolsFramework::Components::EditorComponentBase; - public: - AZ_COMPONENT(EditorAttachmentComponent, "{DA6072FD-E696-47D8-81D9-1F77D3464200}", Base); - static void Reflect(AZ::ReflectContext* context); - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - AttachmentComponent::GetProvidedServices(provided); - } - - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - AttachmentComponent::GetIncompatibleServices(incompatible); - } - - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - AttachmentComponent::GetRequiredServices(required); - } - - ~EditorAttachmentComponent() override = default; - void BuildGameEntity(AZ::Entity* gameEntity) override; - - protected: - - ////////////////////////////////////////////////////////////////////////// - // AZ::Component interface implementation - void Activate() override; - void Deactivate() override; - ////////////////////////////////////////////////////////////////////////// - - AZ::u32 OnTargetIdChanged(); - AZ::u32 OnTargetBoneChanged(); - AZ::u32 OnTargetOffsetChanged(); - AZ::u32 OnAttachedInitiallyChanged(); - AZ::u32 OnScaleSourceChanged(); - - //! Invoked when an attachment property changes - void AttachOrDetachAsNecessary(); - - //! For populating ComboBox - AZStd::vector GetTargetBoneOptions() const; - - //! Create runtime configuration from editor configuration - AttachmentConfiguration CreateAttachmentConfiguration() const; - - //! Create AZ::Transform from position and rotation - AZ::Transform GetTargetOffset() const; - - //! Attach to this entity. - AZ::EntityId m_targetId; - - //! Attach to this bone on target entity. - AZStd::string m_targetBoneName; - - //! Offset from target bone's position. - AZ::Vector3 m_positionOffset = AZ::Vector3::CreateZero(); - - //! Offset from target bone's rotation. - AZ::Vector3 m_rotationOffset = AZ::Vector3::CreateZero(); - - //! Offset from target entity's scale. - AZ::Vector3 m_scaleOffset = AZ::Vector3::CreateOne(); - - //! Observe scale information from the specified source. - AttachmentConfiguration::ScaleSource m_scaleSource = AttachmentConfiguration::ScaleSource::WorldScale; - - //! Whether to attach to target upon activation. - //! If false, the entity remains detached until Attach() is called. - bool m_attachedInitially = true; - - //! Implements actual attachment functionality - LmbrCentral::BoneFollower m_boneFollower; - }; -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp b/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp index 974dddc6e0..ceac768e79 100644 --- a/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp +++ b/Gems/LmbrCentral/Code/Source/LmbrCentral.cpp @@ -21,7 +21,6 @@ #include // Component descriptors -#include "Animation/AttachmentComponent.h" #include "Audio/AudioAreaEnvironmentComponent.h" #include "Audio/AudioEnvironmentComponent.h" #include "Audio/AudioListenerComponent.h" @@ -33,7 +32,6 @@ #include "Audio/AudioSystemComponent.h" #include "Audio/AudioTriggerComponent.h" #include "Bundling/BundlingSystemComponent.h" -#include "Rendering/MeshComponent.h" #include "Ai/NavigationComponent.h" #include "Scripting/TagComponent.h" #include "Scripting/SimpleStateComponent.h" @@ -74,9 +72,6 @@ #include #include -// Asset handlers -#include - // Scriptable Ebus Registration #include "Events/ReflectScriptableEvents.h" @@ -194,7 +189,6 @@ namespace LmbrCentral : AZ::Module() { m_descriptors.insert(m_descriptors.end(), { - AttachmentComponent::CreateDescriptor(), AudioAreaEnvironmentComponent::CreateDescriptor(), AudioEnvironmentComponent::CreateDescriptor(), AudioListenerComponent::CreateDescriptor(), @@ -209,7 +203,6 @@ namespace LmbrCentral LmbrCentralAllocatorComponent::CreateDescriptor(), LmbrCentralAssetBuilderAllocatorComponent::CreateDescriptor(), LmbrCentralSystemComponent::CreateDescriptor(), - MeshComponent::CreateDescriptor(), NavigationComponent::CreateDescriptor(), SimpleStateComponent::CreateDescriptor(), SpawnerComponent::CreateDescriptor(), @@ -329,13 +322,6 @@ namespace LmbrCentral ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) ; } - - MaterialHandle::Reflect(serializeContext); - } - - if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) - { - MaterialHandle::Reflect(behaviorContext); } ReflectScriptableEvents::Reflect(context); @@ -379,10 +365,6 @@ namespace LmbrCentral // Register asset handlers. Requires "AssetDatabaseService" AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!"); - auto meshAssetHandler = aznew MeshAssetHandler(); - meshAssetHandler->Register(); // registers self with AssetManager - m_assetHandlers.emplace_back(meshAssetHandler); - // Add asset types and extensions to AssetCatalog. Uses "AssetCatalogService". auto assetCatalog = AZ::Data::AssetCatalogRequestBus::FindFirstHandler(); if (assetCatalog) @@ -518,8 +500,6 @@ namespace LmbrCentral gEnv = system.GetGlobalEnvironment(); #endif - REGISTER_INT(s_meshAssetHandler_AsyncCvar, 1, 0, "Enables asynchronous loading of legacy mesh formats"); - // Enable catalog now that application's asset root is set. if (system.GetGlobalEnvironment()->IsEditor()) { @@ -536,11 +516,6 @@ namespace LmbrCentral void LmbrCentralSystemComponent::OnCrySystemShutdown([[maybe_unused]] ISystem& system) { - if (gEnv->pConsole) - { - gEnv->pConsole->UnregisterVariable(s_meshAssetHandler_AsyncCvar, true); - } - EBUS_EVENT(AZ::Data::AssetCatalogRequestBus, StopMonitoringAssets); #if !defined(AZ_MONOLITHIC_BUILD) diff --git a/Gems/LmbrCentral/Code/Source/LmbrCentralEditor.cpp b/Gems/LmbrCentral/Code/Source/LmbrCentralEditor.cpp index 14091a2e7a..8536733b01 100644 --- a/Gems/LmbrCentral/Code/Source/LmbrCentralEditor.cpp +++ b/Gems/LmbrCentral/Code/Source/LmbrCentralEditor.cpp @@ -16,7 +16,6 @@ #include "Ai/EditorNavigationAreaComponent.h" #include "Ai/EditorNavigationSeedComponent.h" -#include "Animation/EditorAttachmentComponent.h" #include "Audio/EditorAudioAreaEnvironmentComponent.h" #include "Audio/EditorAudioEnvironmentComponent.h" #include "Audio/EditorAudioListenerComponent.h" @@ -25,7 +24,6 @@ #include "Audio/EditorAudioRtpcComponent.h" #include "Audio/EditorAudioSwitchComponent.h" #include "Audio/EditorAudioTriggerComponent.h" -#include "Rendering/EditorMeshComponent.h" #include "Scripting/EditorLookAtComponent.h" #include "Scripting/EditorRandomTimedSpawnerComponent.h" #include "Scripting/EditorSpawnerComponent.h" @@ -61,7 +59,6 @@ namespace LmbrCentral : LmbrCentralModule() { m_descriptors.insert(m_descriptors.end(), { - EditorAttachmentComponent::CreateDescriptor(), EditorAudioAreaEnvironmentComponent::CreateDescriptor(), EditorAudioEnvironmentComponent::CreateDescriptor(), EditorAudioListenerComponent::CreateDescriptor(), @@ -70,7 +67,6 @@ namespace LmbrCentral EditorAudioRtpcComponent::CreateDescriptor(), EditorAudioSwitchComponent::CreateDescriptor(), EditorAudioTriggerComponent::CreateDescriptor(), - EditorMeshComponent::CreateDescriptor(), EditorTagComponent::CreateDescriptor(), EditorSphereShapeComponent::CreateDescriptor(), EditorDiskShapeComponent::CreateDescriptor(), @@ -107,8 +103,6 @@ namespace LmbrCentral typeIds.emplace_back(descriptor->GetUuid()); } EBUS_EVENT(AzFramework::MetricsPlainTextNameRegistrationBus, RegisterForNameSending, typeIds); - - EditorMeshBus::Handler::BusConnect(); } LmbrCentralEditorModule::~LmbrCentralEditorModule() @@ -123,11 +117,6 @@ namespace LmbrCentral return requiredComponents; } - - bool LmbrCentralEditorModule::AddMeshComponentWithAssetId(const AZ::EntityId& targetEntity, const AZ::Uuid& meshAssetId) - { - return AddMeshComponentWithMesh(targetEntity, meshAssetId); - } } // namespace LmbrCentral AZ_DECLARE_MODULE_CLASS(Gem_LmbrCentralEditor, LmbrCentral::LmbrCentralEditorModule) diff --git a/Gems/LmbrCentral/Code/Source/LmbrCentralEditor.h b/Gems/LmbrCentral/Code/Source/LmbrCentralEditor.h index f180c21d8d..7a9dbd01ba 100644 --- a/Gems/LmbrCentral/Code/Source/LmbrCentralEditor.h +++ b/Gems/LmbrCentral/Code/Source/LmbrCentralEditor.h @@ -13,13 +13,6 @@ #include "LmbrCentral.h" -#include - -namespace Water -{ - class WaterVolumeConverter; -} - namespace LmbrCentral { /** @@ -31,7 +24,6 @@ namespace LmbrCentral */ class LmbrCentralEditorModule : public LmbrCentralModule - , public EditorMeshBus::Handler { public: AZ_RTTI(LmbrCentralEditorModule, "{1BF648D7-3703-4B52-A688-67C253A059F2}", LmbrCentralModule); @@ -39,7 +31,5 @@ namespace LmbrCentral LmbrCentralEditorModule(); ~LmbrCentralEditorModule(); AZ::ComponentTypeList GetRequiredSystemComponents() const override; - - bool AddMeshComponentWithAssetId(const AZ::EntityId& targetEntity, const AZ::Uuid& meshAssetId) override; }; } // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Rendering/EditorMeshComponent.cpp b/Gems/LmbrCentral/Code/Source/Rendering/EditorMeshComponent.cpp deleted file mode 100644 index 64254ee8f0..0000000000 --- a/Gems/LmbrCentral/Code/Source/Rendering/EditorMeshComponent.cpp +++ /dev/null @@ -1,580 +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 "LmbrCentral_precompiled.h" - -#include "EditorMeshComponent.h" -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#include // For updating nav tiles on creation of editor physics. -#include // For basic physicalization at edit-time for object snapping. -#include -#include -#include - -#include -#include -#include - -namespace LmbrCentral -{ - AZ_CVAR(bool, cl_editorMeshIntersectionDebug, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Enable editor mesh intersection debugging"); - - void EditorMeshComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("Static Mesh Render Node", &EditorMeshComponent::m_mesh) - ; - - if (AZ::EditContext* editContext = serializeContext->GetEditContext()) - { - editContext->Class("Mesh", "The Mesh component is the primary method of adding visual geometry to entities") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Rendering") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/StaticMesh.svg") - ->Attribute(AZ::Edit::Attributes::PrimaryAssetType, AZ::AzTypeInfo::Uuid()) - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/StaticMesh.png") - ->Attribute(AZ::Edit::Attributes::DynamicIconOverride, &EditorMeshComponent::GetMeshViewportIconPath) - ->Attribute(AZ::Edit::Attributes::PreferNoViewportIcon, true) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::HelpPageURL, "https://docs.aws.amazon.com/lumberyard/latest/userguide/component-static-mesh.html") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->DataElement(AZ::Edit::UIHandlers::Default, &EditorMeshComponent::m_mesh) - ; - - editContext->Class( - "Render Options", "Rendering options for the mesh.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("Game", 0x232b318c)) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20)) - - ->ClassElement(AZ::Edit::ClassElements::Group, "Options") - ->Attribute(AZ::Edit::Attributes::AutoExpand, false) - - ->DataElement(AZ::Edit::UIHandlers::Slider, &MeshComponentRenderNode::MeshRenderOptions::m_opacity, "Opacity", "Opacity value") - ->Attribute(AZ::Edit::Attributes::Min, 0.f) - ->Attribute(AZ::Edit::Attributes::Max, 1.f) - ->Attribute(AZ::Edit::Attributes::Step, 0.1f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_maxViewDist, "Max view distance", "Maximum view distance in meters.") - ->Attribute(AZ::Edit::Attributes::Suffix, " m") - ->Attribute(AZ::Edit::Attributes::Min, 0.f) - ->Attribute(AZ::Edit::Attributes::Max, &MeshComponentRenderNode::GetDefaultMaxViewDist) - ->Attribute(AZ::Edit::Attributes::Step, 0.1f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_viewDistMultiplier, "View distance multiplier", "Adjusts max view distance. If 1.0 then default is used. 1.1 would be 10% further than default.") - ->Attribute(AZ::Edit::Attributes::Suffix, "x") - ->Attribute(AZ::Edit::Attributes::Min, 0.f) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->DataElement(AZ::Edit::UIHandlers::Slider, &MeshComponentRenderNode::MeshRenderOptions::m_lodRatio, "LOD distance ratio", "Controls LOD ratio over distance.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->Attribute(AZ::Edit::Attributes::Min, 0) - ->Attribute(AZ::Edit::Attributes::Max, 255) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_castShadows, "Cast shadows", "Casts shadows.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_lodBoundingBoxBased, "LOD based on Bounding Boxes", "LOD based on Bounding Boxes.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_useVisAreas, "Use VisAreas", "Allow VisAreas to control this component's visibility.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - - ->ClassElement(AZ::Edit::ClassElements::Group, "Advanced") - ->Attribute(AZ::Edit::Attributes::AutoExpand, false) - - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_rainOccluder, "Rain occluder", "Occludes dynamic raindrops.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->Attribute(AZ::Edit::Attributes::Visibility, &MeshComponentRenderNode::MeshRenderOptions::StaticPropertyVisibility) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_affectDynamicWater, "Affect dynamic water", "Will generate ripples in dynamic water.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->Attribute(AZ::Edit::Attributes::Visibility, &MeshComponentRenderNode::MeshRenderOptions::StaticPropertyVisibility) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_receiveWind, "Receive wind", "Receives wind.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMajorChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_acceptDecals, "Accept decals", "Can receive decals.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_affectNavmesh, "Affect navmesh", "Will affect navmesh generation.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->Attribute(AZ::Edit::Attributes::Visibility, &MeshComponentRenderNode::MeshRenderOptions::StaticPropertyVisibility) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_visibilityOccluder, "Visibility occluder", "Is appropriate for occluding visibility of other objects.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->Attribute(AZ::Edit::Attributes::Visibility, &MeshComponentRenderNode::MeshRenderOptions::StaticPropertyVisibility) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_dynamicMesh, "Deformable mesh", "Enables vertex deformation on mesh.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMajorChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::MeshRenderOptions::m_affectGI, "Affects GI", "Affects the global illumination results.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::MeshRenderOptions::OnMinorChanged) - ->Attribute(AZ::Edit::Attributes::Visibility, &MeshComponentRenderNode::MeshRenderOptions::StaticPropertyVisibility) - ; - - editContext->Class( - "Mesh Rendering", "Attach geometry to the entity.") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20)) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::m_visible, "Visible", "Is currently visible.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::RefreshRenderState) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::m_meshAsset, "Mesh asset", "Mesh asset reference") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::OnAssetPropertyChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::m_material, "Material override", "Optionally specify an override material.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::OnAssetPropertyChanged) - ->DataElement(AZ::Edit::UIHandlers::Default, &MeshComponentRenderNode::m_renderOptions, "Render options", "Render/draw options.") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &MeshComponentRenderNode::RefreshRenderState) - ; - } - } - - if (auto behaviorContext = azrtti_cast(context)) - { - behaviorContext->Class()->RequestBus("MeshComponentRequestBus"); - } - } - - void EditorMeshComponent::Activate() - { - EditorComponentBase::Activate(); - - m_mesh.AttachToEntity(m_entity->GetId()); - bool isStatic = false; - AZ::TransformBus::EventResult(isStatic, m_entity->GetId(), &AZ::TransformBus::Events::IsStaticTransform); - m_mesh.SetTransformStaticState(isStatic); - - bool visible = false; - AzToolsFramework::EditorEntityInfoRequestBus::EventResult( - visible, GetEntityId(), &AzToolsFramework::EditorEntityInfoRequestBus::Events::IsVisible); - m_mesh.UpdateAuxiliaryRenderFlags(!visible, ERF_HIDDEN); - - // Note we are purposely connecting to buses before calling m_mesh.CreateMesh(). - // m_mesh.CreateMesh() can result in events (eg: OnMeshCreated) that we want receive. - MaterialOwnerRequestBus::Handler::BusConnect(m_entity->GetId()); - AzFramework::BoundsRequestBus::Handler::BusConnect(m_entity->GetId()); - MeshComponentRequestBus::Handler::BusConnect(m_entity->GetId()); - MeshComponentNotificationBus::Handler::BusConnect(m_entity->GetId()); - LegacyMeshComponentRequestBus::Handler::BusConnect(m_entity->GetId()); - RenderNodeRequestBus::Handler::BusConnect(m_entity->GetId()); - AZ::TransformNotificationBus::Handler::BusConnect(m_entity->GetId()); - AzToolsFramework::EditorVisibilityNotificationBus::Handler::BusConnect(GetEntityId()); - AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId()); - AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusConnect(GetEntityId()); - AzToolsFramework::EditorComponentSelectionNotificationsBus::Handler::BusConnect(GetEntityId()); - AzFramework::AssetCatalogEventBus::Handler::BusConnect(); - AzFramework::EntityIdContextQueryBus::EventResult(m_contextId, GetEntityId(), &AzFramework::EntityIdContextQueries::GetOwningContextId); - AzFramework::RenderGeometry::IntersectionRequestBus::Handler::BusConnect({ GetEntityId(), m_contextId }); - - m_mesh.m_renderOptions.m_changeCallback = - [this]() - { - m_mesh.RefreshRenderState(); - AffectNavmesh(); - }; - - m_mesh.CreateMesh(); - } - - void EditorMeshComponent::Deactivate() - { - AzFramework::AssetCatalogEventBus::Handler::BusDisconnect(); - AZ::Data::AssetBus::Handler::BusDisconnect(); - MaterialOwnerRequestBus::Handler::BusDisconnect(); - AzFramework::BoundsRequestBus::Handler::BusDisconnect(); - MeshComponentRequestBus::Handler::BusDisconnect(); - MeshComponentNotificationBus::Handler::BusDisconnect(); - LegacyMeshComponentRequestBus::Handler::BusDisconnect(); - RenderNodeRequestBus::Handler::BusDisconnect(); - AZ::TransformNotificationBus::Handler::BusDisconnect(); - AzToolsFramework::EditorVisibilityNotificationBus::Handler::BusDisconnect(); - AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); - AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusDisconnect(); - AzToolsFramework::EditorComponentSelectionNotificationsBus::Handler::BusDisconnect(); - - AzFramework::RenderGeometry::IntersectionRequestBus::Handler::BusDisconnect(); - - m_mesh.m_renderOptions.m_changeCallback = nullptr; - - m_mesh.DestroyMesh(); - m_mesh.AttachToEntity(AZ::EntityId()); - - EditorComponentBase::Deactivate(); - } - - - void EditorMeshComponent::OnMeshCreated(const AZ::Data::Asset& asset) - { - AZ::Data::AssetBus::Handler::BusDisconnect(); - AZ::Data::AssetBus::Handler::BusConnect(asset.GetId()); - - using namespace AzFramework::RenderGeometry; - IntersectionNotificationBus::Event(m_contextId, &IntersectionNotifications::OnGeometryChanged, GetEntityId()); - } - - void EditorMeshComponent::OnMeshDestroyed() - { - using namespace AzFramework::RenderGeometry; - IntersectionNotificationBus::Event(m_contextId, &IntersectionNotifications::OnGeometryChanged, GetEntityId()); - } - - IRenderNode* EditorMeshComponent::GetRenderNode() - { - return &m_mesh; - } - - float EditorMeshComponent::GetRenderNodeRequestBusOrder() const - { - return s_renderNodeRequestBusOrder; - } - - void EditorMeshComponent::OnTransformChanged(const AZ::Transform& /*local*/, const AZ::Transform& world) - { - AZ_UNUSED(world); - - using namespace AzFramework::RenderGeometry; - IntersectionNotificationBus::Event(m_contextId, &IntersectionNotifications::OnGeometryChanged, GetEntityId()); - } - - void EditorMeshComponent::OnStaticChanged(bool isStatic) - { - m_mesh.SetTransformStaticState(isStatic); - if (m_mesh.m_renderOptions.m_changeCallback) - { - m_mesh.m_renderOptions.m_changeCallback(); - } - AffectNavmesh(); - } - - AZ::Aabb EditorMeshComponent::GetWorldBounds() - { - return m_mesh.CalculateWorldAABB(); - } - - AZ::Aabb EditorMeshComponent::GetLocalBounds() - { - return m_mesh.CalculateLocalAABB(); - } - - AzFramework::RenderGeometry::RayResult EditorMeshComponent::RenderGeometryIntersect(const AzFramework::RenderGeometry::RayRequest& ray) - { - AzFramework::RenderGeometry::RayResult result; - if (!GetVisibility() && ray.m_onlyVisible) - { - return result; - } - - if (IStatObj* geometry = GetStatObj()) - { - const AZ::Vector3 rayDirection = (ray.m_endWorldPosition - ray.m_startWorldPosition); - const AZ::Transform& transform = GetTransform()->GetWorldTM(); - const AZ::Transform inverseTransform = transform.GetInverse(); - - const AZ::Vector3 rayStartLocal = inverseTransform.TransformPoint(ray.m_startWorldPosition); - const AZ::Vector3 rayDistNormLocal = inverseTransform.TransformVector(rayDirection).GetNormalized(); - - SRayHitInfo hi; - hi.inReferencePoint = AZVec3ToLYVec3(rayStartLocal); - hi.inRay = Ray(hi.inReferencePoint, AZVec3ToLYVec3(rayDistNormLocal)); - hi.bInFirstHit = true; - hi.bGetVertColorAndTC = true; - - if (geometry->RayIntersection(hi)) - { - AZ::Matrix3x4 invTransformMatrix = AZ::Matrix3x4::CreateFromTransform(inverseTransform); - invTransformMatrix.Transpose(); - - result.m_uv = LYVec2ToAZVec2(hi.vHitTC); - result.m_worldPosition = transform.TransformPoint(LYVec3ToAZVec3(hi.vHitPos)); - result.m_worldNormal = invTransformMatrix.Multiply3x3(LYVec3ToAZVec3(hi.vHitNormal)).GetNormalized(); - result.m_distance = (result.m_worldPosition - ray.m_startWorldPosition).GetLength(); - result.m_entityAndComponent = { GetEntityId(), GetId() }; - if (cl_editorMeshIntersectionDebug) - { - m_debugPos = result.m_worldPosition; - m_debugNormal = result.m_worldNormal; - } - } - } - - return result; - } - - void EditorMeshComponent::SetMeshAsset(const AZ::Data::AssetId& id) - { - m_mesh.SetMeshAsset(id); - AzToolsFramework::ToolsApplicationRequests::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationRequests::AddDirtyEntity, - GetEntityId()); - } - - void EditorMeshComponent::SetMaterial(_smart_ptr material) - { - m_mesh.SetMaterial(material); - - AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, - AzToolsFramework::Refresh_AttributesAndValues); - } - - _smart_ptr EditorMeshComponent::GetMaterial() - { - return m_mesh.GetMaterial(); - } - - void EditorMeshComponent::SetPrimaryAsset(const AZ::Data::AssetId& assetId) - { - SetMeshAsset(assetId); - } - - void EditorMeshComponent::OnEntityVisibilityChanged(bool visibility) - { - m_mesh.UpdateAuxiliaryRenderFlags(!visibility, ERF_HIDDEN); - m_mesh.RefreshRenderState(); - } - - static void DecideColor( - const bool selected, const bool mouseHovered, const bool visible, - ColorB& triangleColor, ColorB& lineColor) - { - const ColorB translucentPurple = ColorB(250, 0, 250, 30); - - // default both colors to hidden - triangleColor = ColorB(AZ::u32(0)); - lineColor = ColorB(AZ::u32(0)); - - if (selected) - { - if (!visible) - { - lineColor = Col_Black; - - if (mouseHovered) - { - triangleColor = translucentPurple; - } - } - } - else - { - if (mouseHovered) - { - triangleColor = translucentPurple; - lineColor = AZColorToLYColorF(AzFramework::ViewportColors::HoverColor); - } - } - } - - void EditorMeshComponent::DisplayEntityViewport( - [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) - { - const bool mouseHovered = m_accentType == AzToolsFramework::EntityAccentType::Hover; - - IEditor* editor = nullptr; - AzToolsFramework::EditorRequests::Bus::BroadcastResult(editor, &AzToolsFramework::EditorRequests::GetEditor); - - const bool highlightGeometryOnMouseHover = editor->GetEditorSettings()->viewports.bHighlightMouseOverGeometry; - // if the mesh component is not visible, when selected we still draw the wireframe to indicate the shapes extent and position - const bool highlightGeometryWhenSelected = editor->GetEditorSettings()->viewports.bHighlightSelectedGeometry || !GetVisibility(); - - if ((!IsSelected() && mouseHovered && highlightGeometryOnMouseHover) || (IsSelected() && highlightGeometryWhenSelected)) - { - AZ::Transform transform = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult(transform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); - - ColorB triangleColor, lineColor; - DecideColor(IsSelected(), mouseHovered, GetVisibility(), triangleColor, lineColor); - - SGeometryDebugDrawInfo dd; - dd.tm = AZTransformToLYTransform(transform); - dd.bExtrude = true; - dd.color = triangleColor; - dd.lineColor = lineColor; - - if (IStatObj* geometry = GetStatObj()) - { - geometry->DebugDraw(dd); - } - } - - if (cl_editorMeshIntersectionDebug) - { - debugDisplay.DrawArrow(m_debugPos, m_debugPos + (0.1f * m_debugNormal), 0.1f); - debugDisplay.DrawBall(m_debugPos, 0.03f); - debugDisplay.DrawWireBox(GetWorldBounds().GetMin(), GetWorldBounds().GetMax()); - } - } - - void EditorMeshComponent::BuildGameEntity(AZ::Entity* gameEntity) - { - if (auto meshComponent = gameEntity->CreateComponent()) - { - m_mesh.CopyPropertiesTo(meshComponent->m_meshRenderNode); - // ensure we do not copy across the edit time entity id - meshComponent->m_meshRenderNode.m_renderOptions.m_attachedToEntityId = AZ::EntityId(); - } - } - - - IStatObj* EditorMeshComponent::GetStatObj() - { - return m_mesh.GetEntityStatObj(); - } - - bool EditorMeshComponent::GetVisibility() - { - return m_mesh.GetVisible(); - } - - void EditorMeshComponent::SetVisibility(bool visible) - { - m_mesh.SetVisible(visible); - } - - void EditorMeshComponent::AffectNavmesh() - { - // Refresh the nav tile when the flag changes. - INavigationSystem* pNavigationSystem = nullptr; // INavigationSystem will be converted to an AZInterface (LY-111343) - if (pNavigationSystem) - { - pNavigationSystem->WorldChanged(AZAabbToLyAABB(GetWorldBounds())); - } - } - - AZStd::string_view staticViewportIcon = "Icons/Components/Viewport/StaticMesh.png"; - AZStd::string_view dynamicViewportIcon = "Icons/Components/Viewport/DynamicMesh.png"; - AZStd::string EditorMeshComponent::GetMeshViewportIconPath() const - { - if (m_mesh.m_renderOptions.IsStatic()) - { - return staticViewportIcon; - } - - return dynamicViewportIcon; - } - - void EditorMeshComponent::OnAssetReloaded(AZ::Data::Asset /*asset*/) - { - using namespace AzFramework::RenderGeometry; - IntersectionNotificationBus::Event(m_contextId, &IntersectionNotifications::OnGeometryChanged, GetEntityId()); - } - - void EditorMeshComponent::OnCatalogAssetRemoved(const AZ::Data::AssetId& assetId, const AZ::Data::AssetInfo& /*assetInfo*/) - { - if (m_mesh.m_meshAsset.GetId() != assetId) - { - return; - } - // If this editor mesh component is loaded and active in the level, it's referencing an asset that was just removed. - // Clearing this asset reference will help visualize this change. Note that this won't clear all references to this - // asset automatically, any levels that aren't loaded won't have the reference removed. - - // Set the mesh asset to invalid on the main thread. - AZ::TickBus::QueueFunction([this, assetId]() - { - // Emit a warning so users know this has occurred, it may not be intentional because the asset was removed before - // the references were cleared. Do this on the main thread. - AZ_Warning("EditorMeshComponent", false, "asset with ID %s referenced by entity named '%s' with ID %s was removed, this reference will be cleared on the associated component.", - assetId.ToString().c_str(), - GetEntity() ? GetEntity()->GetName().c_str() : "Invalid entity", - GetEntityId().ToString().c_str()); - - m_mesh.DestroyMesh(); - AzToolsFramework::ToolsApplicationRequests::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationRequests::AddDirtyEntity, - GetEntityId()); - AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, - AzToolsFramework::Refresh_AttributesAndValues); - }); - } - - AZ::Aabb EditorMeshComponent::GetEditorSelectionBoundsViewport( - const AzFramework::ViewportInfo& /*viewportInfo*/) - { - return GetWorldBounds(); - } - - bool EditorMeshComponent::EditorSelectionIntersectRayViewport( - const AzFramework::ViewportInfo& /*viewportInfo*/, - const AZ::Vector3& src, const AZ::Vector3& dir, float& distance) - { - if (IStatObj* geometry = GetStatObj()) - { - AZ::Transform transform = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult(transform, GetEntityId(), &AZ::TransformBus::Events::GetWorldTM); - auto legacyTransform = AZTransformToLYTransform(transform); - const auto legacySrc = AZVec3ToLYVec3(src); - const auto legacyDir = AZVec3ToLYVec3(dir); - - const Matrix34 inverseTM = legacyTransform.GetInverted(); - const Vec3 raySrcLocal = inverseTM.TransformPoint(legacySrc); - const Vec3 rayDirLocal = inverseTM.TransformVector(legacyDir).GetNormalized(); - - SRayHitInfo hi; - hi.inReferencePoint = raySrcLocal; - hi.inRay = Ray(raySrcLocal, rayDirLocal); - if (geometry->RayIntersection(hi)) - { - const Vec3 worldHitPos = legacyTransform.TransformPoint(hi.vHitPos); - distance = legacySrc.GetDistance(worldHitPos); - return true; - } - } - - return false; - } - - void EditorMeshComponent::OnAccentTypeChanged(AzToolsFramework::EntityAccentType accent) - { - m_accentType = accent; - } - - bool AddMeshComponentWithMesh(const AZ::EntityId& targetEntity, const AZ::Uuid& meshAssetId) - { - // Error handling for failures should be done at the call site, this function can be invoked from Python. - if (!targetEntity.IsValid()) - { - return false; - } - AZ::ComponentTypeList componentsToAdd; - componentsToAdd.push_back(AZ::AzTypeInfo::Uuid()); - - AZStd::vector entityList; - entityList.push_back(targetEntity); - - AzToolsFramework::EntityCompositionRequests::AddComponentsOutcome outcome = - AZ::Failure(AZStd::string("Failed to call AddComponentsToEntities on EntityCompositionRequestBus")); - AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(outcome, &AzToolsFramework::EntityCompositionRequests::AddComponentsToEntities, entityList, componentsToAdd); - - if (!outcome.IsSuccess()) - { - return false; - } - - AZ::Data::AssetId meshAsset(meshAssetId); - - // If necessary, the call site can verify if the mesh was actually set. - LmbrCentral::MeshComponentRequestBus::Event( - targetEntity, - &LmbrCentral::MeshComponentRequestBus::Events::SetMeshAsset, - meshAsset); - return true; - } -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Rendering/EditorMeshComponent.h b/Gems/LmbrCentral/Code/Source/Rendering/EditorMeshComponent.h deleted file mode 100644 index 7617673e3b..0000000000 --- a/Gems/LmbrCentral/Code/Source/Rendering/EditorMeshComponent.h +++ /dev/null @@ -1,175 +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 -#include - -#include -#include - -#include -#include - -#include -#include - -#include "MeshComponent.h" - - -struct IPhysicalEntity; - -namespace LmbrCentral -{ - /** - * In-editor mesh component. - * Conducts some additional listening and operations to ensure immediate - * effects when changing fields in the editor. - */ - class EditorMeshComponent - : public AzToolsFramework::Components::EditorComponentBase - , public AZ::Data::AssetBus::Handler - , private AzFramework::AssetCatalogEventBus::Handler - , public AzFramework::BoundsRequestBus::Handler - , private AzFramework::RenderGeometry::IntersectionRequestBus::Handler - , private MeshComponentRequestBus::Handler - , private MaterialOwnerRequestBus::Handler - , private MeshComponentNotificationBus::Handler - , private RenderNodeRequestBus::Handler - , private AZ::TransformNotificationBus::Handler - , private AzToolsFramework::EntitySelectionEvents::Bus::Handler - , private AzToolsFramework::EditorVisibilityNotificationBus::Handler - , private AzFramework::EntityDebugDisplayEventBus::Handler - , private LegacyMeshComponentRequestBus::Handler - , private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler - , private AzToolsFramework::EditorComponentSelectionNotificationsBus::Handler - { - public: - AZ_COMPONENT(EditorMeshComponent, "{FC315B86-3280-4D03-B4F0-5553D7D08432}", AzToolsFramework::Components::EditorComponentBase) - - ~EditorMeshComponent() = default; - - const float s_renderNodeRequestBusOrder = 100.f; - - // AZ::Component overrides ... - void Activate() override; - void Deactivate() override; - - // BoundsRequestBus and MeshComponentRequestBus overrides ... - AZ::Aabb GetWorldBounds() override; - AZ::Aabb GetLocalBounds() override; - - // IntersectionRequestBus overrides ... - AzFramework::RenderGeometry::RayResult RenderGeometryIntersect(const AzFramework::RenderGeometry::RayRequest& ray) override; - - // MeshComponentRequestBus overrides ... - void SetMeshAsset(const AZ::Data::AssetId& id) override; - AZ::Data::Asset GetMeshAsset() override { return m_mesh.GetMeshAsset(); } - void SetVisibility(bool visible) override; - bool GetVisibility() override; - - // MaterialOwnerRequestBus overrides ... - void SetMaterial(_smart_ptr) override; - _smart_ptr GetMaterial() override; - - // MeshComponentNotificationBus overrides ... - void OnMeshCreated(const AZ::Data::Asset& asset) override; - void OnMeshDestroyed() override; - - // RenderNodeRequestBus overrides ... - IRenderNode* GetRenderNode() override; - float GetRenderNodeRequestBusOrder() const override; - - // TransformNotificationBus overrides ... - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - void OnStaticChanged(bool isStatic) override; - - // EditorVisibilityNotificationBus overrides ... - void OnEntityVisibilityChanged(bool visibility) override; - - // AzFramework::EntityDebugDisplayEventBus overrides .... - void DisplayEntityViewport( - const AzFramework::ViewportInfo& viewportInfo, - AzFramework::DebugDisplayRequests& debugDisplay) override; - - //! Called when you want to change the game asset through code (like when creating components based on assets). - void SetPrimaryAsset(const AZ::Data::AssetId& assetId) override; - - // LegacyMeshComponentRequests overrides ... - IStatObj* GetStatObj() override; - - // EditorComponentBase overrides ... - void BuildGameEntity(AZ::Entity* gameEntity) override; - - // AZ::Data::AssetBus overrides ... - void OnAssetReloaded(AZ::Data::Asset asset) override; - - // AzFramework::AssetCatalogEventBus overrides ... - void OnCatalogAssetRemoved(const AZ::Data::AssetId& assetId, const AZ::Data::AssetInfo& assetInfo) override; - - // EditorComponentSelectionRequestsBus overrides ... - AZ::Aabb GetEditorSelectionBoundsViewport( - const AzFramework::ViewportInfo& viewportInfo) override; - bool EditorSelectionIntersectRayViewport( - const AzFramework::ViewportInfo& viewportInfo, - const AZ::Vector3& src, const AZ::Vector3& dir, float& distance) override; - bool SupportsEditorRayIntersect() override { return true; } - - // EditorComponentSelectionNotificationsBus overrides ... - void OnAccentTypeChanged(AzToolsFramework::EntityAccentType accent) override; - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("MeshService", 0x71d8a455)); - provided.push_back(AZ_CRC("LegacyMeshService", 0xb462a299)); - } - - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); - } - - static void GetDependentServices(AZ::ComponentDescriptor::DependencyArrayType& dependent) - { - dependent.push_back(AZ_CRC("EditorVisibilityService", 0x90888caf)); - } - - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("MeshService", 0x71d8a455)); - incompatible.push_back(AZ_CRC("LegacyMeshService", 0xb462a299)); - } - - static void Reflect(AZ::ReflectContext* context); - - protected: - - // Decides if this mesh affects the navmesh or not. - void AffectNavmesh(); - - AZStd::string GetMeshViewportIconPath() const; - - AzToolsFramework::EntityAccentType m_accentType = AzToolsFramework::EntityAccentType::None; ///< State of the entity selection in the viewport. - MeshComponentRenderNode m_mesh; ///< IRender node implementation. - - AzFramework::EntityContextId m_contextId; - AZ::Vector3 m_debugPos = AZ::Vector3(0); - AZ::Vector3 m_debugNormal = AZ::Vector3(0); - }; - - // Helper function useful for automation. - bool AddMeshComponentWithMesh(const AZ::EntityId& targetEntity, const AZ::Uuid& meshAssetId); -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Rendering/MaterialHandle.cpp b/Gems/LmbrCentral/Code/Source/Rendering/MaterialHandle.cpp deleted file mode 100644 index 6171951398..0000000000 --- a/Gems/LmbrCentral/Code/Source/Rendering/MaterialHandle.cpp +++ /dev/null @@ -1,399 +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 "LmbrCentral_precompiled.h" -#include -#include -#include -#include -#include -#include -#include - - -namespace LmbrCentral -{ - // Provides a set of reflected functions for operating on IMaterial through a MaterialHandle - // We keep these cpp-private instead of putting them in the header to align with the fact that - // MaterialHandle is not useful on the code side, and only exists to support reflection. If it - // were possible to reflect IMaterial directly, we'd still have this same set of functions here. - namespace MaterialHandleFunctions - { - void SetParamVector4(MaterialHandle* thisPtr, const AZStd::string& name, const AZ::Vector4& value) - { - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsMaterialGroup()) - { - Vec4 vec4(value.GetX(), value.GetY(), value.GetZ(), value.GetW()); - thisPtr->m_material->SetGetMaterialParamVec4(name.c_str(), vec4, false, true); - } - else - { - AZ_Error("Material", false, "SetParamVector4 only accepts single Materials, not Material Groups"); - } - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to SetParamVector4"); - } - } - - void SetParamVector3(MaterialHandle* thisPtr, const AZStd::string& name, const AZ::Vector3& value) - { - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsMaterialGroup()) - { - Vec3 vec3(value.GetX(), value.GetY(), value.GetZ()); - thisPtr->m_material->SetGetMaterialParamVec3(name.c_str(), vec3, false, true); - } - else - { - AZ_Error("Material", false, "SetParamVector3 only accepts single Materials, not Material Groups"); - } - - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to SetParamVector3"); - } - } - - void SetParamColor(MaterialHandle* thisPtr, const AZStd::string& name, const AZ::Color& value) - { - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsMaterialGroup()) - { - // When value had garbage data is was not only making the material render black, it also corrupted something - // on the GPU, making black boxes flicker over the sky. - // It was garbage due to a bug in the Color object node where all fields have to be set to some value manually; the default is not 0. - if ((value.GetR() < 0 || value.GetR() > 1) || - (value.GetG() < 0 || value.GetG() > 1) || - (value.GetB() < 0 || value.GetB() > 1) || - (value.GetA() < 0 || value.GetA() > 1)) - { - return; - } - - Vec4 vec4(value.GetR(), value.GetG(), value.GetB(), value.GetA()); - thisPtr->m_material->SetGetMaterialParamVec4(name.c_str(), vec4, false, true); - } - else - { - AZ_Error("Material", false, "SetParamColor only accepts single Materials, not Material Groups"); - } - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to SetParamColor"); - } - } - - void SetParamFloat(MaterialHandle* thisPtr, const AZStd::string& name, float value) - { - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsMaterialGroup()) - { - thisPtr->m_material->SetGetMaterialParamFloat(name.c_str(), value, false, true); - } - else - { - AZ_Error("Material", false, "SetParamFloat only accepts single Materials, not Material Groups"); - } - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to SetParamFloat"); - } - } - - AZ::Vector4 GetParamVector4(MaterialHandle* thisPtr, const AZStd::string& name) - { - AZ::Vector4 value = AZ::Vector4::CreateZero(); - - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsMaterialGroup()) - { - Vec4 vec4; - if (thisPtr->m_material->SetGetMaterialParamVec4(name.c_str(), vec4, true, true)) - { - value.Set(vec4.x, vec4.y, vec4.z, vec4.w); - } - } - else - { - AZ_Error("Material", false, "GetParamVector4 only accepts single Materials, not Material Groups"); - } - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to GetParamVector4"); - } - - return value; - } - - AZ::Vector3 GetParamVector3(MaterialHandle* thisPtr, const AZStd::string& name) - { - AZ::Vector3 value = AZ::Vector3::CreateZero(); - - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsMaterialGroup()) - { - Vec3 vec3; - if (thisPtr->m_material->SetGetMaterialParamVec3(name.c_str(), vec3, true, true)) - { - value.Set(vec3.x, vec3.y, vec3.z); - } - } - else - { - AZ_Error("Material", false, "GetParamVector3 only accepts single Materials, not Material Groups"); - } - - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to GetParamVector3"); - } - - return value; - } - - AZ::Color GetParamColor(MaterialHandle* thisPtr, const AZStd::string& name) - { - AZ::Color value = AZ::Color::CreateZero(); - - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsMaterialGroup()) - { - Vec4 vec4; - if (thisPtr->m_material->SetGetMaterialParamVec4(name.c_str(), vec4, true, true)) - { - value.Set(vec4.x, vec4.y, vec4.z, vec4.w); - } - } - else - { - AZ_Error("Material", false, "GetParamColor only accepts single Materials, not Material Groups"); - } - - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to GetParamColor"); - } - - return value; - } - - float GetParamFloat(MaterialHandle* thisPtr, const AZStd::string& name) - { - float value = 0.0f; - - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsMaterialGroup()) - { - thisPtr->m_material->SetGetMaterialParamFloat(name.c_str(), value, true, true); - } - else - { - AZ_Error("Material", false, "GetParamFloat only accepts single Materials, not Material Groups"); - } - - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to GetParamFloat"); - } - - return value; - } - - MaterialHandle Clone(MaterialHandle* thisPtr) - { - MaterialHandle copy; - - if (thisPtr && thisPtr->m_material) - { - if (!thisPtr->m_material->IsSubMaterial()) - { - copy.m_material = gEnv->p3DEngine->GetMaterialManager()->CloneMultiMaterial(thisPtr->m_material); - } - else - { - AZ_Error("Material", false, "Clone does not support Sub-Materials"); - } - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to Clone"); - } - - return copy; - } - - MaterialHandle FindByName(const AZStd::string& name) - { - MaterialHandle found; - found.m_material = gEnv->p3DEngine->GetMaterialManager()->FindMaterial(name.c_str()); - return found; - } - - MaterialHandle LoadByName(const AZStd::string& name) - { - LmbrCentral::MaterialHandle handle; - handle.m_material = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(name.c_str(), false, false, IMaterialManager::ELoadingFlagsPreviewMode); - - AZ_Error(nullptr, handle.m_material, "Material.LoadByName('%s') failed", name.c_str()); - - return handle; - } - - _smart_ptr GetSubMaterialHelper(_smart_ptr materialGroup, int materialId) - { - if (materialGroup) - { - if (materialGroup->IsMaterialGroup()) - { - int subMtlCount = materialGroup->GetSubMtlCount(); - if (materialId >= 1 && materialId <= subMtlCount) - { - return materialGroup->GetSubMtl(materialId-1); - } - else - { - AZ_Error("Material", false, "Invalid Material ID %d passed to FindSubMaterial. %d Materials are available.", materialId, subMtlCount); - } - } - else - { - AZ_Error("Material", false, "FindSubMaterial does not support single Material"); - } - } - else - { - AZ_Warning("Material", false, "Invalid Material passed to FindSubMaterial."); - } - - return nullptr; - } - - - - MaterialHandle FindSubMaterial(const AZStd::string& name, int id, bool shouldLoad) - { - MaterialHandle found; - _smart_ptr materialGroup = gEnv->p3DEngine->GetMaterialManager()->FindMaterial(name.c_str()); - if (materialGroup) - { - found.m_material = GetSubMaterialHelper(materialGroup, id); - } - else - { - if (shouldLoad) - { - materialGroup = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(name.c_str(), false, false, IMaterialManager::ELoadingFlagsPreviewMode); - if (materialGroup) - { - found.m_material = GetSubMaterialHelper(materialGroup, id); - } - else - { - AZ_Error("Material", false, "Load Material '%s' failed", name.c_str()); - } - } - else - { - AZ_Warning("Material", false, "No Sub-Material is found since Material '%s' is not loaded", name.c_str()); - } - } - - return found; - } - - AZStd::string ToString(MaterialHandle* thisPtr) - { - if (!thisPtr || !thisPtr->m_material) - { - return "Invalid"; - } - else - { - return thisPtr->m_material->GetName(); - } - } - } - - void MaterialHandle::Reflect(AZ::SerializeContext* serializeContext) - { - // This is required in order to create a MaterialHandle variable in script canvas. - serializeContext->Class()->Version(0); - } - - void MaterialHandle::Reflect(AZ::BehaviorContext* behaviorContext) - { - const char* setMaterialParamTooltip = "Sets a Material param value"; - const char* getMaterialParamTooltip = "Returns a Material param value"; - AZ::BehaviorParameterOverrides setMaterialDetails = { "Material", "The Material to modify" }; - AZ::BehaviorParameterOverrides getMaterialDetails = { "Material", "The Material to inspect" }; - AZ::BehaviorParameterOverrides setParamNameDetails = { "ParamName", "The name of the Material param to set" }; - AZ::BehaviorParameterOverrides getParamNameDetails = { "ParamName", "The name of the Material param to return" }; - const AZStd::array getMaterialParamArgs = { { getMaterialDetails,getParamNameDetails } }; - const char* newValueTooltip = "The new value to apply"; - - behaviorContext->Class("Material") - ->Attribute(AZ::Script::Attributes::Category, "Rendering") - ->Method("ToString", &MaterialHandleFunctions::ToString) - ->Attribute(AZ::Script::Attributes::Operator, AZ::Script::Attributes::OperatorType::ToString) - ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) // Hide this node because it doesn't really make sense for the user (GetName would be better), but we need "ToString" in order to provide nice output in Material Variable nodes in script canvas. - ->Method("FindByName", &MaterialHandleFunctions::FindByName, { { { "Name", "Full path name of the Material" } } }) - ->Attribute(AZ::Script::Attributes::ToolTip, "Find a Material by name. Returns Invalid if the Material is not already loaded.") - ->Method("LoadByName", &MaterialHandleFunctions::LoadByName, { { { "Name", "Full path name of the Material" } } }) - ->Attribute(AZ::Script::Attributes::ToolTip, "Find a Material by name, loading the asset if needed. Returns Invalid if the Material could not be found or loaded.") - ->Method("Clone", &MaterialHandleFunctions::Clone, { { { "Material", "The Material to clone" } } }) - ->Attribute(AZ::Script::Attributes::ToolTip, "Creates a copy of the given Material.") - ->Method("FindSubMaterial", &MaterialHandleFunctions::FindSubMaterial, - { { { "Name", "Full path name of the Material Group to get a Sub-Material from" }, - { "MaterialID", "The ID of a Sub-Material to access. IDs start at 1.", behaviorContext->MakeDefaultValue(1) }, - { "ShouldLoad", "Whether to load the Material Group or not if it's not loaded", behaviorContext->MakeDefaultValue(true) } } }) - ->Attribute(AZ::Script::Attributes::ToolTip, "Find a Sub-Material from a Material Group by specified Material ID. Returns Invalid if the Material Group could not be found or loaded or the Sub-Material could not be found.") - ->Method("SetParamVector4", &MaterialHandleFunctions::SetParamVector4, - { { setMaterialDetails,setParamNameDetails,{ "Vector4", newValueTooltip } } }) - ->Attribute(AZ::Script::Attributes::ToolTip, setMaterialParamTooltip) - ->Method("SetParamVector3", &MaterialHandleFunctions::SetParamVector3, - { { setMaterialDetails,setParamNameDetails,{ "Vector3", newValueTooltip } } }) - ->Attribute(AZ::Script::Attributes::ToolTip, setMaterialParamTooltip) - ->Method("SetParamColor", &MaterialHandleFunctions::SetParamColor, - { { setMaterialDetails,setParamNameDetails,{ "Color", newValueTooltip } } }) - ->Attribute(AZ::Script::Attributes::ToolTip, setMaterialParamTooltip) - ->Method("SetParamNumber", &MaterialHandleFunctions::SetParamFloat, // Using "ParamNumber" instead of "ParamFloat" because in Script Canvas all primitives are just "numbers" - { { setMaterialDetails,setParamNameDetails,{ "Number", newValueTooltip } } }) - ->Attribute(AZ::Script::Attributes::ToolTip, setMaterialParamTooltip) - ->Method("GetParamVector4", &MaterialHandleFunctions::GetParamVector4, getMaterialParamArgs) - ->Attribute(AZ::Script::Attributes::ToolTip, getMaterialParamTooltip) - ->Method("GetParamVector3", &MaterialHandleFunctions::GetParamVector3, getMaterialParamArgs) - ->Attribute(AZ::Script::Attributes::ToolTip, getMaterialParamTooltip) - ->Method("GetParamColor", &MaterialHandleFunctions::GetParamColor, getMaterialParamArgs) - ->Attribute(AZ::Script::Attributes::ToolTip, getMaterialParamTooltip) - ->Method("GetParamNumber", &MaterialHandleFunctions::GetParamFloat, getMaterialParamArgs) // Using "ParamNumber" instead of "ParamFloat" because in Script Canvas all primitives are just "numbers" - ->Attribute(AZ::Script::Attributes::ToolTip, getMaterialParamTooltip) - ; - } -} diff --git a/Gems/LmbrCentral/Code/Source/Rendering/MeshAssetHandler.cpp b/Gems/LmbrCentral/Code/Source/Rendering/MeshAssetHandler.cpp deleted file mode 100644 index 18b9003e4f..0000000000 --- a/Gems/LmbrCentral/Code/Source/Rendering/MeshAssetHandler.cpp +++ /dev/null @@ -1,265 +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 "LmbrCentral_precompiled.h" - -#include -#include -#include -#include -#include -#include - -#include -#include "MeshAssetHandler.h" - -#include -#include - -namespace LmbrCentral -{ - ////////////////////////////////////////////////////////////////////////// - const AZStd::string MeshAssetHandlerHelper::s_assetAliasToken = "@assets@/"; - - // what mesh do we use as a placeholder when its currently busy compiling? - static const char* g_meshCompilingSubstituteAsset = "engineassets/objects/default.cgf"; - - MeshAssetHandlerHelper::MeshAssetHandlerHelper() - : m_asyncLoadCvar(nullptr) - { - } - - void MeshAssetHandlerHelper::StripAssetAlias(const char*& assetPath) - { - const size_t assetAliasTokenLen = s_assetAliasToken.size() - 1; - if (0 == strncmp(assetPath, s_assetAliasToken.c_str(), assetAliasTokenLen)) - { - assetPath += assetAliasTokenLen; - } - } - - ICVar* MeshAssetHandlerHelper::GetAsyncLoadCVar() - { - if (!m_asyncLoadCvar) - { - m_asyncLoadCvar = gEnv->pConsole->GetCVar(s_meshAssetHandler_AsyncCvar); - } - - return m_asyncLoadCvar; - } - - ////////////////////////////////////////////////////////////////////////// - // Static Mesh Asset Handler - ////////////////////////////////////////////////////////////////////////// - - void AsyncStatObjLoadCallback(const AZ::Data::Asset& asset, _smart_ptr statObj) - { - if (statObj) - { - asset.Get()->m_statObj = statObj; - } - else - { -#if defined(AZ_ENABLE_TRACING) - AZStd::string assetDescription = asset.ToString(); - AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetDescription, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetPathById, asset.GetId()); - AZ_Error("MeshAssetHandler", false, "Failed to load mesh asset %s", assetDescription.c_str()); -#endif // AZ_ENABLE_TRACING - } - } - - MeshAssetHandler::~MeshAssetHandler() - { - Unregister(); - } - - AZ::Data::AssetPtr MeshAssetHandler::CreateAsset([[maybe_unused]] const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) - { - (void)type; - - AZ_Assert(type == AZ::AzTypeInfo::Uuid(), "Invalid asset type! We handle only 'MeshAsset'"); - - return aznew MeshAsset(); - } - - AZ::Data::AssetId MeshAssetHandler::AssetMissingInCatalog([[maybe_unused]] const AZ::Data::Asset& asset) - { - // if tracing is disabled, we are likely in a situation where we specifically don't want any diagnostic information or "errors" to appear - // so in that case, don't load anything, don't substitute anything, don't escalate anything, just let the empty blank asset return. -#if defined(AZ_ENABLE_TRACING) - if (asset.GetId().IsValid()) - { - // find out whether its still compiling or it will never be available because its source file is missing. - // this also escalates it, if found, to the top of the build queue: - AzFramework::AssetSystem::AssetStatus statusResult = AzFramework::AssetSystem::AssetStatus_Unknown; - AzFramework::AssetSystemRequestBus::BroadcastResult(statusResult, &AzFramework::AssetSystem::AssetSystemRequests::GetAssetStatusById, asset.GetId()); - - if ((statusResult == AzFramework::AssetSystem::AssetStatus_Compiling) || (statusResult == AzFramework::AssetSystem::AssetStatus_Queued)) - { - // note that we can also check other codes and substitute other meshes if we want, here... - // its currently compiling and will finish soon. - // substitute a placeholder mesh: - - if (!m_missingMeshAssetId.IsValid()) - { - // substitute the missing mesh assetId so that there's at least something to render that indicates a problem - // in builds where there is no diagnostics or tracing, don't substitute anything, to prefer that there's no visual indication that - // something is wrong in shipped games. - AZ::Data::AssetCatalogRequestBus::BroadcastResult(m_missingMeshAssetId, &AZ::Data::AssetCatalogRequests::GetAssetIdByPath, g_meshCompilingSubstituteAsset, azrtti_typeid(), false); - AZ_Error("Mesh Asset Handler", m_missingMeshAssetId.IsValid(), "Attempted to substitute %s for a missing asset, but it is also missing!", g_meshCompilingSubstituteAsset); - } - - if (m_missingMeshAssetId.IsValid()) - { - AZ_TracePrintf("MeshAssetHandler", " - substituting with default asset ID %s\n", m_missingMeshAssetId.ToString().c_str()); - // substitute the missing mesh asset. - return m_missingMeshAssetId; - } - } - } -#endif // defined(AZ_ENABLE_TRACING) - - // otherwise, if we get here, it means that either it was truly missing, in which case let an error occur, or the missing default substitute asset - // is also itself missing! - return AZ::Data::AssetId(); - } - - - - void MeshAssetHandler::GetCustomAssetStreamInfoForLoad(AZ::Data::AssetStreamInfo& streamInfo) - { - // The StatObj system only takes in a file name for loading, not a memory buffer. - // If we set our stream data length to 0, the asset system will skip any file I/O for reading the data, and will instead - // go directly into the AssetHandler for processing. - streamInfo.m_dataLen = 0; - } - - AZ::Data::AssetHandler::LoadResult MeshAssetHandler::LoadAssetData( - const AZ::Data::Asset& asset, - AZStd::shared_ptr stream, - const AZ::Data::AssetFilterCB& /*assetLoadFilterCB*/) - { - const char* assetPath = stream->GetFilename(); - - AZ_Assert(asset.GetType() == AZ::AzTypeInfo::Uuid(), "Invalid asset type! We only load 'MeshAsset'"); - if (MeshAsset* meshAsset = asset.GetAs()) - { - AZ_Assert(!meshAsset->m_statObj.get(), "Attempting to create static mesh without cleaning up the old one."); - - // Strip the alias. StatObj instances are stored in a dictionary by their path, - // so to share instances with legacy cry entities, we need to use the same un-aliased format. - StripAssetAlias(assetPath); - - // Temporary cvar guard while async loading of legacy mesh formats is stabilized. - ICVar* cvar = GetAsyncLoadCVar(); - if (!cvar || cvar->GetIVal() == 0) - { - if (gEnv->mMainThreadId != CryGetCurrentThreadId()) - { - AZStd::binary_semaphore signaller; - - auto callback = [&asset, &signaller](IStatObj* obj) - { - AsyncStatObjLoadCallback(asset, obj); - signaller.release(); - }; - - gEnv->p3DEngine->LoadStatObjAsync(callback, assetPath); - signaller.acquire(); - } - else - { - AsyncStatObjLoadCallback(asset, gEnv->p3DEngine->LoadStatObjAutoRef(assetPath)); - } - } - else - { - _smart_ptr statObj = gEnv->p3DEngine->LoadStatObjAutoRef(assetPath); - - if (statObj) - { - meshAsset->m_statObj = statObj; - } - else - { -#if defined(AZ_ENABLE_TRACING) - AZStd::string assetDescription = asset.GetId().ToString(); - AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetDescription, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetPathById, asset.GetId()); - AZ_Error("MeshAssetHandler", false, "Failed to load mesh asset \"%s\".", assetDescription.c_str()); -#endif // AZ_ENABLE_TRACING - } - } - - return AZ::Data::AssetHandler::LoadResult::LoadComplete; - } - return AZ::Data::AssetHandler::LoadResult::Error; - } - - void MeshAssetHandler::DestroyAsset(AZ::Data::AssetPtr ptr) - { - delete ptr; - } - - void MeshAssetHandler::GetHandledAssetTypes(AZStd::vector& assetTypes) - { - assetTypes.push_back(AZ::AzTypeInfo::Uuid()); - } - - void MeshAssetHandler::Register() - { - AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!"); - AZ::Data::AssetManager::Instance().RegisterHandler(this, AZ::AzTypeInfo::Uuid()); - - AZ::AssetTypeInfoBus::Handler::BusConnect(AZ::AzTypeInfo::Uuid()); - } - - void MeshAssetHandler::Unregister() - { - AZ::AssetTypeInfoBus::Handler::BusDisconnect(AZ::AzTypeInfo::Uuid()); - - if (AZ::Data::AssetManager::IsReady()) - { - AZ::Data::AssetManager::Instance().UnregisterHandler(this); - } - } - - AZ::Data::AssetType MeshAssetHandler::GetAssetType() const - { - return AZ::AzTypeInfo::Uuid(); - } - - const char* MeshAssetHandler::GetAssetTypeDisplayName() const - { - return "Static Mesh"; - } - - const char* MeshAssetHandler::GetGroup() const - { - return "Geometry"; - } - - const char* MeshAssetHandler::GetBrowserIcon() const - { - return "Icons/Components/StaticMesh.svg"; - } - - AZ::Uuid MeshAssetHandler::GetComponentTypeId() const - { - return AZ::Uuid("{FC315B86-3280-4D03-B4F0-5553D7D08432}"); - } - - void MeshAssetHandler::GetAssetTypeExtensions(AZStd::vector& extensions) - { - extensions.push_back(CRY_GEOMETRY_FILE_EXT); - } - -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Rendering/MeshAssetHandler.h b/Gems/LmbrCentral/Code/Source/Rendering/MeshAssetHandler.h deleted file mode 100644 index 00936316f5..0000000000 --- a/Gems/LmbrCentral/Code/Source/Rendering/MeshAssetHandler.h +++ /dev/null @@ -1,97 +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 - -struct ICVar; - -namespace LmbrCentral -{ - static const char* s_meshAssetHandler_AsyncCvar = "az_Asset_EnableAsyncMeshLoading"; - - /** - * Base class for mesh asset handlers. Contains shared utilities and functionality. - */ - class MeshAssetHandlerHelper - { - public: - - MeshAssetHandlerHelper(); - - protected: - - /** - * Removes the asset alias from a string - * - * StatObjs, CharacterInstances and GeometryCaches are stored in - * dictionaries by their path which is not aliased like the new AZ systems. - * To look up mesh instances we need the un-aliased path. - * - * This method assumes that the alias will be at the beginning of the string. - * - * @param assetPath The asset path string to remove the alias from - */ - void StripAssetAlias(const char*& assetPath); - - static const AZStd::string s_assetAliasToken; //< The token used to strip the asset alias in StripAssetAlias - - ICVar* GetAsyncLoadCVar(); - ICVar* m_asyncLoadCvar; - }; - - /** - * Handler for static mesh assets (cgf). - */ - class MeshAssetHandler - : public AZ::Data::AssetHandler - , public AZ::AssetTypeInfoBus::Handler - , private MeshAssetHandlerHelper - { - public: - - AZ_CLASS_ALLOCATOR(MeshAssetHandler, AZ::SystemAllocator, 0); - - ~MeshAssetHandler() override; - - ////////////////////////////////////////////////////////////////////////////////////////////// - // AZ::Data::AssetHandler - AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override; - void GetCustomAssetStreamInfoForLoad(AZ::Data::AssetStreamInfo& streamInfo) override; - AZ::Data::AssetHandler::LoadResult LoadAssetData( - const AZ::Data::Asset& asset, - AZStd::shared_ptr stream, - const AZ::Data::AssetFilterCB& assetLoadFilterCB) override; - AZ::Data::AssetId AssetMissingInCatalog(const AZ::Data::Asset& asset) override; - void DestroyAsset(AZ::Data::AssetPtr ptr) override; - void GetHandledAssetTypes(AZStd::vector& assetTypes) override; - ////////////////////////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////////////////////////// - // AZ::AssetTypeInfoBus::Handler - AZ::Data::AssetType GetAssetType() const override; - const char* GetAssetTypeDisplayName() const override; - const char* GetGroup() const override; - const char* GetBrowserIcon() const override; - AZ::Uuid GetComponentTypeId() const override; - void GetAssetTypeExtensions(AZStd::vector& extensions) override; - ////////////////////////////////////////////////////////////////////////////////////////////// - - void Register(); - void Unregister(); - - AZ::Data::AssetId m_missingMeshAssetId; - }; -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Rendering/MeshComponent.cpp b/Gems/LmbrCentral/Code/Source/Rendering/MeshComponent.cpp deleted file mode 100644 index 0ee72b62cf..0000000000 --- a/Gems/LmbrCentral/Code/Source/Rendering/MeshComponent.cpp +++ /dev/null @@ -1,1228 +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 "LmbrCentral_precompiled.h" -#include "MeshComponent.h" -#include - -#include -#include -#include -#include -#include -#include - -#include -#include - -#include - -#include -#include -#include - -namespace LmbrCentral -{ - ////////////////////////////////////////////////////////////////////////// - - //! Handler/binding code that is required for Behavior Context reflection of EBus Notifications. - class MaterialOwnerNotificationBusBehaviorHandler : public MaterialOwnerNotificationBus::Handler, public AZ::BehaviorEBusHandler - { - public: - AZ_EBUS_BEHAVIOR_BINDER(MaterialOwnerNotificationBusBehaviorHandler, "{77705C0E-5ADE-496C-85FF-9278565E278E}", AZ::SystemAllocator - , OnMaterialOwnerReady); - - void OnMaterialOwnerReady() override - { - Call(FN_OnMaterialOwnerReady); - } - }; - - ////////////////////////////////////////////////////////////////////////// - - AZ::BehaviorParameterOverrides CreateMaterialIdDetails(AZ::BehaviorContext* behaviorContext) - { - return{ "MaterialID", "The ID of a Material slot to access, if the Owner has multiple Materials. IDs start at 1.", behaviorContext->MakeDefaultValue(1) }; - } - - AZStd::array GetMaterialParamArgs(AZ::BehaviorContext* behaviorContext) - { - AZ::BehaviorParameterOverrides getParamNameDetails = { "ParamName", "The name of the Material param to return" }; - return{ { getParamNameDetails, CreateMaterialIdDetails(behaviorContext) } }; - } - - void MeshComponent::Reflect(AZ::ReflectContext* context) - { - MeshComponentRenderNode::Reflect(context); - - AZ::SerializeContext* serializeContext = azrtti_cast(context); - - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field("Static Mesh Render Node", &MeshComponent::m_meshRenderNode); - } - - if (AZ::BehaviorContext* behaviorContext = azrtti_cast(context)) - { - behaviorContext->EBus("MeshComponentRequestBus") - ->Event("SetVisibility", &MeshComponentRequestBus::Events::SetVisibility) - ->Event("GetVisibility", &MeshComponentRequestBus::Events::GetVisibility) - ->VirtualProperty("Visibility", "GetVisibility", "SetVisibility"); - - const char* setMaterialParamTooltip = "Sets a Material param value for the given Entity. The Material will be cloned once before any changes are applied, so other instances are not affected."; - const char* getMaterialParamTooltip = "Returns a Material param value for the given Entity"; - AZ::BehaviorParameterOverrides setParamNameDetails = { "ParamName", "The name of the Material param to set" }; - const char* newValueTooltip = "The new value to apply"; - - behaviorContext->EBus("MaterialOwnerRequestBus", nullptr, "Includes functions for Components that have a Material such as Mesh Component, Decal Component, etc.") - ->Attribute(AZ::Script::Attributes::Category, "Rendering") - ->Event("IsMaterialOwnerReady", &MaterialOwnerRequestBus::Events::IsMaterialOwnerReady) - ->Attribute(AZ::Script::Attributes::ToolTip, "Indicates whether the Material Owner is fully initialized, and is ready for Material requests") - ->Event("SetMaterial", &MaterialOwnerRequestBus::Events::SetMaterialHandle) - ->Attribute(AZ::Script::Attributes::ToolTip, "Sets an Entity's Material") - ->Event("GetMaterial", &MaterialOwnerRequestBus::Events::GetMaterialHandle) - ->Attribute(AZ::Script::Attributes::ToolTip, "Returns an Entity's current Material") - ->Event("SetParamVector4", &MaterialOwnerRequestBus::Events::SetMaterialParamVector4, { { setParamNameDetails, { "Vector4", newValueTooltip }, CreateMaterialIdDetails(behaviorContext) } }) - ->Attribute(AZ::Script::Attributes::ToolTip, setMaterialParamTooltip) - ->Event("SetParamVector3", &MaterialOwnerRequestBus::Events::SetMaterialParamVector3, { { setParamNameDetails, { "Vector3", newValueTooltip }, CreateMaterialIdDetails(behaviorContext) } }) - ->Attribute(AZ::Script::Attributes::ToolTip, setMaterialParamTooltip) - ->Event("SetParamColor", &MaterialOwnerRequestBus::Events::SetMaterialParamColor, { { setParamNameDetails, { "Color" , newValueTooltip }, CreateMaterialIdDetails(behaviorContext) } }) - ->Attribute(AZ::Script::Attributes::ToolTip, setMaterialParamTooltip) - ->Event("SetParamNumber", &MaterialOwnerRequestBus::Events::SetMaterialParamFloat, { { setParamNameDetails, { "Number" , newValueTooltip }, CreateMaterialIdDetails(behaviorContext) } }) // Using ParamNumber instead of ParamFloat because in Script Canvas all primitives are just "numbers" - ->Attribute(AZ::Script::Attributes::ToolTip, setMaterialParamTooltip) - ->Event("GetParamVector4", &MaterialOwnerRequestBus::Events::GetMaterialParamVector4, GetMaterialParamArgs(behaviorContext)) - ->Attribute(AZ::Script::Attributes::ToolTip, getMaterialParamTooltip) - ->Event("GetParamVector3", &MaterialOwnerRequestBus::Events::GetMaterialParamVector3, GetMaterialParamArgs(behaviorContext)) - ->Attribute(AZ::Script::Attributes::ToolTip, getMaterialParamTooltip) - ->Event("GetParamColor", &MaterialOwnerRequestBus::Events::GetMaterialParamColor, GetMaterialParamArgs(behaviorContext)) - ->Attribute(AZ::Script::Attributes::ToolTip, getMaterialParamTooltip) - ->Event("GetParamNumber", &MaterialOwnerRequestBus::Events::GetMaterialParamFloat, GetMaterialParamArgs(behaviorContext)) // Using ParamNumber instead of ParamFloat because in Script Canvas all primitives are just "numbers" - ->Attribute(AZ::Script::Attributes::ToolTip, getMaterialParamTooltip); - - behaviorContext->EBus("MaterialOwnerNotificationBus", nullptr, "Provides notifications from Components that have a Material such as Mesh Component, Decal Component, etc.") - ->Attribute(AZ::Script::Attributes::Category, "Rendering") - ->Handler() - ; - - behaviorContext->Class()->RequestBus("MeshComponentRequestBus"); - } - } - - - ////////////////////////////////////////////////////////////////////////// - - void MeshComponentRenderNode::MeshRenderOptions::Reflect(AZ::ReflectContext* context) - { - AZ::SerializeContext* serializeContext = azrtti_cast(context); - - if (serializeContext) - { - serializeContext->Class() - ->Version(5, &VersionConverter) - ->Field("Opacity", &MeshComponentRenderNode::MeshRenderOptions::m_opacity) - ->Field("MaxViewDistance", &MeshComponentRenderNode::MeshRenderOptions::m_maxViewDist) - ->Field("ViewDistanceMultiplier", &MeshComponentRenderNode::MeshRenderOptions::m_viewDistMultiplier) - ->Field("LODRatio", &MeshComponentRenderNode::MeshRenderOptions::m_lodRatio) - ->Field("CastShadows", &MeshComponentRenderNode::MeshRenderOptions::m_castShadows) - ->Field("LODBBoxBased", &MeshComponentRenderNode::MeshRenderOptions::m_lodBoundingBoxBased) - ->Field("UseVisAreas", &MeshComponentRenderNode::MeshRenderOptions::m_useVisAreas) - ->Field("RainOccluder", &MeshComponentRenderNode::MeshRenderOptions::m_rainOccluder) - ->Field("AffectDynamicWater", &MeshComponentRenderNode::MeshRenderOptions::m_affectDynamicWater) - ->Field("ReceiveWind", &MeshComponentRenderNode::MeshRenderOptions::m_receiveWind) - ->Field("AcceptDecals", &MeshComponentRenderNode::MeshRenderOptions::m_acceptDecals) - ->Field("AffectNavmesh", &MeshComponentRenderNode::MeshRenderOptions::m_affectNavmesh) - ->Field("VisibilityOccluder", &MeshComponentRenderNode::MeshRenderOptions::m_visibilityOccluder) - ->Field("DynamicMesh", &MeshComponentRenderNode::MeshRenderOptions::m_dynamicMesh) - ->Field("AffectsGI", &MeshComponentRenderNode::MeshRenderOptions::m_affectGI) - ; - } - } - - bool MeshComponentRenderNode::MeshRenderOptions::VersionConverter(AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement) - { - // conversion from version 1: - // - Remove Bloom (m_allowBloom) - // - Remove MotionBlur (m_allowMotionBlur) - // - Remove DepthTest (m_depthTest) - if (classElement.GetVersion() <= 1) - { - classElement.RemoveElementByName(AZ_CRC("Bloom", 0xc6cd7d1b)); - classElement.RemoveElementByName(AZ_CRC("MotionBlur", 0x917cdb53)); - classElement.RemoveElementByName(AZ_CRC("DepthTest", 0x532f68b9)); - } - - // conversion from version 2: - // - Remove IndoorOnly (m_indoorOnly) - if (classElement.GetVersion() <= 2) - { - classElement.RemoveElementByName(AZ_CRC("IndoorOnly", 0xc8ab6ddb)); - } - - if (classElement.GetVersion() <= 3) - { - classElement.RemoveElementByName(AZ_CRC("CastLightmapShadows", 0x10ce0bf8)); - int index = classElement.FindElement(AZ_CRC("CastDynamicShadows", 0x55c75b43)); - AZ::SerializeContext::DataElementNode& shadowNode = classElement.GetSubElement(index); - shadowNode.SetName("CastShadows"); - } - - // conversion from version 4: - // - Set "CastShadows" to false if "Opacity" is less than 1.0f, in order to not break old assets. - // The new system ignores opacity for shadow casting and relies only on the "CastShadows" flag. - if (classElement.GetVersion() <= 4) - { - float opacity; - int opacityElementIndex = classElement.FindElement(AZ_CRC("Opacity", 0x43fd6d66)); - AZ::SerializeContext::DataElementNode& opacityNode = classElement.GetSubElement(opacityElementIndex); - opacityNode.GetData(opacity); - - if (opacity < 1.0f) - { - int castShadowsElementIndex = classElement.FindElement(AZ_CRC("CastShadows", 0xbe687463)); - AZ::SerializeContext::DataElementNode& castShadowsNode = classElement.GetSubElement(castShadowsElementIndex); - castShadowsNode.SetData(context, false); - } - } - - return true; - } - - bool MeshComponentRenderNode::MeshRenderOptions::IsStatic() const - { - return (m_hasStaticTransform && !m_dynamicMesh && !m_receiveWind); - } - - bool MeshComponentRenderNode::MeshRenderOptions::AffectsGi() const - { - return m_affectGI && IsStatic(); - } - - AZ::Crc32 MeshComponentRenderNode::MeshRenderOptions::StaticPropertyVisibility() const - { - return IsStatic() ? AZ::Edit::PropertyVisibility::Show : AZ::Edit::PropertyVisibility::Hide; - } - - void MeshComponentRenderNode::Reflect(AZ::ReflectContext* context) - { - MeshRenderOptions::Reflect(context); - - AZ::SerializeContext* serializeContext = azrtti_cast(context); - - if (serializeContext) - { - serializeContext->Class() - ->Version(1) - ->Field("Visible", &MeshComponentRenderNode::m_visible) - ->Field("Static Mesh", &MeshComponentRenderNode::m_meshAsset) - ->Field("Material Override", &MeshComponentRenderNode::m_material) - ->Field("Render Options", &MeshComponentRenderNode::m_renderOptions) - ; - } - } - - float MeshComponentRenderNode::GetDefaultMaxViewDist() - { - if (gEnv && gEnv->p3DEngine) - { - return gEnv->p3DEngine->GetMaxViewDistance(false); - } - - // In the editor and the game, the dynamic lookup above should *always* hit. - // This case essentially means no renderer (not even the null renderer) is present. - return FLT_MAX; - } - - MeshComponentRenderNode::MeshRenderOptions::MeshRenderOptions() - : m_opacity(1.f) - , m_viewDistMultiplier(1.f) - , m_lodRatio(100) - , m_useVisAreas(true) - , m_castShadows(true) - , m_lodBoundingBoxBased(false) - , m_rainOccluder(true) - , m_affectNavmesh(true) - , m_affectDynamicWater(false) - , m_acceptDecals(true) - , m_receiveWind(false) - , m_visibilityOccluder(false) - , m_dynamicMesh(false) - , m_hasStaticTransform(false) - , m_affectGI(true) - { - m_maxViewDist = GetDefaultMaxViewDist(); - } - - MeshComponentRenderNode::MeshComponentRenderNode() - : m_statObj(nullptr) - , m_materialOverride(nullptr) - , m_auxiliaryRenderFlags(0) - , m_auxiliaryRenderFlagsHistory(0) - , m_lodDistance(0.f) - , m_lodDistanceScaled(FLT_MAX / (SMeshLodInfo::s_nMaxLodCount + 1)) // defualt overflow prevention - it is scaled by (SMeshLodInfo::s_nMaxLodCount + 1) - , m_lodDistanceScaleValue(1.0f) - , m_isRegisteredWithRenderer(false) - , m_objectMoved(false) - , m_meshAsset(AZ::Data::AssetLoadBehavior::QueueLoad) - , m_visible(true) - { - m_localBoundingBox.Reset(); - m_worldBoundingBox.Reset(); - m_worldTransform = AZ::Transform::CreateIdentity(); - m_renderTransform = Matrix34::CreateIdentity(); - } - - MeshComponentRenderNode::~MeshComponentRenderNode() - { - DestroyMesh(); - } - - void MeshComponentRenderNode::CopyPropertiesTo(MeshComponentRenderNode& rhs) const - { - rhs.m_visible = m_visible; - rhs.m_materialOverride = m_materialOverride; - rhs.m_meshAsset = m_meshAsset; - rhs.m_material = m_material; - rhs.m_renderOptions = m_renderOptions; - } - - void MeshComponentRenderNode::AttachToEntity(AZ::EntityId id) - { - if (AZ::TransformNotificationBus::Handler::BusIsConnectedId(m_renderOptions.m_attachedToEntityId)) - { - AZ::TransformNotificationBus::Handler::BusDisconnect(m_renderOptions.m_attachedToEntityId); - } - - if (m_modificationHelper.IsConnected()) - { - m_modificationHelper.Disconnect(); - } - - if (id.IsValid()) - { - if (!AZ::TransformNotificationBus::Handler::BusIsConnectedId(id)) - { - AZ::TransformNotificationBus::Handler::BusConnect(id); - } - - auto transformHandler = AZ::TransformBus::FindFirstHandler(id); - - UpdateWorldTransform(transformHandler->GetWorldTM()); - - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); - - m_modificationHelper.Connect(id); - } - - m_renderOptions.m_attachedToEntityId = id; - } - - void MeshComponentRenderNode::OnAssetPropertyChanged() - { - if (HasMesh()) - { - DestroyMesh(); - } - - AZ::Data::AssetBus::Handler::BusDisconnect(); - - CreateMesh(); - AzFramework::RenderGeometry::IntersectionNotificationBus::Event(m_contextId, - &AzFramework::RenderGeometry::IntersectionNotifications::OnGeometryChanged, GetEntityId()); - } - - void MeshComponentRenderNode::RefreshRenderState() - { - if (gEnv->IsEditor()) - { - UpdateLocalBoundingBox(); - - AZ::Transform parentTransform = AZ::Transform::CreateIdentity(); - EBUS_EVENT_ID_RESULT(parentTransform, m_renderOptions.m_attachedToEntityId, AZ::TransformBus, GetWorldTM); - OnTransformChanged(AZ::Transform::CreateIdentity(), parentTransform); - - if (HasMesh()) - { - // Re-register with the renderer, as some render settings/flags require it. - // Note that this is editor-only behavior (hence the guard above). - if (m_isRegisteredWithRenderer) - { - RegisterWithRenderer(false); - RegisterWithRenderer(true); - } - } - } - } - - void MeshComponentRenderNode::SetTransformStaticState(bool isStatic) - { - m_renderOptions.m_hasStaticTransform = isStatic; - } - - const AZ::Transform& MeshComponentRenderNode::GetTransform() const - { - return m_worldTransform; - } - - void MeshComponentRenderNode::SetAuxiliaryRenderFlags(uint32 flags) - { - m_auxiliaryRenderFlags = flags; - m_auxiliaryRenderFlagsHistory |= flags; - } - - void MeshComponentRenderNode::UpdateAuxiliaryRenderFlags(bool on, uint32 mask) - { - if (on) - { - m_auxiliaryRenderFlags |= mask; - } - else - { - m_auxiliaryRenderFlags &= ~mask; - } - - m_auxiliaryRenderFlagsHistory |= mask; - } - - bool MeshComponentRenderNode::IsReady() const - { - return HasMesh(); - } - - void MeshComponentRenderNode::CreateMesh() - { - if (m_meshAsset.GetId().IsValid()) - { - if (!AZ::Data::AssetBus::Handler::BusIsConnected()) - { - AZ::Data::AssetBus::Handler::BusConnect(m_meshAsset.GetId()); - } - - m_meshAsset.QueueLoad(); - } - } - - void MeshComponentRenderNode::DestroyMesh() - { - AZ::Data::AssetBus::Handler::BusDisconnect(); - - RegisterWithRenderer(false); - m_statObj = nullptr; - - EBUS_EVENT_ID(m_renderOptions.m_attachedToEntityId, MeshComponentNotificationBus, OnMeshDestroyed); - - m_meshAsset.Release(); - } - - bool MeshComponentRenderNode::HasMesh() const - { - return m_statObj != nullptr; - } - - void MeshComponentRenderNode::SetMeshAsset(const AZ::Data::AssetId& id) - { - AZ::Data::Asset asset = AZ::Data::AssetManager::Instance().FindOrCreateAsset(id, m_meshAsset.GetAutoLoadBehavior()); - - if (asset) - { - m_meshAsset = asset; - OnAssetPropertyChanged(); - } - } - - void MeshComponentRenderNode::GetMemoryUsage(class ICrySizer* pSizer) const - { - pSizer->AddObjectSize(this); - } - - float MeshComponentRenderNode::GetUniformScale() - { - AZ::Vector3 scales = m_worldTransform.GetScale(); - AZ_Assert((scales.GetX() == scales.GetY()) && (scales.GetY() == scales.GetZ()), "Scales are not uniform"); - return scales.GetX(); - } - - float MeshComponentRenderNode::GetColumnScale(int column) - { - return m_worldTransform.GetScale().GetElement(column); - } - - void MeshComponentRenderNode::OnTransformChanged(const AZ::Transform&, const AZ::Transform& parentWorld) - { - // The entity to which we're attached has moved. - UpdateWorldTransform(parentWorld); - AzFramework::RenderGeometry::IntersectionNotificationBus::Event(m_contextId, - &AzFramework::RenderGeometry::IntersectionNotifications::OnGeometryChanged, GetEntityId()); - } - - void MeshComponentRenderNode::OnAssetReady(AZ::Data::Asset asset) - { - if (asset == m_meshAsset) - { - m_meshAsset = asset; - BuildRenderMesh(); - - if (HasMesh()) - { - const AZStd::string& materialOverridePath = m_material.GetAssetPath(); - if (!materialOverridePath.empty()) - { - m_materialOverride = gEnv->p3DEngine->GetMaterialManager()->LoadMaterial(materialOverridePath.c_str()); - - AZ_Warning("MeshComponent", m_materialOverride != gEnv->p3DEngine->GetMaterialManager()->GetDefaultMaterial(), - "Failed to load override Material \"%s\".", - materialOverridePath.c_str()); - } - else - { - m_materialOverride = nullptr; - } - - UpdateLocalBoundingBox(); - UpdateLodDistance(gEnv->p3DEngine->GetFrameLodInfo()); - RegisterWithRenderer(true); - - // Inform listeners that the mesh has been changed - LmbrCentral::MeshComponentNotificationBus::Event(m_renderOptions.m_attachedToEntityId, &LmbrCentral::MeshComponentNotifications::OnMeshCreated, asset); - AzFramework::RenderGeometry::IntersectionNotificationBus::Event(m_contextId, &AzFramework::RenderGeometry::IntersectionNotifications::OnGeometryChanged, GetEntityId()); - } - } - } - - void MeshComponentRenderNode::OnAssetReloaded(AZ::Data::Asset asset) - { - // note that this also corrects the assetId if it is incorrect - do not remove the following line - // even if you call OnAssetReady - OnAssetReady(asset); - } - - void MeshComponentRenderNode::UpdateWorldTransform(const AZ::Transform& entityTransform) - { - m_worldTransform = entityTransform; - - m_renderTransform = AZTransformToLYTransform(m_worldTransform); - - UpdateWorldBoundingBox(); - if (m_isRegisteredWithRenderer && m_renderOptions.AffectsGi()) - { - GiRegistrationBus::Broadcast(&GiRegistration::UpsertToGi, - m_renderOptions.m_attachedToEntityId, - m_worldTransform, - CalculateWorldAABB(), - m_meshAsset, - GetMaterial()); - } - - m_objectMoved = true; - } - - void MeshComponentRenderNode::UpdateLocalBoundingBox() - { - m_localBoundingBox.Reset(); - - if (HasMesh()) - { - m_localBoundingBox.Add(m_statObj->GetAABB()); - } - - AzFramework::EntityBoundsUnionRequestBus::Broadcast( - &AzFramework::EntityBoundsUnionRequestBus::Events::RefreshEntityLocalBoundsUnion, GetEntityId()); - - UpdateWorldBoundingBox(); - } - - void MeshComponentRenderNode::UpdateWorldBoundingBox() - { - m_worldBoundingBox.SetTransformedAABB(m_renderTransform, m_localBoundingBox); - - if (m_isRegisteredWithRenderer) - { - // Re-register with the renderer to update culling info - gEnv->p3DEngine->RegisterEntity(this); - } - } - - void MeshComponentRenderNode::SetVisible(bool isVisible) - { - if (m_visible != isVisible) - { - m_visible = isVisible; - RegisterWithRenderer(false); - RegisterWithRenderer(true); - } - } - - bool MeshComponentRenderNode::GetVisible() - { - return m_visible; - } - - void MeshComponentRenderNode::RegisterWithRenderer(bool registerWithRenderer) - { - if (gEnv && gEnv->p3DEngine) - { - if (registerWithRenderer) - { - if (!m_isRegisteredWithRenderer) - { - ApplyRenderOptions(); - - gEnv->p3DEngine->RegisterEntity(this); - - if (m_renderOptions.AffectsGi()) - { - GiRegistrationBus::Broadcast(&GiRegistration::UpsertToGi, - m_renderOptions.m_attachedToEntityId, - m_worldTransform, - CalculateWorldAABB(), - m_meshAsset, - GetMaterial()); - } - - m_isRegisteredWithRenderer = true; - } - } - else - { - if (m_isRegisteredWithRenderer) - { - gEnv->p3DEngine->FreeRenderNodeState(this); - - GiRegistrationBus::Broadcast(&GiRegistration::RemoveFromGi, - m_renderOptions.m_attachedToEntityId); - - m_isRegisteredWithRenderer = false; - } - } - } - } - - namespace MeshInternal - { - void UpdateRenderFlag(bool enable, int mask, unsigned int& flags) - { - if (enable) - { - flags |= mask; - } - else - { - flags &= ~mask; - } - } - } - - void MeshComponentRenderNode::ApplyRenderOptions() - { - using MeshInternal::UpdateRenderFlag; - unsigned int flags = GetRndFlags(); - flags |= ERF_COMPONENT_ENTITY; - - // Turn off any flag which has ever been set via auxiliary render flags - UpdateRenderFlag(false, m_auxiliaryRenderFlagsHistory, flags); - - // Update flags according to current render settings - UpdateRenderFlag(m_renderOptions.m_useVisAreas == false, ERF_OUTDOORONLY, flags); - UpdateRenderFlag(m_renderOptions.m_castShadows, ERF_CASTSHADOWMAPS | ERF_HAS_CASTSHADOWMAPS, flags); - UpdateRenderFlag(m_renderOptions.m_rainOccluder && m_renderOptions.IsStatic(), ERF_RAIN_OCCLUDER, flags); - UpdateRenderFlag(m_visible == false, ERF_HIDDEN, flags); - UpdateRenderFlag(m_renderOptions.m_receiveWind, ERF_RECVWIND, flags); - UpdateRenderFlag(m_renderOptions.m_visibilityOccluder && m_renderOptions.IsStatic(), ERF_GOOD_OCCLUDER, flags); - //Dynamic meshes shouldn't affect the navmeshes. If that decision is changed we should change this line to no longer require - //static and note that the flag is tied to the negation of the navemesh boolean. - //Also see the editormeshcomponent.cpp AffectNavemesh function. - UpdateRenderFlag(!(m_renderOptions.m_affectNavmesh && m_renderOptions.IsStatic()), ERF_EXCLUDE_FROM_TRIANGULATION, flags); - UpdateRenderFlag(false == m_renderOptions.m_affectDynamicWater && m_renderOptions.IsStatic(), ERF_NODYNWATER, flags); - UpdateRenderFlag(false == m_renderOptions.m_acceptDecals, ERF_NO_DECALNODE_DECALS, flags); - - UpdateRenderFlag(m_renderOptions.m_lodBoundingBoxBased, ERF_LOD_BBOX_BASED, flags); - - // Apply current auxiliary render flags - UpdateRenderFlag(true, m_auxiliaryRenderFlags, flags); - - m_fWSMaxViewDist = m_renderOptions.m_maxViewDist; - - SetViewDistanceMultiplier(m_renderOptions.m_viewDistMultiplier); - - SetLodRatio(static_cast(m_renderOptions.m_lodRatio)); - - SetRndFlags(flags); - } - - CLodValue MeshComponentRenderNode::ComputeLOD( int wantedLod, const SRenderingPassInfo& passInfo) - { - // Default values as per the CVar - default fade going between 2 and 8 meters with dissolve enabled - float dissolveDistMin = 2.0f; - float dissolveDistMax = 8.0f; - int dissolveEnabled = 1; - - if (gEnv && gEnv->pConsole) - { - static ICVar* dissolveDistMinCvar = gEnv->pConsole->GetCVar("e_DissolveDistMin"); - static ICVar* dissolveDistMaxCvar = gEnv->pConsole->GetCVar("e_DissolveDistMax"); - static ICVar* dissolveEnabledCvar = gEnv->pConsole->GetCVar("e_Dissolve"); - - dissolveDistMin = dissolveDistMinCvar->GetFVal(); - dissolveDistMax = dissolveDistMaxCvar->GetFVal(); - dissolveEnabled = dissolveEnabledCvar->GetIVal() ; - } - - const Vec3 cameraPos = passInfo.GetCamera().GetPosition(); - const float entityDistance = sqrt_tpl(Distance::Point_AABBSq(cameraPos, GetBBox())) * passInfo.GetZoomFactor(); - - wantedLod = CLAMP(wantedLod, m_statObj->GetMinUsableLod(), SMeshLodInfo::s_nMaxLodCount); - int currentLod = m_statObj->FindNearesLoadedLOD(wantedLod, true); - - if (dissolveEnabled && passInfo.IsGeneralPass()) - { - float invDissolveDist = 1.0f / CLAMP(0.1f * m_fWSMaxViewDist, dissolveDistMin, dissolveDistMax ); - int nextLod = m_statObj->FindNearesLoadedLOD(currentLod + 1, true); - - // If the user chose to base LOD switch on bounding boxes, then we do not use the geometric mean computed at init. - if (GetRndFlags() & ERF_LOD_BBOX_BASED) - { - const float lodRatio = GetLodRatioNormalized(); - if (lodRatio > 0.0f) - { - // We do not use a geometric mean per object but a global value for all objects. - static ICVar* lodBoundingBoxDistanceMultiplier = gEnv->pConsole->GetCVar("e_LodBoundingBoxDistanceMultiplier"); - - m_lodDistanceScaled = lodBoundingBoxDistanceMultiplier->GetFVal() * m_lodDistanceScaleValue; - } - } - else - { - m_lodDistanceScaled = m_lodDistance * m_lodDistanceScaleValue; - } - - float lodDistance = m_lodDistanceScaled * (currentLod + 1); - uint8 dissolveRatio255 = (uint8)SATURATEB((1.0f + (entityDistance - lodDistance) * invDissolveDist) * 255.f); - - if (dissolveRatio255 == 255) - { - return CLodValue(nextLod, 0, -1); - } - return CLodValue(currentLod, dissolveRatio255, nextLod); - } - - return CLodValue(currentLod); - } - - AZ::Aabb MeshComponentRenderNode::CalculateWorldAABB() const - { - AZ::Aabb aabb = AZ::Aabb::CreateNull(); - if (!m_worldBoundingBox.IsReset()) - { - aabb.AddPoint(LYVec3ToAZVec3(m_worldBoundingBox.min)); - aabb.AddPoint(LYVec3ToAZVec3(m_worldBoundingBox.max)); - } - return aabb; - } - - AZ::Aabb MeshComponentRenderNode::CalculateLocalAABB() const - { - AZ::Aabb aabb = AZ::Aabb::CreateNull(); - if (!m_localBoundingBox.IsReset()) - { - aabb.AddPoint(LYVec3ToAZVec3(m_localBoundingBox.min)); - aabb.AddPoint(LYVec3ToAZVec3(m_localBoundingBox.max)); - } - return aabb; - } - - /*IRenderNode*/ void MeshComponentRenderNode::Render(const struct SRendParams& inRenderParams, const struct SRenderingPassInfo& passInfo) - { - if (!HasMesh()) - { - return; - } - - if (!m_modificationHelper.GetMeshModified()) - { - IStatObj* obj = GetEntityStatObj(); - int subObjectCount = obj->GetSubObjectCount(); - - AZStd::function getSubObject; - if (subObjectCount == 0) - { - getSubObject = [obj](size_t index) - { - if (index > 0) - { - AZ_Warning("MeshComponentRenderNode", false, "Mesh indices out of range"); - return static_cast(nullptr); - } - return obj; - }; - } - else - { - getSubObject = [obj, subObjectCount](size_t index) - { - if (index >= subObjectCount) - { - AZ_Warning("MeshComponentRenderNode", false, "Mesh indices out of range"); - return static_cast(nullptr); - } - return obj->GetSubObject(index)->pStatObj; - }; - } - - for (const LmbrCentral::MeshModificationRequestHelper::MeshLODPrimIndex& meshIndices : m_modificationHelper.MeshesToEdit()) - { - if (meshIndices.lodIndex != 0) - { - continue; - } - - IStatObj* subObject = getSubObject(meshIndices.primitiveIndex); - if (!subObject) - { - continue; - } - - MeshModificationNotificationBus::Event( - GetEntityId(), - &MeshModificationNotificationBus::Events::ModifyMesh, - meshIndices.lodIndex, - meshIndices.primitiveIndex, - subObject->GetRenderMesh()); - } - - m_modificationHelper.SetMeshModified(true); - } - - SRendParams rParams(inRenderParams); - - // Assign a unique pInstance pointer, otherwise effects involving SRenderObjData will not work for this object. CEntityObject::Render does this for legacy entities. - rParams.pInstance = this; - - rParams.fAlpha = m_renderOptions.m_opacity; - - _smart_ptr previousMaterial = rParams.pMaterial; - const int previousObjectFlags = rParams.dwFObjFlags; - - if (m_materialOverride) - { - rParams.pMaterial = m_materialOverride; - } - - if (m_objectMoved) - { - rParams.dwFObjFlags |= FOB_DYNAMIC_OBJECT; - m_objectMoved = false; - } - - rParams.pMatrix = &m_renderTransform; - rParams.bForceDrawStatic = !m_renderOptions.m_dynamicMesh; - if (rParams.pMatrix->IsValid()) - { - rParams.lodValue = ComputeLOD(inRenderParams.lodValue.LodA(), passInfo); - m_statObj->Render(rParams, passInfo); - } - - rParams.pMaterial = previousMaterial; - rParams.dwFObjFlags = previousObjectFlags; - } - - /*IRenderNode*/ bool MeshComponentRenderNode::GetLodDistances(const SFrameLodInfo& frameLodInfo, float* distances) const - { - const float lodRatio = GetLodRatioNormalized(); - if (lodRatio > 0.0f) - { - const float distMultiplier = 1.f / (lodRatio * frameLodInfo.fTargetSize); - - for (int lodIndex = 0; lodIndex < SMeshLodInfo::s_nMaxLodCount; ++lodIndex) - { - distances[lodIndex] = m_lodDistance * (lodIndex + 1) * distMultiplier; - } - } - else - { - for (int lodIndex = 0; lodIndex < SMeshLodInfo::s_nMaxLodCount; ++lodIndex) - { - distances[lodIndex] = FLT_MAX; - } - } - return true; - } - - void MeshComponentRenderNode::UpdateLodDistance(const SFrameLodInfo& frameLodInfo) - { - SMeshLodInfo lodInfo; - - if (HasMesh()) - { - m_statObj->ComputeGeometricMean(lodInfo); - } - - m_lodDistance = sqrt(lodInfo.fGeometricMean); - - // The following computation need to stay in accordance with the 'GetLodDistances' formula. - const float lodRatio = GetLodRatioNormalized(); - if (lodRatio > 0.0f) - { - m_lodDistanceScaled = m_lodDistance / (lodRatio * frameLodInfo.fTargetSize); - m_lodDistanceScaleValue = 1.0f / (lodRatio * frameLodInfo.fTargetSize); - } - } - - /*IRenderNode*/ EERType MeshComponentRenderNode::GetRenderNodeType() - { - return m_renderOptions.IsStatic() ? eERType_StaticMeshRenderComponent : eERType_DynamicMeshRenderComponent; - } - - /*IRenderNode*/ bool MeshComponentRenderNode::CanExecuteRenderAsJob() - { - return !m_renderOptions.m_dynamicMesh - && !m_renderOptions.m_receiveWind - && m_modificationHelper.MeshesToEdit().empty(); - } - - /*IRenderNode*/ const char* MeshComponentRenderNode::GetName() const - { - return "MeshComponentRenderNode"; - } - - /*IRenderNode*/ const char* MeshComponentRenderNode::GetEntityClassName() const - { - return "MeshComponentRenderNode"; - } - - /*IRenderNode*/ Vec3 MeshComponentRenderNode::GetPos([[maybe_unused]] bool bWorldOnly /*= true*/) const - { - return m_renderTransform.GetTranslation(); - } - - /*IRenderNode*/ const AABB MeshComponentRenderNode::GetBBox() const - { - return m_worldBoundingBox; - } - - /*IRenderNode*/ void MeshComponentRenderNode::SetBBox(const AABB& WSBBox) - { - m_worldBoundingBox = WSBBox; - } - - /*IRenderNode*/ void MeshComponentRenderNode::OffsetPosition(const Vec3& delta) - { - // Recalculate local transform - AZ::Transform localTransform = AZ::Transform::CreateIdentity(); - EBUS_EVENT_ID_RESULT(localTransform, m_renderOptions.m_attachedToEntityId, AZ::TransformBus, GetLocalTM); - - localTransform.SetTranslation(localTransform.GetTranslation() + LYVec3ToAZVec3(delta)); - EBUS_EVENT_ID(m_renderOptions.m_attachedToEntityId, AZ::TransformBus, SetLocalTM, localTransform); - - m_objectMoved = true; - } - - /*IRenderNode*/ void MeshComponentRenderNode::SetMaterial(_smart_ptr pMat) - { - m_materialOverride = pMat; - - if (pMat) - { - m_material.SetAssetPath(pMat->GetName()); - } - else - { - // If no material is provided, we intend to reset to the original material so we treat - // it as an asset reset to recreate the mesh. - m_material.SetAssetPath(""); - OnAssetPropertyChanged(); - } - } - - /*IRenderNode*/ _smart_ptr MeshComponentRenderNode::GetMaterial([[maybe_unused]] Vec3* pHitPos /*= nullptr*/) - { - if (m_materialOverride) - { - return m_materialOverride; - } - - if (HasMesh()) - { - return m_statObj->GetMaterial(); - } - - return nullptr; - } - - /*IRenderNode*/ _smart_ptr MeshComponentRenderNode::GetMaterialOverride() - { - return m_materialOverride; - } - - /*IRenderNode*/ float MeshComponentRenderNode::GetMaxViewDist() - { - return(m_renderOptions.m_maxViewDist * 0.75f * GetViewDistanceMultiplier()); - } - - /*IRenderNode*/ IStatObj* MeshComponentRenderNode::GetEntityStatObj(unsigned int nPartId, [[maybe_unused]] unsigned int nSubPartId, Matrix34A* pMatrix, [[maybe_unused]] bool bReturnOnlyVisible) - { - if (0 == nPartId) - { - if (pMatrix) - { - *pMatrix = m_renderTransform; - } - - return m_statObj; - } - - return nullptr; - } - - /*IRenderNode*/ _smart_ptr MeshComponentRenderNode::GetEntitySlotMaterial(unsigned int nPartId, [[maybe_unused]] bool bReturnOnlyVisible, [[maybe_unused]] bool* pbDrawNear) - { - if (0 == nPartId) - { - return m_materialOverride; - } - - return nullptr; - } - - ////////////////////////////////////////////////////////////////////////// - // MeshComponent - const float MeshComponent::s_renderNodeRequestBusOrder = 100.f; - - MeshComponent::MeshComponent() - { - m_materialBusHandler = aznew MaterialOwnerRequestBusHandlerImpl(); - } - - MeshComponent::~MeshComponent() - { - delete m_materialBusHandler; - } - - void MeshComponent::Activate() - { - m_meshRenderNode.AttachToEntity(m_entity->GetId()); - m_materialBusHandler->Activate(&m_meshRenderNode, m_entity->GetId()); - bool isStatic = false; - AZ::TransformBus::EventResult(isStatic, m_entity->GetId(), &AZ::TransformBus::Events::IsStaticTransform); - m_meshRenderNode.SetTransformStaticState(isStatic); - // Note we are purposely connecting to buses before calling m_mesh.CreateMesh(). - // m_mesh.CreateMesh() can result in events (eg: OnMeshCreated) that we want receive. - MaterialOwnerRequestBus::Handler::BusConnect(m_entity->GetId()); - MeshComponentRequestBus::Handler::BusConnect(m_entity->GetId()); - AzFramework::BoundsRequestBus::Handler::BusConnect(m_entity->GetId()); - RenderNodeRequestBus::Handler::BusConnect(m_entity->GetId()); - AzFramework::EntityContextId contextId; - AzFramework::EntityIdContextQueryBus::EventResult(contextId, GetEntityId(), &AzFramework::EntityIdContextQueries::GetOwningContextId); - AzFramework::RenderGeometry::IntersectionRequestBus::Handler::BusConnect({ GetEntityId(), contextId }); - m_meshRenderNode.SetContextId(contextId); - m_meshRenderNode.CreateMesh(); - LegacyMeshComponentRequestBus::Handler::BusConnect(GetEntityId()); - } - - void MeshComponent::Deactivate() - { - AzFramework::RenderGeometry::IntersectionRequestBus::Handler::BusDisconnect(); - - MeshComponentRequestBus::Handler::BusDisconnect(); - AzFramework::BoundsRequestBus::Handler::BusDisconnect(); - MaterialOwnerRequestBus::Handler::BusDisconnect(); - LegacyMeshComponentRequestBus::Handler::BusDisconnect(); - RenderNodeRequestBus::Handler::BusDisconnect(); - - m_meshRenderNode.DestroyMesh(); - m_meshRenderNode.AttachToEntity(AZ::EntityId()); - m_materialBusHandler->Deactivate(); - } - - AZ::Aabb MeshComponent::GetWorldBounds() - { - return m_meshRenderNode.CalculateWorldAABB(); - } - - AZ::Aabb MeshComponent::GetLocalBounds() - { - return m_meshRenderNode.CalculateLocalAABB(); - } - - void MeshComponent::SetMeshAsset(const AZ::Data::AssetId& id) - { - m_meshRenderNode.SetMeshAsset(id); - } - - bool MeshComponent::IsMaterialOwnerReady() - { - return m_materialBusHandler->IsMaterialOwnerReady(); - } - - void MeshComponent::SetMaterial(_smart_ptr material) - { - m_materialBusHandler->SetMaterial(material); - } - - _smart_ptr MeshComponent::GetMaterial() - { - return m_materialBusHandler->GetMaterial(); - } - - void MeshComponent::SetMaterialHandle(const MaterialHandle& materialHandle) - { - m_materialBusHandler->SetMaterialHandle(materialHandle); - } - - MaterialHandle MeshComponent::GetMaterialHandle() - { - return m_materialBusHandler->GetMaterialHandle(); - } - - void MeshComponent::SetMaterialParamVector4(const AZStd::string& name, const AZ::Vector4& value, int materialId) - { - m_materialBusHandler->SetMaterialParamVector4(name, value, materialId); - } - - void MeshComponent::SetMaterialParamVector3(const AZStd::string& name, const AZ::Vector3& value, int materialId) - { - m_materialBusHandler->SetMaterialParamVector3(name, value, materialId); - } - - void MeshComponent::SetMaterialParamColor(const AZStd::string& name, const AZ::Color& value, int materialId) - { - m_materialBusHandler->SetMaterialParamColor(name, value, materialId); - } - - void MeshComponent::SetMaterialParamFloat(const AZStd::string& name, float value, int materialId) - { - m_materialBusHandler->SetMaterialParamFloat(name, value, materialId); - } - - AZ::Vector4 MeshComponent::GetMaterialParamVector4(const AZStd::string& name, int materialId) - { - return m_materialBusHandler->GetMaterialParamVector4(name, materialId); - } - - AZ::Vector3 MeshComponent::GetMaterialParamVector3(const AZStd::string& name, int materialId) - { - return m_materialBusHandler->GetMaterialParamVector3(name, materialId); - } - - AZ::Color MeshComponent::GetMaterialParamColor(const AZStd::string& name, int materialId) - { - return m_materialBusHandler->GetMaterialParamColor(name, materialId); - } - - float MeshComponent::GetMaterialParamFloat(const AZStd::string& name, int materialId) - { - return m_materialBusHandler->GetMaterialParamFloat(name, materialId); - } - - IRenderNode* MeshComponent::GetRenderNode() - { - return &m_meshRenderNode; - } - - float MeshComponent::GetRenderNodeRequestBusOrder() const - { - return s_renderNodeRequestBusOrder; - } - - IStatObj* MeshComponent::GetStatObj() - { - return m_meshRenderNode.GetEntityStatObj(); - } - - AzFramework::RenderGeometry::RayResult MeshComponent::RenderGeometryIntersect(const AzFramework::RenderGeometry::RayRequest& ray) - { - AzFramework::RenderGeometry::RayResult result; - if (!GetVisibility() && ray.m_onlyVisible) - { - return result; - } - - if (IStatObj* geometry = GetStatObj()) - { - const AZ::Vector3 rayDirection = (ray.m_endWorldPosition - ray.m_startWorldPosition); - const AZ::Transform& transform = m_meshRenderNode.GetTransform(); - const AZ::Transform inverseTransform = transform.GetInverse(); - - const AZ::Vector3 rayStartLocal = inverseTransform.TransformPoint(ray.m_startWorldPosition); - const AZ::Vector3 rayDistNormLocal = inverseTransform.TransformVector(rayDirection).GetNormalized(); - - SRayHitInfo hi; - hi.inReferencePoint = AZVec3ToLYVec3(rayStartLocal); - hi.inRay = Ray(hi.inReferencePoint, AZVec3ToLYVec3(rayDistNormLocal)); - hi.bInFirstHit = true; - hi.bGetVertColorAndTC = true; - if (geometry->RayIntersection(hi)) - { - AZ::Matrix3x4 invTransformMatrix = AZ::Matrix3x4::CreateFromTransform(inverseTransform); - invTransformMatrix.Transpose(); - - result.m_uv = LYVec2ToAZVec2(hi.vHitTC); - result.m_worldPosition = transform.TransformPoint(LYVec3ToAZVec3(hi.vHitPos)); - result.m_worldNormal = invTransformMatrix.Multiply3x3(LYVec3ToAZVec3(hi.vHitNormal)).GetNormalized(); - result.m_distance = (result.m_worldPosition - ray.m_startWorldPosition).GetLength(); - result.m_entityAndComponent = { GetEntityId(), GetId() }; - } - } - return result; - } - - bool MeshComponent::GetVisibility() - { - return m_meshRenderNode.GetVisible(); - } - - void MeshComponent::SetVisibility(bool isVisible) - { - m_meshRenderNode.SetVisible(isVisible); - } - - void MeshComponentRenderNode::BuildRenderMesh() - { - m_statObj = nullptr; // Release smart pointer - - MeshAsset* data = m_meshAsset.Get(); - if (!data || !data->m_statObj) - { - return; - } - - // Populate m_statObj. If the mesh doesn't require to be unique, we reuse the render mesh from the asset. If the - // mesh requires to be unique, we create a copy of the asset's render mesh since it will be modified. - - bool hasClothData = !data->m_statObj->GetClothData().empty(); - const int subObjectCount = data->m_statObj->GetSubObjectCount(); - for (int i = 0; i < subObjectCount && !hasClothData; ++i) - { - IStatObj::SSubObject* subObject = data->m_statObj->GetSubObject(i); - if (subObject && - subObject->pStatObj && - !subObject->pStatObj->GetClothData().empty()) - { - hasClothData = true; - } - } - - bool useUniqueMesh = hasClothData; - - if (useUniqueMesh) - { - // Create a copy since each mesh can be deforming differently and we need to send different meshes to render - m_statObj = data->m_statObj->Clone( /*bCloneGeometry*/ true, /*bCloneChildren*/ true, /*bMeshesOnly*/ false); - } - else - { - // Reuse the same render mesh - m_statObj = data->m_statObj; - } - } -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Source/Rendering/MeshComponent.h b/Gems/LmbrCentral/Code/Source/Rendering/MeshComponent.h deleted file mode 100644 index f7a7f5d861..0000000000 --- a/Gems/LmbrCentral/Code/Source/Rendering/MeshComponent.h +++ /dev/null @@ -1,393 +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 -#include -#include -#include - -#include - -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -namespace LmbrCentral -{ - class MaterialOwnerRequestBusHandlerImpl; - - /*! - * RenderNode implementation responsible for integrating with the renderer. - * The node owns render flags, the mesh instance, and the render transform. - */ - class MeshComponentRenderNode - : public IRenderNode - , public AZ::TransformNotificationBus::Handler - , public AZ::Data::AssetBus::Handler - { - friend class EditorMeshComponent; - public: - using MaterialPtr = _smart_ptr < IMaterial > ; - using MeshPtr = _smart_ptr < IStatObj > ; - - AZ_TYPE_INFO(MeshComponentRenderNode, "{46FF2BC4-BEF9-4CC4-9456-36C127C310D7}"); - - MeshComponentRenderNode(); - ~MeshComponentRenderNode() override; - - void CopyPropertiesTo(MeshComponentRenderNode& rhs) const; - - //! Notifies render node which entity owns it, for subscribing to transform - //! bus, etc. - void AttachToEntity(AZ::EntityId id); - - //! Returns true after all required assets are loaded - bool IsReady() const override; - - //! Instantiate mesh instance. - void CreateMesh(); - - //! Destroy mesh instance. - void DestroyMesh(); - - //! Returns true if the node has geometry assigned. - bool HasMesh() const; - - //! Assign a new mesh asset - void SetMeshAsset(const AZ::Data::AssetId& id); - - //! Get the mesh asset - AZ::Data::Asset GetMeshAsset() { return m_meshAsset; } - - //! Invoked in the editor when the user assigns a new asset. - void OnAssetPropertyChanged(); - - //! Render the mesh - void RenderMesh(const struct SRendParams& inRenderParams, const struct SRenderingPassInfo& passInfo); - - //! Updates the render node's world transform based on the entity's. - void UpdateWorldTransform(const AZ::Transform& entityTransform); - - //! Computes world-space AABB. - AZ::Aabb CalculateWorldAABB() const; - - //! Computes local-space AABB. - AZ::Aabb CalculateLocalAABB() const; - - ////////////////////////////////////////////////////////////////////////// - // AZ::Data::AssetBus::Handler - void OnAssetReady(AZ::Data::Asset asset) override; - void OnAssetReloaded(AZ::Data::Asset asset) override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // AZ::TransformNotificationBus::Handler interface implementation - void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; - ////////////////////////////////////////////////////////////////////////// - - ////////////////////////////////////////////////////////////////////////// - // IRenderNode interface implementation - void Render(const struct SRendParams& inRenderParams, const struct SRenderingPassInfo& passInfo) override; - bool GetLodDistances(const SFrameLodInfo& frameLodInfo, float* distances) const override; - float GetFirstLodDistance() const override { return m_lodDistance; } - EERType GetRenderNodeType() override; - bool CanExecuteRenderAsJob() override; - const char* GetName() const override; - const char* GetEntityClassName() const override; - Vec3 GetPos(bool bWorldOnly = true) const override; - const AABB GetBBox() const override; - void SetBBox(const AABB& WSBBox) override; - void OffsetPosition(const Vec3& delta) override; - void SetMaterial(_smart_ptr pMat) override; - _smart_ptr GetMaterial(Vec3* pHitPos = nullptr) override; - _smart_ptr GetMaterialOverride() override; - IStatObj* GetEntityStatObj(unsigned int nPartId = 0, unsigned int nSubPartId = 0, Matrix34A* pMatrix = nullptr, bool bReturnOnlyVisible = false) override; - _smart_ptr GetEntitySlotMaterial(unsigned int nPartId, bool bReturnOnlyVisible = false, bool* pbDrawNear = nullptr) override; - float GetMaxViewDist() override; - void GetMemoryUsage(class ICrySizer* pSizer) const override; - AZ::EntityId GetEntityId() override { return m_renderOptions.m_attachedToEntityId; } - float GetUniformScale() override; - float GetColumnScale(int column) override; - ////////////////////////////////////////////////////////////////////////// - - //! Invoked in the editor when a property requiring render state refresh - //! has changed. - void RefreshRenderState(); - - //! Set/get auxiliary render flags. - void SetAuxiliaryRenderFlags(uint32 flags); - uint32 GetAuxiliaryRenderFlags() const { return m_auxiliaryRenderFlags; } - void UpdateAuxiliaryRenderFlags(bool on, uint32 mask); - - void SetVisible(bool isVisible); - bool GetVisible(); - - static void Reflect(AZ::ReflectContext* context); - - static float GetDefaultMaxViewDist(); - static AZ::Uuid GetRenderOptionsUuid() { return AZ::AzTypeInfo::Uuid(); } - - //! Registers or unregisters our render node with the render. - void RegisterWithRenderer(bool registerWithRenderer); - bool IsRegisteredWithRenderer() const { return m_isRegisteredWithRenderer; } - - //! This function caches off the static flag stat of the transform; - void SetTransformStaticState(bool isStatic); - const AZ::Transform& GetTransform() const; - - void SetContextId(AzFramework::EntityContextId contextId) { m_contextId = contextId; } - - protected: - - //! Calculates base LOD distance based on mesh characteristics. - //! We do this each time the mesh resource changes. - void UpdateLodDistance(const SFrameLodInfo& frameLodInfo); - - //! Computes desired LOD level for the assigned mesh instance. - CLodValue ComputeLOD(int wantedLod, const SRenderingPassInfo& passInfo); - - //! Computes the entity-relative (local space) bounding box for - //! the assigned mesh. - virtual void UpdateLocalBoundingBox(); - - //! Updates the world-space bounding box and world space transform - //! for the assigned mesh. - void UpdateWorldBoundingBox(); - - //! Applies configured render options to the render node. - void ApplyRenderOptions(); - - //! Populates the render mesh from the mesh asset - void BuildRenderMesh(); - - class MeshRenderOptions - { - public: - - AZ_TYPE_INFO(MeshRenderOptions, "{EFF77BEB-CB99-44A3-8F15-111B0200F50D}") - - MeshRenderOptions(); - - float m_opacity; //!< Alpha/opacity value for rendering. - float m_maxViewDist; //!< Maximum draw distance. - float m_viewDistMultiplier; //!< Adjusts max view distance. If 1.0 then default max view distance is used. - AZ::u32 m_lodRatio; //!< Controls LOD distance ratio. - bool m_useVisAreas; //!< Allow VisAreas to control this component's visibility. - bool m_castShadows; //!< Casts shadows. - bool m_lodBoundingBoxBased; //!< LOD based on Bounding Boxes. - bool m_rainOccluder; //!< Occludes raindrops. - bool m_affectNavmesh; //!< Cuts out of the navmesh. - bool m_affectDynamicWater; //!< Affects dynamic water (ripples). - bool m_acceptDecals; //!< Accepts decals. - bool m_receiveWind; //!< Receives wind. - bool m_visibilityOccluder; //!< Appropriate for visibility occluding. - bool m_dynamicMesh; // Mesh can change or deform independent of transform - bool m_hasStaticTransform; - bool m_affectGI; //!< Mesh affects Global Illumination. - - //! The Id of the entity we're associated with, for bus subscription. - //Moved from render mesh to this struct for serialization/reflection utility - AZ::EntityId m_attachedToEntityId; - - AZStd::function m_changeCallback; - - // Minor property changes don't require refreshing/rebuilding the property tree since no other properties - // are shown/hidden as a result of a change. - AZ::u32 OnMinorChanged() - { - if (m_changeCallback) - { - m_changeCallback(); - } - return AZ::Edit::PropertyRefreshLevels::None; - } - - AZ::u32 OnMajorChanged() - { - if (m_changeCallback) - { - m_changeCallback(); - } - return AZ::Edit::PropertyRefreshLevels::EntireTree; - } - - //Returns true if the transform is static and the mesh is not deformable. - bool IsStatic() const; - bool AffectsGi() const; - AZ::Crc32 StaticPropertyVisibility() const; - static void Reflect(AZ::ReflectContext* context); - - private: - static bool VersionConverter(AZ::SerializeContext& context, - AZ::SerializeContext::DataElementNode& classElement); - }; - - //! Should be visible. - bool m_visible; - - //! User-specified material override. - AzFramework::SimpleAssetReference m_material; - - //! Render flags/options. - MeshRenderOptions m_renderOptions; - - //! Currently-assigned material. Null if no material is manually assigned. - MaterialPtr m_materialOverride; - - //! World and render transforms. - //! These are equivalent, but for different math libraries. - AZ::Transform m_worldTransform; - Matrix34 m_renderTransform; - - //! Local and world bounding boxes. - AABB m_localBoundingBox; - AABB m_worldBoundingBox; - - //! Additional render flags -- for special editor behavior, etc. - uint32 m_auxiliaryRenderFlags; - - //! Remember which flags have ever been toggled externally so that we can shut them off - uint32 m_auxiliaryRenderFlagsHistory; - - //! Reference to current asset - AZ::Data::Asset m_meshAsset; - MeshPtr m_statObj; - - //! Computed LOD distance. - float m_lodDistance; - - //! Computed first LOD distance (the following are multiplies of the index) - float m_lodDistanceScaled; - - //! Scale we need to multiply the distance by. - float m_lodDistanceScaleValue; - - //! Identifies whether we've already registered our node with the renderer. - bool m_isRegisteredWithRenderer; - - //! Tracks if the object was moved so we can notify the renderer. - bool m_objectMoved; - - // Helper to store indices for meshes to be modified by other components. - MeshModificationRequestHelper m_modificationHelper; - - // EntityContext of the component - AzFramework::EntityContextId m_contextId; - }; - - - - class MeshComponent - : public AZ::Component - , public MeshComponentRequestBus::Handler - , public MaterialOwnerRequestBus::Handler - , public RenderNodeRequestBus::Handler - , public LegacyMeshComponentRequestBus::Handler - , public AzFramework::BoundsRequestBus::Handler - , public AzFramework::RenderGeometry::IntersectionRequestBus::Handler - { - public: - friend class EditorMeshComponent; - - AZ_COMPONENT(MeshComponent, "{2F4BAD46-C857-4DCB-A454-C412DE67852A}"); - - MeshComponent(); - ~MeshComponent() override; - - AZ_DISABLE_COPY_MOVE(MeshComponent); - - // AZ::Component overrides ... - void Activate() override; - void Deactivate() override; - - // BoundsRequestBus and MeshComponentRequestBus overrides ... - AZ::Aabb GetWorldBounds() override; - AZ::Aabb GetLocalBounds() override; - - // MeshComponentRequestBus overrides ... - void SetMeshAsset(const AZ::Data::AssetId& id) override; - AZ::Data::Asset GetMeshAsset() override { return m_meshRenderNode.GetMeshAsset(); } - void SetVisibility(bool newVisibility) override; - bool GetVisibility() override; - - // MaterialOwnerRequestBus overrides ... - bool IsMaterialOwnerReady() override; - void SetMaterial(_smart_ptr) override; - _smart_ptr GetMaterial() override; - void SetMaterialHandle(const MaterialHandle& materialHandle) override; - MaterialHandle GetMaterialHandle() override; - void SetMaterialParamVector4(const AZStd::string& /*name*/, const AZ::Vector4& /*value*/, int /*materialId = 1*/) override; - void SetMaterialParamVector3(const AZStd::string& /*name*/, const AZ::Vector3& /*value*/, int /*materialId = 1*/) override; - void SetMaterialParamColor(const AZStd::string& /*name*/, const AZ::Color& /*value*/, int /*materialId = 1*/) override; - void SetMaterialParamFloat(const AZStd::string& /*name*/, float /*value*/, int /*materialId = 1*/) override; - AZ::Vector4 GetMaterialParamVector4(const AZStd::string& /*name*/, int /*materialId = 1*/) override; - AZ::Vector3 GetMaterialParamVector3(const AZStd::string& /*name*/, int /*materialId = 1*/) override; - AZ::Color GetMaterialParamColor(const AZStd::string& /*name*/, int /*materialId = 1*/) override; - float GetMaterialParamFloat(const AZStd::string& /*name*/, int /*materialId = 1*/) override; - - // RenderNodeRequestBus overrides ... - IRenderNode* GetRenderNode() override; - float GetRenderNodeRequestBusOrder() const override; - static const float s_renderNodeRequestBusOrder; - - // MeshComponentRequestBus overrides ... - IStatObj* GetStatObj() override; - - // IntersectionRequestBus overrides ... - AzFramework::RenderGeometry::RayResult RenderGeometryIntersect(const AzFramework::RenderGeometry::RayRequest& ray) override; - - protected: - - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC("MeshService", 0x71d8a455)); - provided.push_back(AZ_CRC("LegacyMeshService", 0xb462a299)); - } - - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC("MeshService", 0x71d8a455)); - incompatible.push_back(AZ_CRC("LegacyMeshService", 0xb462a299)); - } - - static void GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) - { - required.push_back(AZ_CRC("TransformService", 0x8ee22c50)); - } - - static void Reflect(AZ::ReflectContext* context); - - void RequireSendingRenderMeshForEditing(size_t lodIndex, size_t primitiveIndex); - void NoRenderMeshesForEditing(); - - ////////////////////////////////////////////////////////////////////////// - // Reflected Data - MeshComponentRenderNode m_meshRenderNode; - MaterialOwnerRequestBusHandlerImpl* m_materialBusHandler; - }; - -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/Tests/EditorMeshComponentTests.cpp b/Gems/LmbrCentral/Code/Tests/EditorMeshComponentTests.cpp deleted file mode 100644 index 8586955254..0000000000 --- a/Gems/LmbrCentral/Code/Tests/EditorMeshComponentTests.cpp +++ /dev/null @@ -1,293 +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 "LmbrCentral_precompiled.h" - -#include -#include -#include -#include -#include -#include -#include -#include - - -#include "Source/Rendering/EditorMeshComponent.h" - -namespace UnitTest -{ - // base physical entity which can be derived from to detect other specific use-cases - struct PhysicalEntityPlaceHolder - : public IPhysicalEntity - { - pe_type GetType() const override { return PE_NONE; } - int AddRef() override { return 0; } - int Release() override { return 0; } - int SetParams([[maybe_unused]] const pe_params* params, [[maybe_unused]] int bThreadSafe = 0) override { return 0; } - int GetParams([[maybe_unused]] pe_params* params) const override { return 0; } - int GetStatus([[maybe_unused]] pe_status* status) const override { return 0; } - int Action(const pe_action*, [[maybe_unused]] int bThreadSafe = 0) override { return 0; } - int AddGeometry([[maybe_unused]] phys_geometry* pgeom, [[maybe_unused]] pe_geomparams* params, [[maybe_unused]] int id = -1, [[maybe_unused]] int bThreadSafe = 0) override { return 0; } - void RemoveGeometry([[maybe_unused]] int id, [[maybe_unused]] int bThreadSafe = 0) override {} - PhysicsForeignData GetForeignData([[maybe_unused]] int itype = 0) const override { return PhysicsForeignData{}; } - int GetiForeignData() const override { return 0; } - int GetStateSnapshot([[maybe_unused]] class CStream& stm, [[maybe_unused]] float time_back = 0, [[maybe_unused]] int flags = 0) override { return 0; } - int GetStateSnapshot([[maybe_unused]] TSerialize ser, [[maybe_unused]] float time_back = 0, [[maybe_unused]] int flags = 0) override { return 0; } - int SetStateFromSnapshot([[maybe_unused]] class CStream& stm, [[maybe_unused]] int flags = 0) override { return 0; } - int PostSetStateFromSnapshot() override { return 0; } - unsigned int GetStateChecksum() override { return 0; } - void SetNetworkAuthority([[maybe_unused]] int authoritive = -1, [[maybe_unused]] int paused = -1) override {} - int SetStateFromSnapshot([[maybe_unused]] TSerialize ser, [[maybe_unused]] int flags = 0) override { return 0; } - int SetStateFromTypedSnapshot([[maybe_unused]] TSerialize ser, [[maybe_unused]] int type, [[maybe_unused]] int flags = 0) override { return 0; } - int GetStateSnapshotTxt([[maybe_unused]] char* txtbuf, [[maybe_unused]] int szbuf, [[maybe_unused]] float time_back = 0) override { return 0; } - void SetStateFromSnapshotTxt([[maybe_unused]] const char* txtbuf, [[maybe_unused]] int szbuf) override {} - int DoStep([[maybe_unused]] float time_interval) override { return 0; } - int DoStep([[maybe_unused]] float time_interval, [[maybe_unused]] int iCaller) override { return 0; } - void StartStep([[maybe_unused]] float time_interval) override {} - void StepBack([[maybe_unused]] float time_interval) override {} - void GetMemoryStatistics([[maybe_unused]] ICrySizer* pSizer) const override {} - }; - - // special test fake to validate incoming pe_params - struct PhysicalEntitySetParamsCheck - : public PhysicalEntityPlaceHolder - { - int SetParams(const pe_params* params, [[maybe_unused]] int bThreadSafe = 0) override - { - if (params->type == pe_params_pos::type_id) - { - pe_params_pos* params_pos = (pe_params_pos*)params; - - Vec3 s; - if (Matrix34* m34 = params_pos->pMtx3x4) - { - s.Set(m34->GetColumn(0).len(), m34->GetColumn(1).len(), m34->GetColumn(2).len()); - Matrix33 m33(m34->GetColumn(0) / s.x, m34->GetColumn(1) / s.y, m34->GetColumn(2) / s.z); - // ensure passed in params_pos->pMtx3x4 is orthonormal - // ref - see Cry_Quat.h - explicit ILINE Quat_tpl(const Matrix33_tpl&m) - m_isOrthonormal = m33.IsOrthonormalRH(0.1f); - } - } - - return 0; - } - - bool m_isOrthonormal = false; - }; - - class TestEditorMeshComponent - : public LmbrCentral::EditorMeshComponent - { - public: - AZ_EDITOR_COMPONENT(TestEditorMeshComponent, "{6C6B593A-1946-4239-AE16-E8B96D9835E5}", LmbrCentral::EditorMeshComponent) - - static void Reflect(AZ::ReflectContext* context); - - TestEditorMeshComponent() = default; - - }; - - void TestEditorMeshComponent::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(0); - } - } - - class EditorMeshComponentTestFixture - : public ToolsApplicationFixture - { - AZStd::unique_ptr m_testMeshComponentDescriptor; - - public: - void SetUpEditorFixtureImpl() override - { - AZ::SerializeContext* serializeContext = nullptr; - AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationRequests::GetSerializeContext); - - m_testMeshComponentDescriptor = - AZStd::unique_ptr(TestEditorMeshComponent::CreateDescriptor()); - m_testMeshComponentDescriptor->Reflect(serializeContext); - } - - void TearDownEditorFixtureImpl() override - { - m_testMeshComponentDescriptor.reset(); - } - }; - - struct MeshAssetHandlerFixture - : ScopedAllocatorSetupFixture - { - protected: - void SetUp() override - { - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - - AZ::Data::AssetManager::Create(AZ::Data::AssetManager::Descriptor()); - AZ::Data::AssetManager::Instance().SetAssetInfoUpgradingEnabled(false); - - m_handler.Register(); - } - - void TearDown() override - { - m_handler.Unregister(); - AZ::Data::AssetManager::Destroy(); - - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - } - - LmbrCentral::MeshAssetHandler m_handler; - }; - - struct MockAssetSystemRequestHandler - : AzFramework::AssetSystemRequestBus::Handler - { - MockAssetSystemRequestHandler() - { - BusConnect(); - } - - ~MockAssetSystemRequestHandler() - { - BusDisconnect(); - } - - AzFramework::AssetSystem::AssetStatus GetAssetStatusById([[maybe_unused]] const AZ::Data::AssetId& assetId) override - { - m_statusRequest = true; - - return AzFramework::AssetSystem::AssetStatus_Queued; - } - - MOCK_METHOD1(CompileAssetSync, AzFramework::AssetSystem::AssetStatus (const AZStd::string&)); - MOCK_METHOD1(CompileAssetSync_FlushIO, AzFramework::AssetSystem::AssetStatus (const AZStd::string&)); - MOCK_METHOD1(CompileAssetSyncById, AzFramework::AssetSystem::AssetStatus (const AZ::Data::AssetId&)); - MOCK_METHOD1(CompileAssetSyncById_FlushIO, AzFramework::AssetSystem::AssetStatus (const AZ::Data::AssetId&)); - MOCK_METHOD4(ConfigureSocketConnection, bool (const AZStd::string&, const AZStd::string&, const AZStd::string&, const AZStd::string&)); - MOCK_METHOD1(Connect, bool (const char*)); - MOCK_METHOD2(ConnectWithTimeout, bool (const char*, AZStd::chrono::duration)); - MOCK_METHOD0(Disconnect, bool ()); - MOCK_METHOD1(EscalateAssetBySearchTerm, bool (AZStd::string_view)); - MOCK_METHOD1(EscalateAssetByUuid, bool (const AZ::Uuid&)); - MOCK_METHOD0(GetAssetProcessorPingTimeMilliseconds, float ()); - MOCK_METHOD1(GetAssetStatus, AzFramework::AssetSystem::AssetStatus (const AZStd::string&)); - MOCK_METHOD1(GetAssetStatus_FlushIO, AzFramework::AssetSystem::AssetStatus (const AZStd::string&)); - MOCK_METHOD2(GetAssetStatusSearchType, AzFramework::AssetSystem::AssetStatus(const AZStd::string&, int)); - MOCK_METHOD2(GetAssetStatusSearchType_FlushIO, AzFramework::AssetSystem::AssetStatus(const AZStd::string&, int)); - MOCK_METHOD1(GetAssetStatusById_FlushIO, AzFramework::AssetSystem::AssetStatus (const AZ::Data::AssetId&)); - MOCK_METHOD3(GetUnresolvedProductReferences, void (AZ::Data::AssetId, AZ::u32&, AZ::u32&)); - MOCK_METHOD0(SaveCatalog, bool ()); - MOCK_METHOD1(SetAssetProcessorIP, void (const AZStd::string&)); - MOCK_METHOD1(SetAssetProcessorPort, void (AZ::u16)); - MOCK_METHOD1(SetBranchToken, void (const AZStd::string&)); - MOCK_METHOD1(SetProjectName, void (const AZStd::string&)); - MOCK_METHOD0(ShowAssetProcessor, void ()); - MOCK_METHOD1(ShowInAssetProcessor, void (const AZStd::string&)); - MOCK_METHOD1(WaitUntilAssetProcessorReady, bool(AZStd::chrono::duration)); - MOCK_METHOD1(WaitUntilAssetProcessorConnected, bool(AZStd::chrono::duration)); - MOCK_METHOD1(WaitUntilAssetProcessorDisconnected, bool(AZStd::chrono::duration)); - MOCK_METHOD0(AssetProcessorIsReady, bool()); - MOCK_METHOD0(ConnectedWithAssetProcessor, bool()); - MOCK_METHOD0(DisconnectedWithAssetProcessor, bool()); - MOCK_METHOD0(NegotiationWithAssetProcessorFailed, bool()); - MOCK_METHOD0(StartDisconnectingAssetProcessor, void()); - MOCK_METHOD1(EstablishAssetProcessorConnection, bool(const AzFramework::AssetSystem::ConnectionSettings&)); - MOCK_METHOD3(AppendAssetToPrioritySet, bool (const AZStd::string&, const AZ::Uuid&, uint32_t)); - MOCK_METHOD3(AppendAssetsToPrioritySet, bool (const AZStd::string&, const AZStd::vector&, uint32_t)); - MOCK_METHOD2(RemoveAssetFromPrioritySet, bool (const AZStd::string&, const AZ::Uuid&)); - MOCK_METHOD2(RemoveAssetsFromPrioritySet, bool (const AZStd::string&, const AZStd::vector&)); - bool m_statusRequest = false; - }; - - struct MockCatalog - : AZ::Data::AssetCatalogRequestBus::Handler - { - MockCatalog() - { - BusConnect(); - } - - ~MockCatalog() - { - BusDisconnect(); - } - - AZ::Data::AssetId GetAssetIdByPath(const char*, const AZ::Data::AssetType&, bool) override - { - m_generatedId = AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 1234); - - return m_generatedId; - } - - MOCK_METHOD1(GetAssetInfoById, AZ::Data::AssetInfo (const AZ::Data::AssetId&)); - MOCK_METHOD1(AddAssetType, void (const AZ::Data::AssetType&)); - MOCK_METHOD1(AddDeltaCatalog, bool (AZStd::shared_ptr)); - MOCK_METHOD1(AddExtension, void (const char*)); - MOCK_METHOD0(ClearCatalog, void ()); - MOCK_METHOD5(CreateBundleManifest, bool (const AZStd::string&, const AZStd::vector&, const AZStd::string&, int, const AZStd::vector&)); - MOCK_METHOD2(CreateDeltaCatalog, bool (const AZStd::vector&, const AZStd::string&)); - MOCK_METHOD0(DisableCatalog, void ()); - MOCK_METHOD1(EnableCatalogForAsset, void (const AZ::Data::AssetType&)); - MOCK_METHOD3(EnumerateAssets, void (BeginAssetEnumerationCB, AssetEnumerationCB, EndAssetEnumerationCB)); - MOCK_METHOD1(GenerateAssetIdTEMP, AZ::Data::AssetId (const char*)); - MOCK_METHOD1(GetAllProductDependencies, AZ::Outcome, AZStd::string> (const AZ::Data::AssetId&)); - MOCK_METHOD3(GetAllProductDependenciesFilter, AZ::Outcome, AZStd::string> (const AZ::Data::AssetId&, const AZStd::unordered_set&, const AZStd::vector&)); - MOCK_METHOD1(GetAssetPathById, AZStd::string (const AZ::Data::AssetId&)); - MOCK_METHOD1(GetDirectProductDependencies, AZ::Outcome, AZStd::string> (const AZ::Data::AssetId&)); - MOCK_METHOD1(GetHandledAssetTypes, void (AZStd::vector&)); - MOCK_METHOD0(GetRegisteredAssetPaths, AZStd::vector ()); - MOCK_METHOD2(InsertDeltaCatalog, bool (AZStd::shared_ptr, size_t)); - MOCK_METHOD2(InsertDeltaCatalogBefore, bool (AZStd::shared_ptr, AZStd::shared_ptr)); - MOCK_METHOD1(LoadCatalog, bool (const char*)); - MOCK_METHOD2(RegisterAsset, void (const AZ::Data::AssetId&, AZ::Data::AssetInfo&)); - MOCK_METHOD1(RemoveDeltaCatalog, bool (AZStd::shared_ptr)); - MOCK_METHOD1(SaveCatalog, bool (const char*)); - MOCK_METHOD0(StartMonitoringAssets, void ()); - MOCK_METHOD0(StopMonitoringAssets, void ()); - MOCK_METHOD1(UnregisterAsset, void (const AZ::Data::AssetId&)); - - AZ::Data::AssetId m_generatedId{}; - }; - - struct MockAssetData - : LmbrCentral::MeshAsset - { - MockAssetData(AZ::Data::AssetId assetId) - { - m_assetId = assetId; - } - }; - - TEST_F(MeshAssetHandlerFixture, LoadAsset_StillInQueue_LoadsSubstituteAsset) - { - MockAssetSystemRequestHandler assetSystem; - MockCatalog catalog; - AZ::Data::AssetId assetId(AZ::Uuid::CreateRandom(), 0); - - AZ::Data::Asset asset(aznew MockAssetData(assetId), AZ::Data::AssetLoadBehavior::Default); - auto substituteAssetId = m_handler.AssetMissingInCatalog(asset); - - ASSERT_TRUE(assetSystem.m_statusRequest); - ASSERT_TRUE(catalog.m_generatedId.IsValid()); - ASSERT_EQ(substituteAssetId, catalog.m_generatedId); - } - - - -} // namespace UnitTest diff --git a/Gems/LmbrCentral/Code/include/LmbrCentral/Animation/SkeletalHierarchyRequestBus.h b/Gems/LmbrCentral/Code/include/LmbrCentral/Animation/SkeletalHierarchyRequestBus.h new file mode 100644 index 0000000000..b24ac2709b --- /dev/null +++ b/Gems/LmbrCentral/Code/include/LmbrCentral/Animation/SkeletalHierarchyRequestBus.h @@ -0,0 +1,54 @@ +/* +* 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 + +namespace LmbrCentral +{ + /*! + * SkeletonHierarchyRequestBus + * Messages serviced by components to provide information about skeletal hierarchies. + */ + class SkeletalHierarchyRequests + : public AZ::ComponentBus + { + public: + + /** + * \return Number of joints in the skeleton joint hierarchy. + */ + virtual AZ::u32 GetJointCount() { return 0; } + + /** + * \param jointIndex Index of joint whose name should be returned. + * \return Name of the joint at the specified index. Null if joint index is not valid. + */ + virtual const char* GetJointNameByIndex(AZ::u32 /*jointIndex*/) { return nullptr; } + + /** + * \param jointName Name of joint whose index should be returned. + * \return Index of the joint with the specified name. -1 if the joint was not found. + */ + virtual AZ::s32 GetJointIndexByName(const char* /*jointName*/) { return 0; } + + /** + * \param jointIndex Index of joint whose local-space transform should be returned. + * \return Joint's character-space transform. Identify if joint index was not valid. + */ + virtual AZ::Transform GetJointTransformCharacterRelative(AZ::u32 /*jointIndex*/) { return AZ::Transform::CreateIdentity(); } + }; + + using SkeletalHierarchyRequestBus = AZ::EBus; + +} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/EditorMeshBus.h b/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/EditorMeshBus.h deleted file mode 100644 index 19cad8cd29..0000000000 --- a/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/EditorMeshBus.h +++ /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 - -#include - -namespace LmbrCentral -{ - class EditorMeshBusRequests : - public AZ::EBusTraits - { - public: - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - - virtual bool AddMeshComponentWithAssetId(const AZ::EntityId& targetEntity, const AZ::Uuid& meshAssetId) = 0; - }; - using EditorMeshBus = AZ::EBus; -} diff --git a/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/MeshComponentBus.h b/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/MeshComponentBus.h deleted file mode 100644 index 2f64bb084a..0000000000 --- a/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/MeshComponentBus.h +++ /dev/null @@ -1,164 +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 - -struct IStatObj; -struct SRenderingPassInfo; -struct SRendParams; - -namespace LmbrCentral -{ - /*! - * MeshComponentRequestBus - * Messages serviced by the mesh component. - */ - class MeshComponentRequests - : public AZ::ComponentBus - { - public: - - /** - * Returns the axis aligned bounding box in world coordinates - */ - virtual AZ::Aabb GetWorldBounds() = 0; - - /** - * Returns the axis aligned bounding box in model coordinates - */ - virtual AZ::Aabb GetLocalBounds() = 0; - - /** - * Sets the mesh asset for this component - */ - virtual void SetMeshAsset(const AZ::Data::AssetId& id) = 0; - - /** - * Returns the asset used by the mesh - */ - virtual AZ::Data::Asset GetMeshAsset() = 0; - - /** - * Returns true if the mesh is currently visible - */ - virtual bool GetVisibility() { return true; } - - /** - * Sets the current visibility of the mesh - */ - virtual void SetVisibility([[maybe_unused]] bool isVisible) {} - }; - - using MeshComponentRequestBus = AZ::EBus; - - /*! - * SkeletonHierarchyRequestBus - * Messages serviced by components to provide information about skeletal hierarchies. - */ - class SkeletalHierarchyRequests - : public AZ::ComponentBus - { - public: - - /** - * \return Number of joints in the skeleton joint hierarchy. - */ - virtual AZ::u32 GetJointCount() { return 0; } - - /** - * \param jointIndex Index of joint whose name should be returned. - * \return Name of the joint at the specified index. Null if joint index is not valid. - */ - virtual const char* GetJointNameByIndex(AZ::u32 /*jointIndex*/) { return nullptr; } - - /** - * \param jointName Name of joint whose index should be returned. - * \return Index of the joint with the specified name. -1 if the joint was not found. - */ - virtual AZ::s32 GetJointIndexByName(const char* /*jointName*/) { return 0; } - - /** - * \param jointIndex Index of joint whose local-space transform should be returned. - * \return Joint's character-space transform. Identify if joint index was not valid. - */ - virtual AZ::Transform GetJointTransformCharacterRelative(AZ::u32 /*jointIndex*/) { return AZ::Transform::CreateIdentity(); } - }; - - using SkeletalHierarchyRequestBus = AZ::EBus; - - /*! - * LegacyMeshComponentRequestBus - * Messages serviced by the mesh component. - */ - class LegacyMeshComponentRequests - : public AZ::ComponentBus - { - public: - virtual IStatObj* GetStatObj() = 0; - }; - - using LegacyMeshComponentRequestBus = AZ::EBus; - - /*! - * MeshComponentNotificationBus - * Events dispatched by the mesh component. - */ - class MeshComponentNotifications - : public AZ::ComponentBus - { - public: - - /** - * Notifies listeners the mesh instance has been created. - * \param asset - The asset the mesh instance is based on. - */ - virtual void OnMeshCreated(const AZ::Data::Asset& asset) { (void)asset; } - - /** - * Notifies listeners that the mesh instance has been destroyed. - */ - virtual void OnMeshDestroyed() {} - - virtual void OnBoundsReset() {}; - - /* - * Notifies listeners prior to making the render call - */ - virtual void OnMeshPreRender([[maybe_unused]] const struct SRendParams& inOutRenderParams, [[maybe_unused]] const SRenderingPassInfo& passInfo) {}; - - /** - * When connecting to this bus if the asset is ready you will immediately get an OnMeshCreated event - **/ - template - struct ConnectionPolicy - : public AZ::EBusConnectionPolicy - { - static void Connect(typename Bus::BusPtr& busPtr, typename Bus::Context& context, typename Bus::HandlerNode& handler, typename Bus::Context::ConnectLockGuard& connectLock, const typename Bus::BusIdType& id = 0) - { - AZ::EBusConnectionPolicy::Connect(busPtr, context, handler, connectLock, id); - - AZ::Data::Asset asset; - EBUS_EVENT_ID_RESULT(asset, id, MeshComponentRequestBus, GetMeshAsset); - if (asset.GetStatus() == AZ::Data::AssetData::AssetStatus::Ready) - { - handler->OnMeshCreated(asset); - } - } - }; - }; - - using MeshComponentNotificationBus = AZ::EBus; -} // namespace LmbrCentral diff --git a/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/Utils/MaterialOwnerRequestBusHandlerImpl.h b/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/Utils/MaterialOwnerRequestBusHandlerImpl.h index 2779f68eb4..6fc0e85553 100644 --- a/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/Utils/MaterialOwnerRequestBusHandlerImpl.h +++ b/Gems/LmbrCentral/Code/include/LmbrCentral/Rendering/Utils/MaterialOwnerRequestBusHandlerImpl.h @@ -12,7 +12,6 @@ #pragma once #include -#include #include #include @@ -28,8 +27,7 @@ namespace LmbrCentral //! This does not actually inherit the MaterialOwnerRequestBus::Handler interface because it is //! not intended to subscribe to that bus, but it does provide implementations for all the same functions. class MaterialOwnerRequestBusHandlerImpl - : public MeshComponentNotificationBus::Handler - , public AZ::TickBus::Handler + : public AZ::TickBus::Handler , public MaterialOwnerRequestBus::Handler { using MaterialPtr = _smart_ptr < IMaterial >; @@ -57,14 +55,7 @@ namespace LmbrCentral if (m_renderNode) { - if (!m_renderNode->IsReady()) - { - // Some material owners, in particular MeshComponents, may not be ready upon activation because the - // actual mesh data and default material haven't been loaded yet. Until the RenderNode is ready, - // it's material probably isn't valid. - MeshComponentNotificationBus::Handler::BusConnect(entityId); - } - else + if (m_renderNode->IsReady()) { // For some material owner types (like DecalComponent), the material is ready immediately. But we can't // send the event yet because components are still being Activated, so we delay until the first tick. @@ -81,7 +72,6 @@ namespace LmbrCentral void Deactivate() { m_notificationBus = nullptr; - MeshComponentNotificationBus::Handler::BusDisconnect(); MaterialOwnerRequestBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); } @@ -300,16 +290,6 @@ namespace LmbrCentral } ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// - // MeshComponentNotificationBus interface implementation - void OnMeshCreated([[maybe_unused]] const AZ::Data::Asset& asset) override - { - AZ_Assert(IsMaterialOwnerReady(), "Got OnMeshCreated but the RenderNode still isn't ready"); - SendReadyEvent(); - MeshComponentNotificationBus::Handler::BusDisconnect(); - } - ////////////////////////////////////////////////////////////////////////// - ////////////////////////////////////////////////////////////////////////// // TickBus interface implementation void OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) override diff --git a/Gems/LmbrCentral/Code/lmbrcentral_editor_files.cmake b/Gems/LmbrCentral/Code/lmbrcentral_editor_files.cmake index 8d9e70478a..be62919093 100644 --- a/Gems/LmbrCentral/Code/lmbrcentral_editor_files.cmake +++ b/Gems/LmbrCentral/Code/lmbrcentral_editor_files.cmake @@ -12,14 +12,11 @@ set(FILES include/LmbrCentral/Rendering/EditorCameraCorrectionBus.h include/LmbrCentral/Rendering/EditorLightComponentBus.h - include/LmbrCentral/Rendering/EditorMeshBus.h include/LmbrCentral/Shape/EditorPolygonPrismShapeComponentBus.h include/LmbrCentral/Shape/EditorSplineComponentBus.h include/LmbrCentral/Shape/EditorTubeShapeComponentBus.h include/LmbrCentral/Component/EditorWrappedComponentBase.h include/LmbrCentral/Component/EditorWrappedComponentBase.inl - Source/Animation/EditorAttachmentComponent.h - Source/Animation/EditorAttachmentComponent.cpp Source/Audio/EditorAudioAreaEnvironmentComponent.h Source/Audio/EditorAudioAreaEnvironmentComponent.cpp Source/Audio/EditorAudioEnvironmentComponent.h @@ -40,8 +37,6 @@ set(FILES Source/Builders/BenchmarkAssetBuilder/BenchmarkAssetBuilderComponent.cpp Source/Builders/BenchmarkAssetBuilder/BenchmarkAssetBuilderWorker.h Source/Builders/BenchmarkAssetBuilder/BenchmarkAssetBuilderWorker.cpp - Source/Rendering/EditorMeshComponent.h - Source/Rendering/EditorMeshComponent.cpp Source/Scripting/EditorLookAtComponent.h Source/Scripting/EditorLookAtComponent.cpp Source/Scripting/EditorRandomTimedSpawnerComponent.cpp diff --git a/Gems/LmbrCentral/Code/lmbrcentral_editor_tests_files.cmake b/Gems/LmbrCentral/Code/lmbrcentral_editor_tests_files.cmake index a96f0ac4ab..b78ff769c2 100644 --- a/Gems/LmbrCentral/Code/lmbrcentral_editor_tests_files.cmake +++ b/Gems/LmbrCentral/Code/lmbrcentral_editor_tests_files.cmake @@ -19,7 +19,6 @@ set(FILES Tests/EditorCompoundShapeComponentTests.cpp Tests/EditorCylinderShapeComponentTests.cpp Tests/EditorPolygonPrismShapeComponentTests.cpp - Tests/EditorMeshComponentTests.cpp Tests/SpawnerComponentTest.cpp Tests/Builders/CopyDependencyBuilderTest.cpp Tests/Builders/SliceBuilderTests.cpp diff --git a/Gems/LmbrCentral/Code/lmbrcentral_files.cmake b/Gems/LmbrCentral/Code/lmbrcentral_files.cmake index 99d1adda14..df6bafd499 100644 --- a/Gems/LmbrCentral/Code/lmbrcentral_files.cmake +++ b/Gems/LmbrCentral/Code/lmbrcentral_files.cmake @@ -17,6 +17,7 @@ set(FILES include/LmbrCentral/Ai/NavigationSystemBus.h include/LmbrCentral/Ai/NavigationSeedBus.h include/LmbrCentral/Animation/AttachmentComponentBus.h + include/LmbrCentral/Animation/SkeletalHierarchyRequestBus.h include/LmbrCentral/Audio/AudioEnvironmentComponentBus.h include/LmbrCentral/Audio/AudioListenerComponentBus.h include/LmbrCentral/Audio/AudioMultiPositionComponentBus.h @@ -40,7 +41,6 @@ set(FILES include/LmbrCentral/Rendering/MaterialHandle.h include/LmbrCentral/Rendering/MaterialOwnerBus.h include/LmbrCentral/Rendering/MeshAsset.h - include/LmbrCentral/Rendering/MeshComponentBus.h include/LmbrCentral/Rendering/MeshModificationBus.h include/LmbrCentral/Rendering/RenderNodeBus.h include/LmbrCentral/Rendering/GiRegistrationBus.h @@ -69,8 +69,6 @@ set(FILES include/LmbrCentral/Terrain/TerrainSystemRequestBus.h Source/Ai/NavigationSystemComponent.h Source/Ai/NavigationSystemComponent.cpp - Source/Animation/AttachmentComponent.h - Source/Animation/AttachmentComponent.cpp Source/Audio/AudioAreaEnvironmentComponent.h Source/Audio/AudioAreaEnvironmentComponent.cpp Source/Audio/AudioEnvironmentComponent.h @@ -99,11 +97,6 @@ set(FILES Source/Events/ReflectScriptableEvents.cpp Source/Geometry/GeometrySystemComponent.h Source/Geometry/GeometrySystemComponent.cpp - Source/Rendering/MaterialHandle.cpp - Source/Rendering/MeshAssetHandler.h - Source/Rendering/MeshAssetHandler.cpp - Source/Rendering/MeshComponent.h - Source/Rendering/MeshComponent.cpp Source/Rendering/EntityDebugDisplayComponent.h Source/Rendering/EntityDebugDisplayComponent.cpp Source/Scripting/LookAtComponent.h diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp index e1ea3addec..2dc8fc97ec 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.cpp +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.cpp @@ -345,7 +345,6 @@ namespace PhysX AzToolsFramework::BoxManipulatorRequestBus::Handler::BusConnect( AZ::EntityComponentIdPair(GetEntityId(), GetId())); ColliderShapeRequestBus::Handler::BusConnect(GetEntityId()); - LmbrCentral::MeshComponentNotificationBus::Handler::BusConnect(GetEntityId()); AZ::Render::MeshComponentNotificationBus::Handler::BusConnect(GetEntityId()); EditorColliderComponentRequestBus::Handler::BusConnect(AZ::EntityComponentIdPair(GetEntityId(), GetId())); m_nonUniformScaleChangedHandler = AZ::NonUniformScaleChangedEvent::Handler( @@ -394,7 +393,6 @@ namespace PhysX m_nonUniformScaleChangedHandler.Disconnect(); EditorColliderComponentRequestBus::Handler::BusDisconnect(); AZ::Render::MeshComponentNotificationBus::Handler::BusDisconnect(); - LmbrCentral::MeshComponentNotificationBus::Handler::BusDisconnect(); ColliderShapeRequestBus::Handler::BusDisconnect(); AzToolsFramework::BoxManipulatorRequestBus::Handler::BusDisconnect(); AZ::TransformNotificationBus::Handler::BusDisconnect(); @@ -1179,17 +1177,7 @@ namespace PhysX AZ::Render::MeshComponentRequestBus::EventResult(atomMeshAsset, GetEntityId(), &AZ::Render::MeshComponentRequestBus::Events::GetModelAsset); - if (atomMeshAsset.GetId().IsValid()) - { - return atomMeshAsset; - } - - // Try legacy render MeshComponent - AZ::Data::Asset legacyMeshAsset; - LmbrCentral::MeshComponentRequestBus::EventResult(legacyMeshAsset, - GetEntityId(), &LmbrCentral::MeshComponentRequests::GetMeshAsset); - - return legacyMeshAsset; + return atomMeshAsset; } void EditorColliderComponent::SetCollisionMeshFromRender() @@ -1264,14 +1252,6 @@ namespace PhysX renderMeshAsset.GetHint().c_str()); } } - - void EditorColliderComponent::OnMeshCreated([[maybe_unused]] const AZ::Data::Asset& asset) - { - if (ShouldUpdateCollisionMeshFromRender()) - { - SetCollisionMeshFromRender(); - } - } void EditorColliderComponent::OnModelReady([[maybe_unused]] const AZ::Data::Asset& modelAsset, [[maybe_unused]] const AZ::Data::Instance& model) diff --git a/Gems/PhysX/Code/Source/EditorColliderComponent.h b/Gems/PhysX/Code/Source/EditorColliderComponent.h index f179525802..e78be1b959 100644 --- a/Gems/PhysX/Code/Source/EditorColliderComponent.h +++ b/Gems/PhysX/Code/Source/EditorColliderComponent.h @@ -32,8 +32,6 @@ #include #include -#include - #include #include #include @@ -105,7 +103,6 @@ namespace PhysX , private PhysX::MeshColliderComponentRequestsBus::Handler , private AZ::TransformNotificationBus::Handler , private PhysX::ColliderShapeRequestBus::Handler - , private LmbrCentral::MeshComponentNotificationBus::Handler , private AZ::Render::MeshComponentNotificationBus::Handler , private PhysX::EditorColliderComponentRequestBus::Handler , private Physics::WorldBodyRequestBus::Handler @@ -175,9 +172,6 @@ namespace PhysX AZ::Transform GetCurrentTransform() override; AZ::Vector3 GetBoxScale() override; - // LmbrCentral::MeshComponentNotificationBus - void OnMeshCreated(const AZ::Data::Asset& asset) override; - // AZ::Render::MeshComponentNotificationBus void OnModelReady(const AZ::Data::Asset& modelAsset, const AZ::Data::Instance& model) override; From 6eddf39effc6c6160bfe9f90bb7154aa4a2fcb7f Mon Sep 17 00:00:00 2001 From: jonbeer Date: Mon, 3 May 2021 15:27:26 -0700 Subject: [PATCH 052/185] Adding additional PhysX tests for work with Prefabs --- .../Physics/ShapeConfiguration.cpp | 18 +++ Gems/PhysX/Code/CMakeLists.txt | 1 + .../Code/Tests/PhysXColliderPrefabTests.cpp | 126 ++++++++++++++++++ Gems/PhysX/Code/physx_tests_files.cmake | 1 + 4 files changed, 146 insertions(+) create mode 100644 Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp diff --git a/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp b/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp index f01e42a443..617fd026b6 100644 --- a/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp +++ b/Code/Framework/AzFramework/AzFramework/Physics/ShapeConfiguration.cpp @@ -32,6 +32,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("Radius", &SphereShapeConfiguration::m_radius) @@ -60,6 +63,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("Configuration", &BoxShapeConfiguration::m_dimensions) @@ -88,6 +94,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("Height", &CapsuleShapeConfiguration::m_height) @@ -137,6 +146,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("PhysicsAsset", &PhysicsAssetShapeConfiguration::m_asset) @@ -169,6 +181,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("Scale", &NativeShapeConfiguration::m_nativeShapeScale) @@ -192,6 +207,9 @@ namespace Physics { if (auto serializeContext = azrtti_cast(context)) { + serializeContext + ->RegisterGenericType>(); + serializeContext->Class() ->Version(1) ->Field("CookedData", &CookedMeshShapeConfiguration::m_cookedData) diff --git a/Gems/PhysX/Code/CMakeLists.txt b/Gems/PhysX/Code/CMakeLists.txt index ac5fd902c2..65fafcf88b 100644 --- a/Gems/PhysX/Code/CMakeLists.txt +++ b/Gems/PhysX/Code/CMakeLists.txt @@ -45,6 +45,7 @@ ly_add_target( ${physx_dependency} AZ::AzCore AZ::AzFramework + AZ::AzToolsFramework Legacy::CryCommon Gem::LmbrCentral ) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp new file mode 100644 index 0000000000..d489ac2990 --- /dev/null +++ b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp @@ -0,0 +1,126 @@ +/* +* 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 + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + + +namespace PhysX +{ + class PhysXColliderPrefabTest + : public ::testing::Test + { + protected: + void SetUp() override + { + + } + + void TearDown() override + { + + } + + + }; + + TEST_F(PhysXColliderPrefabTest, JsonStoreAndLoadPhysicsObjectsWithPrefabTest) + { + AzToolsFramework::Prefab::PrefabDom prefabDom; + + //material selection + Physics::MaterialSelection materialSelection; + AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), materialSelection); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Material Selection", prefabDom); + + Physics::MaterialSelection newSelection; + AZ::JsonSerialization::Load(newSelection, prefabDom); + + EXPECT_EQ(materialSelection.GetMaterialId(), newSelection.GetMaterialId()); + + //collider configuration + Physics::ColliderConfiguration colliderConfig; + AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfig); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + + Physics::ColliderConfiguration newConfig; + AZ::JsonSerialization::Load(newConfig, prefabDom); + + EXPECT_EQ(colliderConfig.m_collisionLayer, newConfig.m_collisionLayer); + + //shared pointer - collider configuration - defaults only + auto colliderConfigPtr = AZStd::make_shared(); + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfigPtr); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + + colliderConfigPtr = nullptr; + AZ::JsonSerialization::Load(colliderConfigPtr, prefabDom); + + EXPECT_NE(nullptr, colliderConfigPtr); + + //shared pointer - collider configuration - non default + auto updatedColliderConfigPtr = AZStd::make_shared(); + updatedColliderConfigPtr->m_isTrigger = true; + AZ::JsonSerializationResult::ResultCode result2 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedColliderConfigPtr); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + + updatedColliderConfigPtr = nullptr; + AZ::JsonSerialization::Load(updatedColliderConfigPtr, prefabDom); + + EXPECT_NE(nullptr, updatedColliderConfigPtr); + + //shared pointer - shape configuration - defaults only + auto shapeConfigPtr = AZStd::make_shared(); + AZ::JsonSerializationResult::ResultCode result3 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeConfigPtr); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Shape Configuration", prefabDom); + + shapeConfigPtr = nullptr; + AZ::JsonSerialization::Load(shapeConfigPtr, prefabDom); + + EXPECT_NE(nullptr, shapeConfigPtr); + + //shared pointer - shape configuration - non default + auto updatedShapeConfigPtr = AZStd::make_shared(); + updatedShapeConfigPtr->m_radius = 2.0f; + AZ::JsonSerializationResult::ResultCode result4 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedShapeConfigPtr); + + AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Shape Configuration", prefabDom); + + updatedShapeConfigPtr = nullptr; + AZ::JsonSerialization::Load(updatedShapeConfigPtr, prefabDom); + + EXPECT_NE(nullptr, updatedColliderConfigPtr); + } +} diff --git a/Gems/PhysX/Code/physx_tests_files.cmake b/Gems/PhysX/Code/physx_tests_files.cmake index 406aed64a7..182ff6a625 100644 --- a/Gems/PhysX/Code/physx_tests_files.cmake +++ b/Gems/PhysX/Code/physx_tests_files.cmake @@ -25,6 +25,7 @@ set(FILES Tests/PhysXForceRegionTest.cpp Tests/PhysXMaterialLibraryTest.cpp Tests/PhysXCollisionFilteringTest.cpp + Tests/PhysXColliderPrefabTests.cpp Tests/PhysXJointsTest.cpp Tests/PhysXSceneTests.cpp Tests/PhysXSceneQueryTests.cpp From 7f81602fe7189cc2f84ae73750eaf0eaeae656c2 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 3 May 2021 15:43:42 -0700 Subject: [PATCH 053/185] Use the material id from the base mesh when optimizing blend shapes (#517) This is cherry-picked from #311 When processing meshes with blend shapes, the mesh optimizer disables the optimize duplicates setting, to prevent potential vertex reodering that could cause the base mesh vertices to become out of sync with the blend shape. However, it will still reorder vertices based on their material. It places all triangles that use the same material in the same submesh, grouping them together in the resulting mesh. The SceneAPI does not track material ids for blend shapes. To ensure that the blend shape triangles are reordered in the same way as the base shape, this change makes the blend shape optimization use the material id from the base shape. --- .../MeshOptimizer/MeshOptimizerComponent.cpp | 16 ++++------------ .../MeshOptimizer/MeshOptimizerComponent.h | 4 +--- 2 files changed, 5 insertions(+), 15 deletions(-) diff --git a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp index 8be67fe89b..592a8e2a75 100644 --- a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp +++ b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.cpp @@ -290,7 +290,7 @@ namespace AZ::SceneGenerationComponents const bool hasBlendShapes = HasAnyBlendShapeChild(graph, nodeIndex); - auto [optimizedMesh, optimizedUVs, optimizedTangents, optimizedBitangents, optimizedVertexColors, optimizedSkinWeights] = OptimizeMesh(mesh, uvDatas, tangentDatas, bitangentDatas, colorDatas, skinWeightDatas, meshGroup, hasBlendShapes); + auto [optimizedMesh, optimizedUVs, optimizedTangents, optimizedBitangents, optimizedVertexColors, optimizedSkinWeights] = OptimizeMesh(mesh, mesh, uvDatas, tangentDatas, bitangentDatas, colorDatas, skinWeightDatas, meshGroup, hasBlendShapes); const NodeIndex optimizedMeshNodeIndex = graph.AddChild(graph.GetNodeParent(nodeIndex), name.c_str(), AZStd::move(optimizedMesh)); @@ -322,7 +322,7 @@ namespace AZ::SceneGenerationComponents for (const NodeIndex& blendShapeNodeIndex : nodeIndexes(Containers::MakeDerivedFilterView(childNodes(nodeIndex)))) { const IBlendShapeData* blendShapeNode = static_cast(graph.GetNodeContent(blendShapeNodeIndex).get()); - auto [optimizedBlendShape, _1, _2, _3 , _4, _5] = OptimizeMesh(blendShapeNode, {}, {}, {}, {}, {}, meshGroup, hasBlendShapes); + auto [optimizedBlendShape, _1, _2, _3 , _4, _5] = OptimizeMesh(blendShapeNode, mesh, {}, {}, {}, {}, {}, meshGroup, hasBlendShapes); const AZStd::string optimizedName {graph.GetNodeName(blendShapeNodeIndex).GetName(), graph.GetNodeName(blendShapeNodeIndex).GetNameLength()}; const NodeIndex optimizedNodeIndex = graph.AddChild(optimizedMeshNodeIndex, optimizedName.c_str(), AZStd::move(optimizedBlendShape)); @@ -383,6 +383,7 @@ namespace AZ::SceneGenerationComponents AZStd::unique_ptr > MeshOptimizerComponent::OptimizeMesh( const MeshDataType* meshData, + const IMeshData* baseMesh, const AZStd::vector>& uvs, const AZStd::vector>& tangents, const AZStd::vector>& bitangents, @@ -441,7 +442,7 @@ namespace AZ::SceneGenerationComponents const AZ::u32 faceCount = meshData->GetFaceCount(); for (AZ::u32 faceIndex = 0; faceIndex < faceCount; ++faceIndex) { - meshBuilder.BeginPolygon(GetFaceMaterialId(meshData, faceIndex)); + meshBuilder.BeginPolygon(baseMesh->GetFaceMaterialId(faceIndex)); for (const AZ::u32 vertexIndex : meshData->GetFaceInfo(faceIndex).vertexIndex) { const int orgVertexNumber = meshData->GetUsedPointIndexForControlPoint(meshData->GetControlPointIndex(vertexIndex)); @@ -584,15 +585,6 @@ namespace AZ::SceneGenerationComponents ); } - unsigned int MeshOptimizerComponent::GetFaceMaterialId([[maybe_unused]] const AZ::SceneAPI::DataTypes::IBlendShapeData* meshData, [[maybe_unused]] unsigned int index) - { - return 0; - } - unsigned int MeshOptimizerComponent::GetFaceMaterialId(const AZ::SceneAPI::DataTypes::IMeshData* meshData, unsigned int index) - { - return meshData->GetFaceMaterialId(index); - } - void MeshOptimizerComponent::AddFace(AZ::SceneData::GraphData::BlendShapeData* blendShape, unsigned int index1, unsigned int index2, unsigned int index3, [[maybe_unused]] unsigned int faceMaterialId) { blendShape->AddFace({index1, index2, index3}); diff --git a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.h b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.h index ee8fa5afe5..e499f30e2e 100644 --- a/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.h +++ b/Gems/SceneProcessing/Code/Source/Generation/Components/MeshOptimizer/MeshOptimizerComponent.h @@ -66,6 +66,7 @@ namespace AZ::SceneGenerationComponents AZStd::unique_ptr > OptimizeMesh( const MeshDataType* meshData, + const SceneAPI::DataTypes::IMeshData* baseMesh, const AZStd::vector>& uvs, const AZStd::vector>& tangents, const AZStd::vector>& bitangents, @@ -74,9 +75,6 @@ namespace AZ::SceneGenerationComponents const AZ::SceneAPI::DataTypes::IMeshGroup& meshGroup, bool hasBlendShapes); - static unsigned int GetFaceMaterialId(const AZ::SceneAPI::DataTypes::IBlendShapeData* meshData, unsigned int index); - static unsigned int GetFaceMaterialId(const AZ::SceneAPI::DataTypes::IMeshData* meshData, unsigned int index); - static void AddFace(AZ::SceneData::GraphData::BlendShapeData* blendShape, unsigned int index1, unsigned int index2, unsigned int index3, unsigned int faceMaterialId); static void AddFace(AZ::SceneData::GraphData::MeshData* mesh, unsigned int index1, unsigned int index2, unsigned int index3, unsigned int faceMaterialId); }; From 4485edf77d118771e4a051fefb91d009deb7353f Mon Sep 17 00:00:00 2001 From: Eric Phister <52085794+amzn-phist@users.noreply.github.com> Date: Mon, 3 May 2021 17:46:54 -0500 Subject: [PATCH 054/185] LYN-2578: Updates cmake install for 'scripts' directory. (#518) * LYN-2578: Updates cmake install for 'scripts' directory. Updates destination of certain binaries. * LYN-2578: Updates to cmake install based on feedback. --- CMakeLists.txt | 4 ++- cmake/Platform/Common/Install_common.cmake | 38 +++++++++++++++------- 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index cefbcf2ef4..868757ebcd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -75,7 +75,9 @@ foreach(restricted_platform ${PAL_RESTRICTED_PLATFORMS}) endif() endforeach() -add_subdirectory(scripts) +if(NOT INSTALLED_ENGINE) + add_subdirectory(scripts) +endif() # SPEC-1417 will investigate and fix this if(NOT PAL_PLATFORM_NAME STREQUAL "Mac") diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index fb3a7b1b09..8fe2fe2c1c 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -286,7 +286,7 @@ endfunction() function(ly_setup_others) # List of directories we want to install relative to engine root - set(DIRECTORIES_TO_INSTALL Tools/LyTestTools Tools/RemoteConsole scripts) + set(DIRECTORIES_TO_INSTALL Tools/LyTestTools Tools/RemoteConsole) foreach(dir ${DIRECTORIES_TO_INSTALL}) get_filename_component(install_path ${dir} DIRECTORY) @@ -301,6 +301,24 @@ function(ly_setup_others) endforeach() + # Scripts + file(GLOB o3de_scripts "${CMAKE_SOURCE_DIR}/scripts/o3de.*") + install(FILES + ${o3de_scripts} + DESTINATION ./scripts + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + ) + + install(DIRECTORY + ${CMAKE_SOURCE_DIR}/scripts/bundler + ${CMAKE_SOURCE_DIR}/scripts/project_manager + DESTINATION ./scripts + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + PATTERN "__pycache__" EXCLUDE + PATTERN "CMakeLists.txt" EXCLUDE + PATTERN "tests" EXCLUDE + ) + install(DIRECTORY "${CMAKE_SOURCE_DIR}/python" DESTINATION . COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} @@ -311,7 +329,7 @@ function(ly_setup_others) # Registry install(DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin/$/Registry - DESTINATION ./bin/$ + DESTINATION ./bin/${PAL_PLATFORM_NAME}/$ COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} ) install(DIRECTORY @@ -350,16 +368,14 @@ function(ly_setup_others) endif() endforeach() - # Qt Binaries - set(QT_BIN_DIRS bearer iconengines imageformats platforms styles translations) - foreach(qt_dir ${QT_BIN_DIRS}) - install(DIRECTORY - ${CMAKE_CURRENT_BINARY_DIR}/bin/$/${qt_dir} - DESTINATION ./bin/$ - COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} - ) - endforeach() + set(QT_DIRS bearer iconengines imageformats platforms styles translations) + list(TRANSFORM QT_DIRS PREPEND "${CMAKE_CURRENT_BINARY_DIR}/bin/$/" OUTPUT_VARIABLE QT_BIN_DIRS) + install(DIRECTORY + ${QT_BIN_DIRS} + DESTINATION ./bin/${PAL_PLATFORM_NAME}/$ + COMPONENT ${LY_DEFAULT_INSTALL_COMPONENT} + ) # Templates install(DIRECTORY From dfe57c9d8f7a66c127ddcc511f831ed3eca5e47e Mon Sep 17 00:00:00 2001 From: Vincent Liu <5900509+onecent1101@users.noreply.github.com> Date: Mon, 3 May 2021 16:16:19 -0700 Subject: [PATCH 055/185] [LYN-2964][LYN-2965] Improve user experience of using AWSScriptBehaviorS3 (#495) As AWS S3 GetObject doesn't provide proper file handling, move logic into custom request validation step --- .../Public/ScriptCanvas/AWSScriptBehaviorS3.h | 12 +++- .../ScriptCanvas/AWSScriptBehaviorS3.cpp | 58 +++++++++++----- .../ScriptCanvas/AWSScriptBehaviorS3Test.cpp | 67 ++++++++++++++++++- 3 files changed, 119 insertions(+), 18 deletions(-) diff --git a/Gems/AWSCore/Code/Include/Public/ScriptCanvas/AWSScriptBehaviorS3.h b/Gems/AWSCore/Code/Include/Public/ScriptCanvas/AWSScriptBehaviorS3.h index 5d7baf19a1..9d779e3629 100644 --- a/Gems/AWSCore/Code/Include/Public/ScriptCanvas/AWSScriptBehaviorS3.h +++ b/Gems/AWSCore/Code/Include/Public/ScriptCanvas/AWSScriptBehaviorS3.h @@ -75,6 +75,16 @@ namespace AWSCore class AWSScriptBehaviorS3 : public AWSScriptBehaviorBase { + static constexpr const char AWSScriptBehaviorS3Name[] = "AWSScriptBehaviorS3"; + static constexpr const char OutputFileIsEmptyErrorMessage[] = "Request validation failed, output file is empty."; + static constexpr const char OutputFileMissFullPathErrorMessage[] = "Request validation failed, output file miss full path."; + static constexpr const char OutputFileIsDirectoryErrorMessage[] = "Request validation failed, output file is a directory."; + static constexpr const char OutputFileDirectoryNotExistErrorMessage[] = "Request validation failed, output file directory doesn't exist."; + static constexpr const char OutputFileIsReadOnlyErrorMessage[] = "Request validation failed, output file is read-only."; + static constexpr const char BucketNameIsEmptyErrorMessage[] = "Request validation failed, bucket name is empty"; + static constexpr const char ObjectKeyNameIsEmptyErrorMessage[] = "Request validation failed, object key name is empty."; + static constexpr const char RegionNameIsEmptyErrorMessage[] = "Request validation failed, region name is empty."; + public: AWS_SCRIPT_BEHAVIOR_DEFINITION(AWSScriptBehaviorS3, "{7F4E956C-7463-4236-B320-C992D36A9C6E}"); @@ -87,7 +97,7 @@ namespace AWSCore private: using S3NotificationFunctionType = void(AWSScriptBehaviorS3Notifications::*)(const AZStd::string&); static bool ValidateGetObjectRequest(S3NotificationFunctionType notificationFunc, - const AZStd::string& bucket, const AZStd::string& objectKey, const AZStd::string& region, const AZStd::string& outFile); + const AZStd::string& bucket, const AZStd::string& objectKey, const AZStd::string& region, AZStd::string& outFile); static bool ValidateHeadObjectRequest(S3NotificationFunctionType notificationFunc, const AZStd::string& bucket, const AZStd::string& key, const AZStd::string& region); diff --git a/Gems/AWSCore/Code/Source/ScriptCanvas/AWSScriptBehaviorS3.cpp b/Gems/AWSCore/Code/Source/ScriptCanvas/AWSScriptBehaviorS3.cpp index 742a6826af..1f529572f1 100644 --- a/Gems/AWSCore/Code/Source/ScriptCanvas/AWSScriptBehaviorS3.cpp +++ b/Gems/AWSCore/Code/Source/ScriptCanvas/AWSScriptBehaviorS3.cpp @@ -43,7 +43,7 @@ namespace AWSCore void AWSScriptBehaviorS3::ReflectBehaviors(AZ::BehaviorContext* behaviorContext) { - behaviorContext->Class("AWSScriptBehaviorS3") + behaviorContext->Class(AWSScriptBehaviorS3Name) ->Attribute(AZ::Script::Attributes::Category, "AWSCore") ->Method("GetObject", &AWSScriptBehaviorS3::GetObject, {{{"Bucket Resource KeyName", "The resource key name of the bucket in resource mapping config file."}, @@ -86,7 +86,9 @@ namespace AWSCore void AWSScriptBehaviorS3::GetObjectRaw( const AZStd::string& bucket, const AZStd::string& objectKey, const AZStd::string& region, const AZStd::string& outFile) { - if (!ValidateGetObjectRequest(&AWSScriptBehaviorS3NotificationBus::Events::OnGetObjectError, bucket, objectKey, region, outFile)) + AZStd::string normalizedOutFile = outFile; + if (!ValidateGetObjectRequest( + &AWSScriptBehaviorS3NotificationBus::Events::OnGetObjectError, bucket, objectKey, region, normalizedOutFile)) { return; } @@ -112,10 +114,10 @@ namespace AWSCore job->request.SetBucket(Aws::String(bucket.c_str())); job->request.SetKey(Aws::String(objectKey.c_str())); - Aws::String outFileName(outFile.c_str()); + Aws::String outFileName(normalizedOutFile.c_str()); job->request.SetResponseStreamFactory([outFileName]() { return Aws::New( - "AWSScriptBehaviorS3", outFileName.c_str(), + AWSScriptBehaviorS3Name, outFileName.c_str(), std::ios_base::out | std::ios_base::in | std::ios_base::binary | std::ios_base::trunc); }); job->Start(); @@ -163,20 +165,44 @@ namespace AWSCore } bool AWSScriptBehaviorS3::ValidateGetObjectRequest(S3NotificationFunctionType notificationFunc, - const AZStd::string& bucket, const AZStd::string& objectKey, const AZStd::string& region, const AZStd::string& outFile) + const AZStd::string& bucket, const AZStd::string& objectKey, const AZStd::string& region, AZStd::string& outFile) { if (ValidateHeadObjectRequest(notificationFunc, bucket, objectKey, region)) { - if (!AzFramework::StringFunc::Path::IsValid(outFile.c_str())) + AzFramework::StringFunc::Path::Normalize(outFile); + if (outFile.empty()) { - AZ_Warning("AWSScriptBehaviorS3", false, "Request validation failed, outfile is not valid."); - AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, "Request validation failed, outfile is not valid."); + AZ_Warning(AWSScriptBehaviorS3Name, false, OutputFileIsEmptyErrorMessage); + AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, OutputFileIsEmptyErrorMessage); return false; } + if (!AzFramework::StringFunc::Path::HasDrive(outFile.c_str())) + { + AZ_Warning(AWSScriptBehaviorS3Name, false, OutputFileMissFullPathErrorMessage); + AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, OutputFileMissFullPathErrorMessage); + return false; + } + if (AZ::IO::FileIOBase::GetInstance()->IsDirectory(outFile.c_str())) + { + AZ_Warning(AWSScriptBehaviorS3Name, false, OutputFileIsDirectoryErrorMessage); + AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, OutputFileIsDirectoryErrorMessage); + return false; + } + auto lastSeparator = outFile.find_last_of(AZ_CORRECT_FILESYSTEM_SEPARATOR); + if (lastSeparator != AZStd::string::npos) + { + auto parentPath = outFile.substr(0, lastSeparator); + if (!AZ::IO::FileIOBase::GetInstance()->Exists(parentPath.c_str())) + { + AZ_Warning(AWSScriptBehaviorS3Name, false, OutputFileDirectoryNotExistErrorMessage); + AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, OutputFileDirectoryNotExistErrorMessage); + return false; + } + } if (AZ::IO::FileIOBase::GetInstance()->IsReadOnly(outFile.c_str())) { - AZ_Warning("AWSScriptBehaviorS3", false, "Request validation failed, outfile is read-only."); - AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, "Request validation failed, outfile is read-only."); + AZ_Warning(AWSScriptBehaviorS3Name, false, OutputFileIsReadOnlyErrorMessage); + AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, OutputFileIsReadOnlyErrorMessage); return false; } return true; @@ -189,20 +215,20 @@ namespace AWSCore { if (bucket.empty()) { - AZ_Warning("AWSScriptBehaviorS3", false, "Request validation failed, bucket name is required."); - AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, "Request validation failed, bucket name is required."); + AZ_Warning(AWSScriptBehaviorS3Name, false, BucketNameIsEmptyErrorMessage); + AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, BucketNameIsEmptyErrorMessage); return false; } if (objectKey.empty()) { - AZ_Warning("AWSScriptBehaviorS3", false, "Request validation failed, object key name is required."); - AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, "Request validation failed, object key name is required."); + AZ_Warning(AWSScriptBehaviorS3Name, false, ObjectKeyNameIsEmptyErrorMessage); + AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, ObjectKeyNameIsEmptyErrorMessage); return false; } if (region.empty()) { - AZ_Warning("AWSScriptBehaviorS3", false, "Request validation failed, region name is required."); - AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, "Request validation failed, region name is required."); + AZ_Warning(AWSScriptBehaviorS3Name, false, RegionNameIsEmptyErrorMessage); + AWSScriptBehaviorS3NotificationBus::Broadcast(notificationFunc, RegionNameIsEmptyErrorMessage); return false; } return true; diff --git a/Gems/AWSCore/Code/Tests/ScriptCanvas/AWSScriptBehaviorS3Test.cpp b/Gems/AWSCore/Code/Tests/ScriptCanvas/AWSScriptBehaviorS3Test.cpp index fe258580e0..3489f09ac3 100644 --- a/Gems/AWSCore/Code/Tests/ScriptCanvas/AWSScriptBehaviorS3Test.cpp +++ b/Gems/AWSCore/Code/Tests/ScriptCanvas/AWSScriptBehaviorS3Test.cpp @@ -11,6 +11,7 @@ */ #include +#include #include #include @@ -38,7 +39,37 @@ public: MOCK_METHOD1(OnGetObjectError, void(const AZStd::string&)); }; -using AWSScriptBehaviorS3Test = UnitTest::ScopedAllocatorSetupFixture; +class AWSScriptBehaviorS3Test + : public AWSCoreFixture +{ +public: + void CreateReadOnlyTestFile(const AZStd::string& filePath) + { + AZ::IO::SystemFile file; + if (!file.Open( + filePath.c_str(), + AZ::IO::SystemFile::OpenMode::SF_OPEN_CREATE | AZ::IO::SystemFile::SF_OPEN_CREATE_PATH | AZ::IO::SystemFile::SF_OPEN_WRITE_ONLY)) + { + AZ_Assert(false, "Failed to open test file at %s", filePath.c_str()); + } + AZStd::string testContent = "It is a test file"; + if (file.Write(testContent.c_str(), testContent.size()) != testContent.size()) + { + AZ_Assert(false, "Failed to write test file with content %s", testContent.c_str()); + } + file.Close(); + AZ_Assert(AZ::IO::SystemFile::SetWritable(filePath.c_str(), false), "Failed to mark test file as read-only"); + } + + void RemoveReadOnlyTestFile(const AZStd::string& filePath) + { + if (!filePath.empty()) + { + AZ_Assert(AZ::IO::SystemFile::SetWritable(filePath.c_str(), true), "Failed to mark test file as writeable"); + AZ_Assert(AZ::IO::SystemFile::Delete(filePath.c_str()), "Failed to delete test config file at %s", filePath.c_str()); + } + } +}; TEST_F(AWSScriptBehaviorS3Test, HeadObjectRaw_CallWithEmptyBucketName_InvokeOnError) { @@ -96,6 +127,40 @@ TEST_F(AWSScriptBehaviorS3Test, GetObjectRaw_CallWithEmptyOutfileName_InvokeOnEr AWSScriptBehaviorS3::GetObjectRaw("dummyBucket", "dummyObject", "dummyRegion", ""); } +TEST_F(AWSScriptBehaviorS3Test, GetObjectRaw_CallWithOutfileNameMissFullPath_InvokeOnError) +{ + AWSScriptBehaviorS3NotificationBusHandlerMock s3HandlerMock; + EXPECT_CALL(s3HandlerMock, OnGetObjectError(::testing::_)).Times(1); + AWSScriptBehaviorS3::GetObjectRaw("dummyBucket", "dummyObject", "dummyRegion", "dummyOut.txt"); +} + +TEST_F(AWSScriptBehaviorS3Test, GetObjectRaw_CallWithOutfileNameIsDirectory_InvokeOnError) +{ + AWSScriptBehaviorS3NotificationBusHandlerMock s3HandlerMock; + EXPECT_CALL(s3HandlerMock, OnGetObjectError(::testing::_)).Times(1); + AWSScriptBehaviorS3::GetObjectRaw("dummyBucket", "dummyObject", "dummyRegion", AZ::Test::GetCurrentExecutablePath()); +} + +TEST_F(AWSScriptBehaviorS3Test, GetObjectRaw_CallWithOutfileDirectoryNoExist_InvokeOnError) +{ + AWSScriptBehaviorS3NotificationBusHandlerMock s3HandlerMock; + EXPECT_CALL(s3HandlerMock, OnGetObjectError(::testing::_)).Times(1); + AZStd::string dummyDirectory = AZStd::string::format("%s/dummyDirectory/dummyOut.txt", AZ::Test::GetCurrentExecutablePath().c_str()); + AWSScriptBehaviorS3::GetObjectRaw("dummyBucket", "dummyObject", "dummyRegion", dummyDirectory); +} + +TEST_F(AWSScriptBehaviorS3Test, GetObjectRaw_CallWithOutfileIsReadOnly_InvokeOnError) +{ + AWSScriptBehaviorS3NotificationBusHandlerMock s3HandlerMock; + EXPECT_CALL(s3HandlerMock, OnGetObjectError(::testing::_)).Times(1); + AZStd::string randomTestFile = AZStd::string::format("%s/test%s.txt", + AZ::Test::GetCurrentExecutablePath().c_str(), AZ::Uuid::CreateRandom().ToString(false, false).c_str()); + AzFramework::StringFunc::Path::Normalize(randomTestFile); + CreateReadOnlyTestFile(randomTestFile); + AWSScriptBehaviorS3::GetObjectRaw("dummyBucket", "dummyObject", "dummyRegion", randomTestFile); + RemoveReadOnlyTestFile(randomTestFile); +} + TEST_F(AWSScriptBehaviorS3Test, GetObject_NoBucketNameInResourceMappingFound_InvokeOnError) { AWSScriptBehaviorS3NotificationBusHandlerMock s3HandlerMock; From 73dca7e9e2e3d806f0b48355343df6a68a7e4e1f Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 3 May 2021 10:07:44 -0700 Subject: [PATCH 056/185] Fix Editor crash when slices are deleted with prefabs enabled --- .../ComponentEntityEditorPlugin/SandboxIntegration.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index ecfb155d79..7a418a1f2e 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -302,17 +302,20 @@ void SandboxIntegrationManager::OnCatalogAssetAdded(const AZ::Data::AssetId& ass // operation writing to shared resource is queued on main thread. void SandboxIntegrationManager::OnCatalogAssetRemoved(const AZ::Data::AssetId& assetId, const AZ::Data::AssetInfo& assetInfo) { + bool isPrefabSystemEnabled = false; + AzFramework::ApplicationRequests::Bus::BroadcastResult(isPrefabSystemEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled); + // Check to see if the removed slice asset has any instance in the level, then check if // those dangling instances are directly under the root slice (not sub-slices). If yes, // detach them and save necessary information so they can be restored when their slice asset // comes back. - if (assetInfo.m_assetType == AZ::AzTypeInfo::Uuid()) + if (!isPrefabSystemEnabled && assetInfo.m_assetType == AZ::AzTypeInfo::Uuid()) { AZ::SliceComponent* rootSlice = nullptr; AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::BroadcastResult(rootSlice, &AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::Events::GetEditorRootSlice); - AZ_Assert(rootSlice, "Editor root slice missing!"); + AZ_Assert(rootSlice != nullptr, "Editor root slice missing!"); AZStd::vector entitiesToDetach; const AZ::SliceComponent::SliceList& subSlices = rootSlice->GetSlices(); From d8145d33e94118527de48a6d2e3b54904cfdd73e Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 3 May 2021 10:13:55 -0700 Subject: [PATCH 057/185] Reverted an assert condition to its previous state --- .../Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index 7a418a1f2e..724664b1dc 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -315,7 +315,7 @@ void SandboxIntegrationManager::OnCatalogAssetRemoved(const AZ::Data::AssetId& a AZ::SliceComponent* rootSlice = nullptr; AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::BroadcastResult(rootSlice, &AzToolsFramework::SliceEditorEntityOwnershipServiceRequestBus::Events::GetEditorRootSlice); - AZ_Assert(rootSlice != nullptr, "Editor root slice missing!"); + AZ_Assert(rootSlice, "Editor root slice missing!"); AZStd::vector entitiesToDetach; const AZ::SliceComponent::SliceList& subSlices = rootSlice->GetSlices(); From a7624bb98587372350549fe15c1c63250b4434ac Mon Sep 17 00:00:00 2001 From: srikappa Date: Mon, 3 May 2021 17:23:00 -0700 Subject: [PATCH 058/185] Removed returning AZ::Failure when AZ::Assert is thrown --- .../Prefab/PrefabPublicHandler.cpp | 57 ++++++------------- .../Prefab/PrefabPublicHandler.h | 3 +- 2 files changed, 17 insertions(+), 43 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp index 1b4bf9f50c..475510c52f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.cpp @@ -96,12 +96,7 @@ namespace AzToolsFramework // target templates of the other instances. for (auto& nestedInstance : instances) { - PrefabOperationResult removeLinkResult = RemoveLink( - nestedInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); - if (!removeLinkResult.IsSuccess()) - { - return removeLinkResult; - } + RemoveLink(nestedInstance, commonRootEntityOwningInstance->get().GetTemplateId(), undoBatch.GetUndoBatch()); } PrefabUndoHelpers::UpdatePrefabInstance( @@ -241,14 +236,9 @@ namespace AzToolsFramework // Retrieve the owning instance of the common root entity, which will be our new instance's parent instance. commonRootEntityOwningInstance = GetOwnerInstanceByEntityId(commonRootEntityId); - if (!commonRootEntityOwningInstance) - { - AZ_Assert( - false, - "Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided"); - return AZ::Failure(AZStd::string( - "Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided")); - } + AZ_Assert( + commonRootEntityOwningInstance.has_value(), + "Failed to create prefab : Couldn't get a valid owning instance for the common root entity of the enities provided"); return AZ::Success(); } @@ -290,47 +280,32 @@ namespace AzToolsFramework m_prefabUndoCache.Store(containerEntityId, AZStd::move(containerEntityDomAfter)); } - PrefabOperationResult PrefabPublicHandler::RemoveLink( + void PrefabPublicHandler::RemoveLink( AZStd::unique_ptr& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch) { LinkReference nestedInstanceLink = m_prefabSystemComponentInterface->FindLink(sourceInstance->GetLinkId()); - if (!nestedInstanceLink.has_value()) - { - AZ_Assert(false, "A valid link was not found for one of the instances provided as input for the CreatePrefab operation."); - return AZ::Failure( - AZStd::string("A valid link was not found for one of the instances provided as input for the CreatePrefab operation.")); - } + AZ_Assert( + nestedInstanceLink.has_value(), + "A valid link was not found for one of the instances provided as input for the CreatePrefab operation."); PrefabDomReference nestedInstanceLinkDom = nestedInstanceLink->get().GetLinkDom(); - if (!nestedInstanceLinkDom.has_value()) - { - AZ_Assert( - false, - "A valid DOM was not found for the link corresponding to one of the instances provided as input for the " - "CreatePrefab operation."); - return AZ::Failure(AZStd::string("A valid DOM was not found for the link corresponding to one of the instances " - "provided as input for the CreatePrefab operation.")); - } + AZ_Assert( + nestedInstanceLinkDom.has_value(), + "A valid DOM was not found for the link corresponding to one of the instances provided as input for the " + "CreatePrefab operation."); PrefabDomValueReference nestedInstanceLinkPatches = PrefabDomUtils::FindPrefabDomValue(nestedInstanceLinkDom->get(), PrefabDomUtils::PatchesName); - if (!nestedInstanceLinkPatches.has_value()) - { - AZ_Assert( - false, - "A valid DOM for patches was not found for the link corresponding to one of the instances provided as input for the " - "CreatePrefab operation."); - return AZ::Failure(AZStd::string("A valid DOM for patcheswas not found for the link corresponding to one of the instances " - "provided as input for the CreatePrefab operation.")); - } + AZ_Assert( + nestedInstanceLinkPatches.has_value(), + "A valid DOM for patches was not found for the link corresponding to one of the instances provided as input for the " + "CreatePrefab operation."); PrefabDom patchesCopyForUndoSupport; patchesCopyForUndoSupport.CopyFrom(nestedInstanceLinkPatches->get(), patchesCopyForUndoSupport.GetAllocator()); PrefabUndoHelpers::RemoveLink( sourceInstance->GetTemplateId(), targetTemplateId, sourceInstance->GetInstanceAlias(), sourceInstance->GetLinkId(), patchesCopyForUndoSupport, undoBatch); - - return AZ::Success(); } PrefabOperationResult PrefabPublicHandler::SavePrefab(AZ::IO::Path filePath) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h index 8d27603e8d..5ade666a40 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Prefab/PrefabPublicHandler.h @@ -88,9 +88,8 @@ namespace AzToolsFramework * \param sourceInstance The instance corresponding to the source template of the link to be removed. * \param targetTemplateId The id of the target template of the link to be removed. * \param undoBatch The undo batch to set as parent for this remove link action. - * \return PrefabOperationResult Indicates whether the removal of link was successful. */ - PrefabOperationResult RemoveLink( + void RemoveLink( AZStd::unique_ptr& sourceInstance, TemplateId targetTemplateId, UndoSystem::URSequencePoint* undoBatch); /** From bcbe1bfef7017358114aed081ccb46b170a5b194 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Mon, 3 May 2021 20:09:37 -0500 Subject: [PATCH 059/185] LYN-2537 AssetBundler updates (#426) * LYN-2537 Updated the AssetBundler code to looks for the AssetSeedList files within the Assets/Engine directory Updated the MissingDependencyScanner GetXMLDependenciesFile functions to use the Assets/Engine directory as well Also fixed the MissingDependencyScanner to properly located dependency xml files within gem directories * Adding back input argument validation for the AssetBundler command options. Also added an application_options settings registry file that contains the list of valid command options for the ComponentApplication * Adding missing end of file newline for applications_options.setreg * Fixed the AssetBundler help output for the bundleSeed command --- .../AssetBundle/AssetBundleComponent.cpp | 29 ++----- .../source/ui/AssetBundlerTabWidget.cpp | 18 ++-- .../AssetBundler/source/ui/SeedTabWidget.cpp | 2 +- .../source/utils/applicationManager.cpp | 83 +++++++++++++++---- .../Tools/AssetBundler/source/utils/utils.cpp | 18 ++-- Code/Tools/AssetBundler/source/utils/utils.h | 15 ---- .../{ => Assets}/Engine/SeedAssetList.seed | 0 Code/Tools/AssetBundler/tests/tests_main.cpp | 15 ++-- .../utilities/MissingDependencyScanner.cpp | 12 +-- .../Code/Source/AssetSeedUtil.h | 2 +- .../Code/Tests/AssetValidationTest.cpp | 11 +-- Registry/application_options.setreg | 17 ++++ 12 files changed, 127 insertions(+), 95 deletions(-) rename Code/Tools/AssetBundler/tests/{ => Assets}/Engine/SeedAssetList.seed (100%) create mode 100644 Registry/application_options.setreg diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBundle/AssetBundleComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBundle/AssetBundleComponent.cpp index 61e144d338..95319d2e6b 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBundle/AssetBundleComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/AssetBundle/AssetBundleComponent.cpp @@ -17,7 +17,7 @@ #include #include #include -#include +#include #include #include #include @@ -250,7 +250,7 @@ namespace AzToolsFramework AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); AZ_Assert(fileIO != nullptr, "AZ::IO::FileIOBase must be ready for use.\n"); - AZStd::string bundleFilePath = assetBundleSettings.m_bundleFilePath; + AZ::IO::Path bundleFilePath = AZ::IO::Path(AZStd::string_view{ AZ::Utils::GetEnginePath() }) / assetBundleSettings.m_bundleFilePath; AzFramework::PlatformId platformId = static_cast(AzFramework::PlatformHelper::GetPlatformIndexFromName(assetBundleSettings.m_platform.c_str())); @@ -259,22 +259,13 @@ namespace AzToolsFramework return false; } - const char* appRoot = nullptr; - AzFramework::ApplicationRequests::Bus::BroadcastResult(appRoot, &AzFramework::ApplicationRequests::GetAppRoot); - - if (AzFramework::StringFunc::Path::IsRelative(bundleFilePath.c_str())) - { - AzFramework::StringFunc::Path::ConstructFull(appRoot, bundleFilePath.c_str(), bundleFilePath, true); - } - AZ::u64 maxSizeInBytes = static_cast(assetBundleSettings.m_maxBundleSizeInMB * NumOfBytesInMB); AZ::u64 assetCatalogFileSizeBuffer = static_cast(AssetCatalogFileSizeBufferPercentage * assetBundleSettings.m_maxBundleSizeInMB * NumOfBytesInMB) / 100; AZ::u64 bundleSize = 0; AZ::u64 totalFileSize = 0; int bundleIndex = 0; - AZStd::string bundleFullPath = bundleFilePath; - AZStd::string tempBundleFilePath = bundleFullPath + "_temp"; + AZStd::string tempBundleFilePath = bundleFilePath.Native() + "_temp"; AZStd::vector dependentBundleNames; AZStd::vector levelDirs; @@ -301,7 +292,7 @@ namespace AzToolsFramework if (fileIO->Exists(bundleFilePath.c_str())) { // This will delete both the parent bundle as well as all the dependent bundles mentioned in the manifest file of the parent bundle. - if (!DeleteBundleFiles(bundleFilePath)) + if (!DeleteBundleFiles(bundleFilePath.Native())) { return false; } @@ -390,7 +381,7 @@ namespace AzToolsFramework // we need to find a bundle which does not exist on disk; bundleIndex++; numOfTries--; - dependentBundleFileName = CreateAssetBundleFileName(bundleFilePath, bundleIndex); + dependentBundleFileName = CreateAssetBundleFileName(bundleFilePath.Native(), bundleIndex); AzFramework::StringFunc::Path::ReplaceFullName(tempBundleFilePath, (dependentBundleFileName + tempBundleFileSuffix).c_str()); } while (numOfTries && fileIO->Exists(tempBundleFilePath.c_str())); @@ -463,15 +454,7 @@ namespace AzToolsFramework AZ::IO::FileIOBase* fileIO = AZ::IO::FileIOBase::GetInstance(); - AZStd::string assetFileInfoListPath = assetBundleSettings.m_assetFileInfoListPath; - - const char* appRoot = nullptr; - AzFramework::ApplicationRequests::Bus::BroadcastResult(appRoot, &AzFramework::ApplicationRequests::GetAppRoot); - - if (AzFramework::StringFunc::Path::IsRelative(assetFileInfoListPath.c_str())) - { - AzFramework::StringFunc::Path::ConstructFull(appRoot, assetFileInfoListPath.c_str(), assetFileInfoListPath, true); - } + AZ::IO::Path assetFileInfoListPath = AZ::IO::Path{ AZStd::string_view{AZ::Utils::GetEnginePath()} } / assetBundleSettings.m_assetFileInfoListPath; if (!fileIO->Exists(assetFileInfoListPath.c_str())) { diff --git a/Code/Tools/AssetBundler/source/ui/AssetBundlerTabWidget.cpp b/Code/Tools/AssetBundler/source/ui/AssetBundlerTabWidget.cpp index 2719944af4..9dcfd34c35 100644 --- a/Code/Tools/AssetBundler/source/ui/AssetBundlerTabWidget.cpp +++ b/Code/Tools/AssetBundler/source/ui/AssetBundlerTabWidget.cpp @@ -15,6 +15,7 @@ #include #include +#include #include #include #include @@ -232,8 +233,8 @@ namespace AssetBundler for (const QJsonValue scanPath : m_watchedFiles + m_watchedFolders) { - AZStd::string scanFilePathStr = scanPath.toString().toUtf8().data(); - AzFramework::StringFunc::Path::ConstructFull(GetCachedEngineRoot().c_str(), scanFilePathStr.c_str(), scanFilePathStr); + auto scanFilePathStr = (AZ::IO::Path(AZStd::string_view{ AZ::Utils::GetEnginePath() }) + / scanPath.toString().toUtf8().data()).LexicallyNormal(); // Check whether the file has already been watched // Get absolute file paths via QFileInfo to keep consistency in the letter case @@ -263,8 +264,8 @@ namespace AssetBundler for (auto itr = scanPaths.begin(); itr != scanPaths.end(); ++itr) { QJsonValueRef scanPathValueRef = *itr; - AZStd::string scanPath = scanPathValueRef.toString().toUtf8().data(); - AzFramework::StringFunc::Path::ConstructFull(GetCachedEngineRoot().c_str(), scanPath.c_str(), scanPath); + auto scanPath = (AZ::IO::Path(AZStd::string_view{ AZ::Utils::GetEnginePath() }) + / scanPathValueRef.toString().toUtf8().data()).LexicallyNormal(); // Check whether the file is being watched // Get absolute file paths via QFileInfo to keep consistency in the letter case @@ -316,13 +317,8 @@ namespace AssetBundler for (const QJsonValue scanPath : scanPaths[AssetBundlingFileTypes[fileType]].toArray()) { - AZStd::string absoluteScanPath = scanPath.toString().toUtf8().data(); - AZStd::replace(absoluteScanPath.begin(), absoluteScanPath.end(), AZ_WRONG_FILESYSTEM_SEPARATOR, AZ_CORRECT_FILESYSTEM_SEPARATOR); - - if (AzFramework::StringFunc::Path::IsRelative(absoluteScanPath.c_str())) - { - AzFramework::StringFunc::Path::ConstructFull(GetCachedEngineRoot().c_str(), absoluteScanPath.c_str(), absoluteScanPath); - } + auto absoluteScanPath = (AZ::IO::Path(AZStd::string_view{ AZ::Utils::GetEnginePath() }) + / scanPath.toString().toUtf8().data()).LexicallyNormal(); if (AZ::IO::FileIOBase::GetInstance()->IsDirectory(absoluteScanPath.c_str())) { diff --git a/Code/Tools/AssetBundler/source/ui/SeedTabWidget.cpp b/Code/Tools/AssetBundler/source/ui/SeedTabWidget.cpp index b05a2e0c90..60b4104c5a 100644 --- a/Code/Tools/AssetBundler/source/ui/SeedTabWidget.cpp +++ b/Code/Tools/AssetBundler/source/ui/SeedTabWidget.cpp @@ -138,7 +138,7 @@ namespace AssetBundler m_watchedFolders.insert(m_guiApplicationManager->GetSeedListsFolder().c_str()); // Get the list of default Seed List files - m_filePathToGemNameMap = AssetBundler::GetDefaultSeedListFiles(GetCachedEngineRoot().c_str(), m_guiApplicationManager->GetCurrentProjectName(), + m_filePathToGemNameMap = AssetBundler::GetDefaultSeedListFiles(AZStd::string_view{ AZ::Utils::GetEnginePath() }, m_guiApplicationManager->GetCurrentProjectName(), m_guiApplicationManager->GetGemInfoList(), m_guiApplicationManager->GetEnabledPlatforms()); // Get the list of default Seeds that are not stored in a Seed List file on-disk diff --git a/Code/Tools/AssetBundler/source/utils/applicationManager.cpp b/Code/Tools/AssetBundler/source/utils/applicationManager.cpp index 7aae023e72..ccf5427771 100644 --- a/Code/Tools/AssetBundler/source/utils/applicationManager.cpp +++ b/Code/Tools/AssetBundler/source/utils/applicationManager.cpp @@ -45,13 +45,6 @@ namespace AssetBundler { const char compareVariablePrefix = '$'; - GemInfo::GemInfo(AZStd::string name, AZStd::string relativeFilePath, AZStd::string absoluteFilePath) - : m_gemName(name) - , m_relativeFilePath(relativeFilePath) - , m_absoluteFilePath(absoluteFilePath) - { - } - ApplicationManager::ApplicationManager(int* argc, char*** argv, QObject* parent) : QObject(parent) , AzToolsFramework::ToolsApplication(argc, argv) @@ -80,8 +73,6 @@ namespace AssetBundler m_assetSeedManager = AZStd::make_unique(); AZ_TracePrintf(AssetBundler::AppWindowName, "\n"); - g_cachedEngineRoot = AZ::IO::FixedMaxPath(GetEngineRoot()); - // There is no need to update the UserSettings file, so we can avoid a race condition by disabling save on shutdown AZ::UserSettingsComponentRequestBus::Broadcast(&AZ::UserSettingsComponentRequests::DisableSaveOnFinalize); return true; @@ -383,6 +374,13 @@ namespace AssetBundler { using namespace AzToolsFramework; + auto validateArgsOutcome = ValidateInputArgs(parser, m_allSeedsArgs); + if (!validateArgsOutcome.IsSuccess()) + { + OutputHelpSeeds(); + return AZ::Failure(validateArgsOutcome.TakeError()); + } + SeedsParams params; params.m_ignoreFileCase = parser->HasSwitch(IgnoreFileCaseFlag); @@ -473,6 +471,13 @@ namespace AssetBundler AZ::Outcome ApplicationManager::ParseAssetListsCommandData(const AZ::CommandLine* parser) { + auto validateArgsOutcome = ValidateInputArgs(parser, m_allAssetListsArgs); + if (!validateArgsOutcome.IsSuccess()) + { + OutputHelpAssetLists(); + return AZ::Failure(validateArgsOutcome.TakeError()); + } + AssetListsParams params; // Read in Platform arg @@ -536,6 +541,13 @@ namespace AssetBundler AZ::Outcome ApplicationManager::ParseComparisonRulesCommandData(const AZ::CommandLine* parser) { + auto validateArgsOutcome = ValidateInputArgs(parser, m_allComparisonRulesArgs); + if (!validateArgsOutcome.IsSuccess()) + { + OutputHelpComparisonRules(); + return AZ::Failure(validateArgsOutcome.TakeError()); + } + ScopedTraceHandler traceHandler; ComparisonRulesParams params; @@ -918,6 +930,13 @@ namespace AssetBundler AZ::Outcome ApplicationManager::ParseCompareCommandData(const AZ::CommandLine* parser) { + auto validateArgsOutcome = ValidateInputArgs(parser, m_allCompareArgs); + if (!validateArgsOutcome.IsSuccess()) + { + OutputHelpCompare(); + return AZ::Failure(validateArgsOutcome.TakeError()); + } + ComparisonParams params; // Read in Platform arg @@ -1009,6 +1028,13 @@ namespace AssetBundler AZ::Outcome ApplicationManager::ParseBundleSettingsCommandData(const AZ::CommandLine* parser) { + auto validateArgsOutcome = ValidateInputArgs(parser, m_allBundleSettingsArgs); + if (!validateArgsOutcome.IsSuccess()) + { + OutputHelpBundleSettings(); + return AZ::Failure(validateArgsOutcome.TakeError()); + } + BundleSettingsParams params; // Read in Platform arg @@ -1213,6 +1239,13 @@ namespace AssetBundler AZ::Outcome ApplicationManager::ParseBundlesCommandData(const AZ::CommandLine* parser) { + auto validateArgsOutcome = ValidateInputArgs(parser, m_allBundlesArgs); + if (!validateArgsOutcome.IsSuccess()) + { + OutputHelpBundles(); + return AZ::Failure(validateArgsOutcome.TakeError()); + } + auto parseSettingsOutcome = ParseBundleSettingsAndOverrides(parser, BundlesCommand); if (!parseSettingsOutcome.IsSuccess()) { @@ -1224,6 +1257,14 @@ namespace AssetBundler AZ::Outcome ApplicationManager::ParseBundleSeedCommandData(const AZ::CommandLine* parser) { + + auto validateArgsOutcome = ValidateInputArgs(parser, m_allBundleSeedArgs); + if (!validateArgsOutcome.IsSuccess()) + { + OutputHelpBundleSeed(); + return AZ::Failure(validateArgsOutcome.TakeError()); + } + BundleSeedParams params; params.m_addSeedList = GetAddSeedArgList(parser); @@ -1241,6 +1282,12 @@ namespace AssetBundler AZ::Outcome ApplicationManager::ValidateInputArgs(const AZ::CommandLine* parser, const AZStd::vector& validArgList) { + constexpr AZStd::string_view ApplicationArgList = "/O3DE/AzCore/Application/ValidCommandOptions"; + AZStd::vector validApplicationArgs; + if (auto settingsRegistry = AZ::SettingsRegistry::Get(); settingsRegistry != nullptr) + { + settingsRegistry->GetObject(validApplicationArgs, ApplicationArgList); + } for (const auto& paramInfo : *parser) { // Skip positional arguments @@ -1258,10 +1305,18 @@ namespace AssetBundler break; } } + for (const auto& validArg : validApplicationArgs) + { + if (AZ::StringFunc::Equal(paramInfo.m_option, validArg)) + { + isValidArg = true; + break; + } + } if (!isValidArg) { - return AZ::Failure(AZStd::string::format("Unknown argument: \"--%s\" is not an unknown argument for this sub-command.", paramInfo.m_option.c_str())); + return AZ::Failure(AZStd::string::format(R"(Invalid argument: "--%s" is not a valid argument for this sub-command.)", paramInfo.m_option.c_str())); } } @@ -1346,10 +1401,10 @@ namespace AssetBundler } // If no platform was specified, defaulting to platforms specified in the asset processor config files - const char* appRoot = nullptr; - AzFramework::ApplicationRequests::Bus::BroadcastResult(appRoot, &AzFramework::ApplicationRequests::GetAppRoot); - - AzFramework::PlatformFlags platformFlags = GetEnabledPlatformFlags(GetEngineRoot(), appRoot, AZ::Utils::GetProjectPath().c_str()); + AzFramework::PlatformFlags platformFlags = GetEnabledPlatformFlags( + AZStd::string_view{ AZ::Utils::GetEnginePath() }, + AZStd::string_view{ AZ::Utils::GetEnginePath() }, + AZStd::string_view{ AZ::Utils::GetProjectPath() }); auto platformsString = AzFramework::PlatformHelper::GetCommaSeparatedPlatformList(platformFlags); AZ_TracePrintf(AppWindowName, "No platform specified, defaulting to platforms ( %s ).\n", platformsString.c_str()); diff --git a/Code/Tools/AssetBundler/source/utils/utils.cpp b/Code/Tools/AssetBundler/source/utils/utils.cpp index 6058728a76..39bc1a7e13 100644 --- a/Code/Tools/AssetBundler/source/utils/utils.cpp +++ b/Code/Tools/AssetBundler/source/utils/utils.cpp @@ -109,17 +109,15 @@ namespace AssetBundler const char* AssetCatalogFilename = "assetcatalog.xml"; - AZ::IO::FixedMaxPath g_cachedEngineRoot; - - const char EngineDirectoryName[] = "Engine"; + constexpr auto EngineDirectoryName = AZ::IO::FixedMaxPath("Assets") / "Engine"; const char RestrictedDirectoryName[] = "restricted"; const char PlatformsDirectoryName[] = "Platforms"; const char GemsDirectoryName[] = "Gems"; const char GemsAssetsDirectoryName[] = "Assets"; const char GemsSeedFileName[] = "seedList"; const char EngineSeedFileName[] = "SeedAssetList"; - + namespace Internal { @@ -131,7 +129,7 @@ namespace AssetBundler AZStd::unordered_map& defaultSeedLists, AzFramework::PlatformFlags platformFlags) { - AZ::IO::FixedMaxPath engineRoot(GetCachedEngineRoot()); + AZ::IO::FixedMaxPath engineRoot(AZ::Utils::GetEnginePath()); AZ::IO::FixedMaxPath engineRestrictedRoot = engineRoot / RestrictedDirectoryName; AZ::IO::FixedMaxPath engineLocalPath = AZ::IO::PathView(engineDirectory.LexicallyRelative(engineRoot)); @@ -204,12 +202,6 @@ namespace AssetBundler } } - AZ::IO::FixedMaxPath GetCachedEngineRoot() - { - AZ_Error(AppWindowName, !g_cachedEngineRoot.empty(), "Cached Engine Root has not been initialized by the Bundler."); - return g_cachedEngineRoot; - } - void AddPlatformIdentifier(AZStd::string& filePath, const AZStd::string& platformIdentifier) { AZStd::string fileName; @@ -257,11 +249,11 @@ namespace AssetBundler absoluteEngineSeedFilePath.ReplaceExtension(AzToolsFramework::AssetSeedManager::GetSeedFileExtension()); if (fileIO->Exists(absoluteEngineSeedFilePath.c_str())) { - defaultSeedLists[absoluteEngineSeedFilePath.Native()] = EngineDirectoryName; + defaultSeedLists[absoluteEngineSeedFilePath.Native()] = EngineDirectoryName.String(); } // Add Seed Lists from the Platforms directory - Internal::AddPlatformsDirectorySeeds(engineDirectory, EngineDirectoryName, defaultSeedLists, platformFlag); + Internal::AddPlatformsDirectorySeeds(engineDirectory, EngineDirectoryName.String(), defaultSeedLists, platformFlag); auto absoluteProjectDefaultSeedFilePath = AZ::IO::Path(projectPath) / EngineSeedFileName; absoluteProjectDefaultSeedFilePath.ReplaceExtension(AzToolsFramework::AssetSeedManager::GetSeedFileExtension()); diff --git a/Code/Tools/AssetBundler/source/utils/utils.h b/Code/Tools/AssetBundler/source/utils/utils.h index 629fd90a31..454a279878 100644 --- a/Code/Tools/AssetBundler/source/utils/utils.h +++ b/Code/Tools/AssetBundler/source/utils/utils.h @@ -122,20 +122,8 @@ namespace AssetBundler //////////////////////////////////////////////////////////////////////////////////////////// extern const char* AssetCatalogFilename; - extern AZ::IO::FixedMaxPath g_cachedEngineRoot; static const size_t MaxErrorMessageLength = 4096; - //! This struct stores gem related information - struct GemInfo - { - AZ_CLASS_ALLOCATOR(GemInfo, AZ::SystemAllocator, 0); - GemInfo(AZStd::string name, AZStd::string relativeFilePath, AZStd::string absoluteFilePath); - GemInfo() = default; - AZStd::string m_gemName; - AZStd::string m_relativeFilePath; - AZStd::string m_absoluteFilePath; - }; - // The Warning Absorber is used to absorb warnings // One case that this is being used is during loading of the asset catalog. @@ -151,9 +139,6 @@ namespace AssetBundler bool OnPreWarning(const char* window, const char* fileName, int line, const char* func, const char* message) override; }; - // Returns the cached engine root. Throws an error if the cached path has not been initialized by the Bundler Application. - AZ::IO::FixedMaxPath GetCachedEngineRoot(); - /** * Determines the name of the currently enabled game project * @return Current Project name on success, error message on failure diff --git a/Code/Tools/AssetBundler/tests/Engine/SeedAssetList.seed b/Code/Tools/AssetBundler/tests/Assets/Engine/SeedAssetList.seed similarity index 100% rename from Code/Tools/AssetBundler/tests/Engine/SeedAssetList.seed rename to Code/Tools/AssetBundler/tests/Assets/Engine/SeedAssetList.seed diff --git a/Code/Tools/AssetBundler/tests/tests_main.cpp b/Code/Tools/AssetBundler/tests/tests_main.cpp index 6d874a3320..9e12623b0d 100644 --- a/Code/Tools/AssetBundler/tests/tests_main.cpp +++ b/Code/Tools/AssetBundler/tests/tests_main.cpp @@ -88,7 +88,7 @@ namespace AssetBundler const char RelativeTestFolder[] = "Code/Tools/AssetBundler/tests"; const char GemsFolder[] = "Gems"; - const char EngineFolder[] = "Engine"; + constexpr auto EngineFolder = AZ::IO::FixedMaxPath("Assets") / "Engine"; const char PlatformsFolder[] = "Platforms"; const char DummyProjectFolder[] = "DummyProject"; @@ -113,13 +113,14 @@ namespace AssetBundler AZ::SettingsRegistry::Register(&m_registry); } - AssetBundler::g_cachedEngineRoot = m_data->m_application.get()->GetEngineRoot(); - if (AssetBundler::g_cachedEngineRoot.empty()) + AZ::IO::FixedMaxPath engineRoot = AZ::Utils::GetEnginePath(); + if (engineRoot.empty()) { GTEST_FATAL_FAILURE_(AZStd::string::format("Unable to locate engine root.\n").c_str()); } - AzFramework::StringFunc::Path::Join(AssetBundler::g_cachedEngineRoot.c_str(), RelativeTestFolder, m_data->m_testEngineRoot); + + m_data->m_testEngineRoot = (engineRoot / RelativeTestFolder).LexicallyNormal().String(); m_data->m_localFileIO = aznew AZ::IO::LocalFileIO(); m_data->m_priorFileIO = AZ::IO::FileIOBase::GetInstance(); @@ -131,8 +132,8 @@ namespace AssetBundler AddGemData(m_data->m_testEngineRoot.c_str(), "GemA"); AddGemData(m_data->m_testEngineRoot.c_str(), "GemB"); - AZStd::string absoluteEngineSeedFilePath; - AzFramework::StringFunc::Path::ConstructFull(m_data->m_testEngineRoot.c_str(), EngineFolder, "SeedAssetList", AzToolsFramework::AssetSeedManager::GetSeedFileExtension(), absoluteEngineSeedFilePath, true); + auto absoluteEngineSeedFilePath = m_data->m_testEngineRoot / EngineFolder / "SeedAssetList"; + absoluteEngineSeedFilePath.ReplaceExtension(AzToolsFramework::AssetSeedManager::GetSeedFileExtension()); m_data->m_gemSeedFilePairList.emplace_back(AZStd::make_pair(absoluteEngineSeedFilePath, true)); AddGemData(m_data->m_testEngineRoot.c_str(), "GemC", false); @@ -212,7 +213,7 @@ namespace AssetBundler AZStd::unique_ptr m_application = {}; AZ::IO::FileIOBase* m_priorFileIO = nullptr; AZ::IO::FileIOBase* m_localFileIO = nullptr; - AZStd::string m_testEngineRoot; + AZ::IO::Path m_testEngineRoot; }; const int GemAIndex = 0; diff --git a/Code/Tools/AssetProcessor/native/utilities/MissingDependencyScanner.cpp b/Code/Tools/AssetProcessor/native/utilities/MissingDependencyScanner.cpp index 73125fd58a..9daf97cf79 100644 --- a/Code/Tools/AssetProcessor/native/utilities/MissingDependencyScanner.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/MissingDependencyScanner.cpp @@ -20,30 +20,32 @@ AZ_POP_DISABLE_WARNING #include "native/AssetDatabase/AssetDatabase.h" #include "native/assetprocessor.h" #include +#include #include #include #include #include +#include #include #include #include #include -#include namespace AssetProcessor { - const char* EngineFolder = "Engine"; + constexpr auto EngineFolder = AZ::IO::FixedMaxPath("Assets") / "Engine"; AZStd::string GetXMLDependenciesFile(const AZStd::string& fullPath, const AZStd::vector& gemInfoList, AZStd::string& tokenName) { AZ::IO::Path xmlDependenciesFileFullPath; - tokenName = EngineFolder; + tokenName = EngineFolder.String(); for (const AzFramework::GemInfo& gemElement : gemInfoList) { for (const AZ::IO::Path& absoluteSourcePath : gemElement.m_absoluteSourcePaths) { - if (AZ::StringFunc::StartsWith(fullPath, absoluteSourcePath.Native()) || AZ::StringFunc::Equal(absoluteSourcePath.Native(), fullPath)) + if (AZ::IO::PathView(fullPath).IsRelativeTo(absoluteSourcePath)) { + xmlDependenciesFileFullPath = absoluteSourcePath; xmlDependenciesFileFullPath /= AzFramework::GemInfo::GetGemAssetFolder(); xmlDependenciesFileFullPath /= AZStd::string::format("%s_Dependencies.xml", gemElement.m_gemName.c_str());; if (AZ::IO::FileIOBase::GetInstance()->Exists(xmlDependenciesFileFullPath.c_str())) @@ -57,7 +59,7 @@ namespace AssetProcessor // if we are here than either the %gemName%_Dependencies.xml file does not exists or the user inputted path is not inside a gems folder, // in both the cases we will return the engine dependencies file - xmlDependenciesFileFullPath = AZ::IO::FileIOBase::GetInstance()->GetAlias("@devroot@"); + xmlDependenciesFileFullPath = AZ::Utils::GetEnginePath(); xmlDependenciesFileFullPath /= EngineFolder; xmlDependenciesFileFullPath /= "Engine_Dependencies.xml"; diff --git a/Gems/AssetValidation/Code/Source/AssetSeedUtil.h b/Gems/AssetValidation/Code/Source/AssetSeedUtil.h index 4a6ff1f1d8..60d94e8903 100644 --- a/Gems/AssetValidation/Code/Source/AssetSeedUtil.h +++ b/Gems/AssetValidation/Code/Source/AssetSeedUtil.h @@ -30,7 +30,7 @@ namespace AssetValidation::AssetSeed constexpr char GemsDirectoryName[] = "Gems"; constexpr char GemsSeedFileName[] = "seedList"; constexpr char EngineSeedFileName[] = "SeedAssetList"; - constexpr char EngineDirectoryName[] = "Engine"; + constexpr auto EngineDirectoryName = AZ::IO::FixedMaxPath("Assets") / "Engine"; void AddPlatformSeeds(const AZStd::string& rootFolder, AZStd::vector& defaultSeedLists, AzFramework::PlatformFlags platformFlags); diff --git a/Gems/AssetValidation/Code/Tests/AssetValidationTest.cpp b/Gems/AssetValidation/Code/Tests/AssetValidationTest.cpp index a5ff671fc3..5003c4484c 100644 --- a/Gems/AssetValidation/Code/Tests/AssetValidationTest.cpp +++ b/Gems/AssetValidation/Code/Tests/AssetValidationTest.cpp @@ -32,20 +32,21 @@ TEST_F(AssetValidationTest, DefaultSeedList_ReturnsExpectedSeedLists) { AZStd::vector gemInfo; - AZStd::string gemSeedList, engineSeedList, projectSeedList; + AZ::IO::Path gemSeedList, engineSeedList, projectSeedList; - ASSERT_TRUE(CreateDummyFile((AZ::IO::Path("mockGem") / AzFramework::GemInfo::GetGemAssetFolder()).c_str(), "seedList", "Mock Gem Seed List", gemSeedList)); - ASSERT_TRUE(CreateDummyFile("Engine", "SeedAssetList", "Engine Seed List", engineSeedList)); + ASSERT_TRUE(CreateDummyFile((AZ::IO::Path("mockGem") / AzFramework::GemInfo::GetGemAssetFolder()).c_str(), "seedList", "Mock Gem Seed List", gemSeedList.Native())); + ASSERT_TRUE(CreateDummyFile((AZ::IO::Path("Assets") / "Engine").c_str(), "SeedAssetList", "Engine Seed List", engineSeedList.Native())); AZ::SettingsRegistryInterface::FixedValueString projectName = AZ::Utils::GetProjectName(); ASSERT_FALSE(projectName.empty()); - ASSERT_TRUE(CreateDummyFile(projectName.c_str(), "SeedAssetList", "Project Seed List", projectSeedList)); + ASSERT_TRUE(CreateDummyFile(projectName.c_str(), "SeedAssetList", "Project Seed List", projectSeedList.Native())); AzFramework::GemInfo mockGem("MockGem"); mockGem.m_absoluteSourcePaths.push_back((m_tempDir / "mockGem").string().c_str()); gemInfo.push_back(mockGem); - AZStd::vector defaultSeedLists = AssetValidation::AssetSeed::GetDefaultSeedListFiles(gemInfo, AzFramework::PlatformFlags::Platform_PC); + AZStd::vector defaultSeedStringList = AssetValidation::AssetSeed::GetDefaultSeedListFiles(gemInfo, AzFramework::PlatformFlags::Platform_PC); + AZStd::vector defaultSeedLists{ AZStd::make_move_iterator(defaultSeedStringList.begin()), AZStd::make_move_iterator(defaultSeedStringList.end()) }; ASSERT_THAT(defaultSeedLists, ::testing::UnorderedElementsAre(gemSeedList, engineSeedList, projectSeedList)); } diff --git a/Registry/application_options.setreg b/Registry/application_options.setreg new file mode 100644 index 0000000000..06ccdc9b41 --- /dev/null +++ b/Registry/application_options.setreg @@ -0,0 +1,17 @@ +{ + "O3DE" : { + "AzCore": { + "Application": { + "ValidCommandOptions": [ + "project-path", + "engine-path", + "project-cache-path", + "regset", + "regremove", + "regdump", + "regdumpall" + ] + } + } + } +} From edf8ab4822277349fdcc3daa42f38dbf8134af36 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Mon, 3 May 2021 18:55:42 -0700 Subject: [PATCH 060/185] Renaming CPack.cmake to Packaging.cmake to avoid infinite recursion (Packaging.cmake includes CPack.cmake) (#533) --- CMakeLists.txt | 2 +- cmake/{CPack.cmake => Packaging.cmake} | 0 cmake/cmake_files.cmake | 2 +- 3 files changed, 2 insertions(+), 2 deletions(-) rename cmake/{CPack.cmake => Packaging.cmake} (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index 868757ebcd..ae8a7a05f8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -127,5 +127,5 @@ if(NOT INSTALLED_ENGINE) ly_setup_o3de_install() # IMPORTANT: must be included last - include(cmake/CPack.cmake) + include(cmake/Packaging.cmake) endif() diff --git a/cmake/CPack.cmake b/cmake/Packaging.cmake similarity index 100% rename from cmake/CPack.cmake rename to cmake/Packaging.cmake diff --git a/cmake/cmake_files.cmake b/cmake/cmake_files.cmake index 5045a42cbe..e423eb0dbc 100644 --- a/cmake/cmake_files.cmake +++ b/cmake/cmake_files.cmake @@ -14,7 +14,6 @@ set(FILES 3rdPartyPackages.cmake CommandExecution.cmake Configurations.cmake - CPack.cmake Dependencies.cmake Deployment.cmake EngineFinder.cmake @@ -27,6 +26,7 @@ set(FILES LYPython.cmake LYWrappers.cmake Monolithic.cmake + Packaging.cmake PAL.cmake PALTools.cmake Projects.cmake From 03c219bd2dfa6d3d5f37a7bfe552e1dd04f4087e Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Mon, 3 May 2021 21:31:06 -0500 Subject: [PATCH 061/185] Removed unused code --- Code/Sandbox/Editor/IconManager.cpp | 7 --- .../SandboxIntegration.cpp | 7 --- .../Code/Source/AtomBridgeEditorModule.cpp | 2 - .../Code/Source/BuilderComponent.cpp | 53 ------------------- .../AtomBridge/Code/Source/BuilderComponent.h | 36 ------------- .../Code/atombridge_editor_files.cmake | 2 - 6 files changed, 107 deletions(-) delete mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp delete mode 100644 Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h diff --git a/Code/Sandbox/Editor/IconManager.cpp b/Code/Sandbox/Editor/IconManager.cpp index 3916ee7726..828a7cdfcc 100644 --- a/Code/Sandbox/Editor/IconManager.cpp +++ b/Code/Sandbox/Editor/IconManager.cpp @@ -114,13 +114,6 @@ int CIconManager::GetIconTexture(const char* iconName) return 0; } - ITexture* texture = GetIEditor()->GetRenderer() ? GetIEditor()->GetRenderer()->EF_LoadTexture(iconName) : nullptr; - if (texture) - { - id = texture->GetTextureID(); - m_textures[iconName] = id; - } - return id; } diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp index b0dce80ec8..378bf3d4a1 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/SandboxIntegration.cpp @@ -161,13 +161,6 @@ void SandboxIntegrationManager::Setup() AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusConnect(); AzToolsFramework::SliceEditorEntityOwnershipServiceNotificationBus::Handler::BusConnect(); - // turn on the this debug display request bus implementation if no other implementation is active - if( !(AzFramework::DebugDisplayRequestBus::HasHandlers())) - { - m_debugDisplayBusImplementationActive = true; - AzFramework::DebugDisplayRequestBus::Handler::BusConnect( - AzToolsFramework::ViewportInteraction::g_mainViewportEntityDebugDisplayId); - } AzFramework::DisplayContextRequestBus::Handler::BusConnect(); SetupFileExtensionMap(); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeEditorModule.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeEditorModule.cpp index c955523d09..f2c2a6f5aa 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeEditorModule.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/AtomBridgeEditorModule.cpp @@ -13,7 +13,6 @@ #include #include #include -#include #include "./Editor/AssetCollectionAsyncLoaderTestComponent.h" @@ -33,7 +32,6 @@ namespace AZ { // Push results of [MyComponent]::CreateDescriptor() into m_descriptors here. m_descriptors.insert(m_descriptors.end(), { - BuilderComponent::CreateDescriptor(), AssetCollectionAsyncLoaderTestComponent::CreateDescriptor(), }); } diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.cpp deleted file mode 100644 index 997b7c3b0c..0000000000 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.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. -* -*/ - -#include -#include -#include -#include - -#include - -#include - -namespace AZ -{ - namespace AtomBridge - { - void BuilderComponent::Reflect(AZ::ReflectContext* context) - { - if (auto* serialize = azrtti_cast(context)) - { - serialize->Class() - ->Version(0) - ->Attribute(AZ::Edit::Attributes::SystemComponentTags, AZStd::vector({ AssetBuilderSDK::ComponentTags::AssetBuilder })) - ; - } - } - - BuilderComponent::BuilderComponent() - { - } - - BuilderComponent::~BuilderComponent() - { - } - - void BuilderComponent::Activate() - { - } - - void BuilderComponent::Deactivate() - { - } - } // namespace RPI -} // namespace AZ diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h b/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.h deleted file mode 100644 index d6c462cc43..0000000000 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/BuilderComponent.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. -* -*/ - -#pragma once - -#include - -namespace AZ -{ - namespace AtomBridge - { - class BuilderComponent final - : public AZ::Component - { - public: - AZ_COMPONENT(BuilderComponent, "{D1FE015B-8431-4155-8FD0-8197F246901A}"); - static void Reflect(AZ::ReflectContext* context); - - BuilderComponent(); - ~BuilderComponent() override; - - // AZ::Component overrides... - void Activate() override; - void Deactivate() override; - }; - } // namespace RPI -} // namespace AZ diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_editor_files.cmake b/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_editor_files.cmake index f2cf8c6c14..55ed9f28a0 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_editor_files.cmake +++ b/Gems/AtomLyIntegration/AtomBridge/Code/atombridge_editor_files.cmake @@ -13,8 +13,6 @@ set(FILES Source/AtomBridgeEditorModule.cpp Source/AtomBridgeModule.cpp Source/AtomBridgeModule.h - Source/BuilderComponent.cpp - Source/BuilderComponent.h Source/Editor/AssetCollectionAsyncLoaderTestComponent.cpp Source/Editor/AssetCollectionAsyncLoaderTestComponent.h ) From 837458abf27a13e10ede29226bbe3aa30c3b9791 Mon Sep 17 00:00:00 2001 From: jiaweig Date: Mon, 3 May 2021 20:23:03 -0700 Subject: [PATCH 062/185] ATOM-15391 [RHI][Vulkan][Android] SSAO introduces horizontal lines on flat surfaces --- .../Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl index c1fa41991e..8294911b44 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SsaoCompute.azsl @@ -277,6 +277,8 @@ void MainCS(uint3 thread_id : SV_GroupThreadID, uint3 group_id : SV_GroupID, uin // Gather depth values float2 depthGatherUV = mad(float2(ldsPosition), GetPixelSize(), ldsOffsetUV); + // Gather on some GPUs will fall onto same pixels in adjacent coordinates due to rounding errors + depthGatherUV += GetHalfPixelSize(); float4 depthGather = PassSrg::m_linearDepth.Gather(PassSrg::PointSampler, depthGatherUV); WriteDepthGatherToLDS(ldsPosition, depthGather); From 31885753cbcd2ba79a724ba2626d6f4873849ea0 Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Mon, 3 May 2021 22:46:28 -0700 Subject: [PATCH 063/185] Fixes for compile failures with Clang on Windows (#532) * Fix compile errors when building with Clang. * Fix for clang-based unity builds --- .../AzCore/RTTI/AzStdOnDemandReflection.inl | 2 +- .../AzFramework/ProjectManager/ProjectManager.cpp | 2 +- .../PerforcePlugin/PerforceSourceControl.h | 2 +- .../Code/Source/Framework/MultipartFormData.cpp | 2 +- Gems/Atom/RHI/Code/Tests/Buffer.h | 2 ++ Gems/Atom/RHI/Code/Tests/Query.h | 1 - .../Source/RHI/FrameGraphExecuteGroupBase.cpp | 2 +- Gems/Metastream/Code/CMakeLists.txt | 2 ++ .../Platform/Android/metastream_android.cmake | 10 ++++++++++ .../Platform/Common/MSVC/metastream_msvc.cmake | 4 ---- .../Source/Platform/Linux/metastream_linux.cmake | 10 ++++++++++ .../Code/Source/Platform/Mac/metastream_mac.cmake | 10 ++++++++++ .../Platform/Windows/metastream_windows.cmake | 15 +++++++++++++++ .../Code/Source/Platform/iOS/metastream_ios.cmake | 10 ++++++++++ 14 files changed, 64 insertions(+), 10 deletions(-) create mode 100644 Gems/Metastream/Code/Source/Platform/Android/metastream_android.cmake create mode 100644 Gems/Metastream/Code/Source/Platform/Linux/metastream_linux.cmake create mode 100644 Gems/Metastream/Code/Source/Platform/Mac/metastream_mac.cmake create mode 100644 Gems/Metastream/Code/Source/Platform/Windows/metastream_windows.cmake create mode 100644 Gems/Metastream/Code/Source/Platform/iOS/metastream_ios.cmake diff --git a/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl b/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl index ab92604266..079c70c878 100644 --- a/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl +++ b/Code/Framework/AzCore/AzCore/RTTI/AzStdOnDemandReflection.inl @@ -816,7 +816,7 @@ namespace AZ template static void ReflectUnpackMethodFold(BehaviorContext::ClassBuilder& builder) { - AZStd::string methodName = AZStd::string::format("Get%ld", Index); + const AZStd::string methodName = AZStd::string::format("Get%zu", Index); builder->Method(methodName.data(), [](ContainerType& value) { return AZStd::get(value); }) ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) ->Attribute(AZ::ScriptCanvasAttributes::TupleGetFunctionIndex, Index) diff --git a/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp b/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp index ea8fd75cfd..985bc4665d 100644 --- a/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp +++ b/Code/Framework/AzFramework/AzFramework/ProjectManager/ProjectManager.cpp @@ -137,7 +137,7 @@ namespace AzFramework::ProjectManager } AZ::IO::FixedMaxPath pythonPath = engineRootPath / "python"; pythonPath /= AZ_TRAIT_AZFRAMEWORK_PYTHON_SHELL; - auto cmdPath = AZ::IO::FixedMaxPathString::format("%s %s%s --executable_path=%s --parent_pid=%" PRId64, pythonPath.Native().c_str(), + auto cmdPath = AZ::IO::FixedMaxPathString::format("%s %s%s --executable_path=%s --parent_pid=%" PRIu32, pythonPath.Native().c_str(), debugOption.c_str(), (projectManagerPath / projectsScript).c_str(), executablePath.c_str(), AZ::Platform::GetCurrentProcessId()); AzFramework::ProcessLauncher::ProcessLaunchInfo processLaunchInfo; diff --git a/Code/Sandbox/Plugins/PerforcePlugin/PerforceSourceControl.h b/Code/Sandbox/Plugins/PerforcePlugin/PerforceSourceControl.h index 16489d99fc..1efbbc912c 100644 --- a/Code/Sandbox/Plugins/PerforcePlugin/PerforceSourceControl.h +++ b/Code/Sandbox/Plugins/PerforcePlugin/PerforceSourceControl.h @@ -26,7 +26,7 @@ class CPerforceSourceControl public: // constructor CPerforceSourceControl() = default; - ~CPerforceSourceControl() = default; + virtual ~CPerforceSourceControl() = default; void Init(); diff --git a/Gems/AWSCore/Code/Source/Framework/MultipartFormData.cpp b/Gems/AWSCore/Code/Source/Framework/MultipartFormData.cpp index fdd5fa3c92..bec352bf35 100644 --- a/Gems/AWSCore/Code/Source/Framework/MultipartFormData.cpp +++ b/Gems/AWSCore/Code/Source/Framework/MultipartFormData.cpp @@ -117,7 +117,7 @@ namespace AWSCore result.m_content.append(AZStd::string::format(Detail::FOOTER_FMT, m_boundary.c_str())); // Populate the metadata - result.m_contentLength = AZStd::string::format("%lu", result.m_content.length()); + result.m_contentLength = AZStd::string::format("%zu", result.m_content.length()); result.m_contentType = AZStd::string::format("multipart/form-data; boundary=%s", m_boundary.c_str()); return result; diff --git a/Gems/Atom/RHI/Code/Tests/Buffer.h b/Gems/Atom/RHI/Code/Tests/Buffer.h index cfa216293f..a5538b0071 100644 --- a/Gems/Atom/RHI/Code/Tests/Buffer.h +++ b/Gems/Atom/RHI/Code/Tests/Buffer.h @@ -30,6 +30,8 @@ namespace UnitTest void ShutdownInternal() override; }; + class BufferPool; + class Buffer : public AZ::RHI::Buffer { diff --git a/Gems/Atom/RHI/Code/Tests/Query.h b/Gems/Atom/RHI/Code/Tests/Query.h index 6220ae5f55..80b47f3e42 100644 --- a/Gems/Atom/RHI/Code/Tests/Query.h +++ b/Gems/Atom/RHI/Code/Tests/Query.h @@ -21,7 +21,6 @@ namespace UnitTest class Query : public AZ::RHI::Query { - friend class QueryPool; public: AZ_CLASS_ALLOCATOR(Query, AZ::SystemAllocator, 0); diff --git a/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphExecuteGroupBase.cpp b/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphExecuteGroupBase.cpp index 809790a7d5..6251eca7dc 100644 --- a/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphExecuteGroupBase.cpp +++ b/Gems/Atom/RHI/DX12/Code/Source/RHI/FrameGraphExecuteGroupBase.cpp @@ -32,7 +32,7 @@ namespace AZ AZ_Assert(commandList && commandList->IsRecording() == false, "Command list not valid."); } } -#endif() +#endif return AZStd::move(m_workRequest); } diff --git a/Gems/Metastream/Code/CMakeLists.txt b/Gems/Metastream/Code/CMakeLists.txt index 47b6f6f9c5..326c21c5a9 100644 --- a/Gems/Metastream/Code/CMakeLists.txt +++ b/Gems/Metastream/Code/CMakeLists.txt @@ -36,6 +36,7 @@ ly_add_target( metastream_shared_files.cmake ${pal_source_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake PLATFORM_INCLUDE_FILES + ${pal_source_dir}/metastream_${PAL_PLATFORM_NAME_LOWERCASE}.cmake ${common_source_dir}/${PAL_TRAIT_COMPILER_ID}/metastream_${PAL_TRAIT_COMPILER_ID_LOWERCASE}.cmake INCLUDE_DIRECTORIES PRIVATE @@ -62,6 +63,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) metastream_shared_files.cmake ${pal_source_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake PLATFORM_INCLUDE_FILES + ${pal_source_dir}/metastream_${PAL_PLATFORM_NAME_LOWERCASE}.cmake ${common_source_dir}/${PAL_TRAIT_COMPILER_ID}/metastream_${PAL_TRAIT_COMPILER_ID_LOWERCASE}.cmake INCLUDE_DIRECTORIES PRIVATE diff --git a/Gems/Metastream/Code/Source/Platform/Android/metastream_android.cmake b/Gems/Metastream/Code/Source/Platform/Android/metastream_android.cmake new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/Metastream/Code/Source/Platform/Android/metastream_android.cmake @@ -0,0 +1,10 @@ +# +# 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. +# diff --git a/Gems/Metastream/Code/Source/Platform/Common/MSVC/metastream_msvc.cmake b/Gems/Metastream/Code/Source/Platform/Common/MSVC/metastream_msvc.cmake index 2a42a01b08..5cebdbd198 100644 --- a/Gems/Metastream/Code/Source/Platform/Common/MSVC/metastream_msvc.cmake +++ b/Gems/Metastream/Code/Source/Platform/Common/MSVC/metastream_msvc.cmake @@ -11,7 +11,3 @@ # CivetHttpServer.cpp uses a try catch block set(LY_COMPILE_OPTIONS PRIVATE /EHsc) -set(LY_BUILD_DEPENDENCIES - PRIVATE - 3rdParty::civetweb -) \ No newline at end of file diff --git a/Gems/Metastream/Code/Source/Platform/Linux/metastream_linux.cmake b/Gems/Metastream/Code/Source/Platform/Linux/metastream_linux.cmake new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/Metastream/Code/Source/Platform/Linux/metastream_linux.cmake @@ -0,0 +1,10 @@ +# +# 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. +# diff --git a/Gems/Metastream/Code/Source/Platform/Mac/metastream_mac.cmake b/Gems/Metastream/Code/Source/Platform/Mac/metastream_mac.cmake new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/Metastream/Code/Source/Platform/Mac/metastream_mac.cmake @@ -0,0 +1,10 @@ +# +# 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. +# diff --git a/Gems/Metastream/Code/Source/Platform/Windows/metastream_windows.cmake b/Gems/Metastream/Code/Source/Platform/Windows/metastream_windows.cmake new file mode 100644 index 0000000000..3705f7d6fc --- /dev/null +++ b/Gems/Metastream/Code/Source/Platform/Windows/metastream_windows.cmake @@ -0,0 +1,15 @@ +# +# 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(LY_BUILD_DEPENDENCIES + PRIVATE + 3rdParty::civetweb +) diff --git a/Gems/Metastream/Code/Source/Platform/iOS/metastream_ios.cmake b/Gems/Metastream/Code/Source/Platform/iOS/metastream_ios.cmake new file mode 100644 index 0000000000..4d5680a30d --- /dev/null +++ b/Gems/Metastream/Code/Source/Platform/iOS/metastream_ios.cmake @@ -0,0 +1,10 @@ +# +# 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. +# From 80f692118bb15de792679c99597785911fb587e8 Mon Sep 17 00:00:00 2001 From: guthadam Date: Tue, 4 May 2021 01:27:12 -0500 Subject: [PATCH 064/185] ATOM-15451 always bring material editor and foreground when launching Bus, command line option, and handler to activate material editor window Made sure that material editor action in Ly tools menu is not checked/checkable Ly editor pushes command line option to use the same RHI https://jira.agscollab.com/browse/LYN-2610 https://jira.agscollab.com/browse/ATOM-15451 https://jira.agscollab.com/browse/ATOM-13742 --- .../Window/MaterialEditorWindowRequestBus.h | 3 +++ .../Code/Source/MaterialEditorApplication.cpp | 12 ++++++++++++ .../Source/Window/MaterialEditorWindow.cpp | 6 ++++++ .../Code/Source/Window/MaterialEditorWindow.h | 1 + .../Window/MaterialEditorWindowComponent.cpp | 1 + .../Material/EditorMaterialSystemComponent.cpp | 18 +++++++++++++++++- 6 files changed, 40 insertions(+), 1 deletion(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h index 538777b762..55e6ddac20 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Include/Atom/Window/MaterialEditorWindowRequestBus.h @@ -28,6 +28,9 @@ namespace MaterialEditor static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + //! Bring main window to foreground + virtual void ActivateWindow() = 0; + //! Add dockable widget in main window //! @param name title of the dockable window //! @param widget docked window content diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index ea82210814..3ffe2af1a6 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -45,6 +45,7 @@ #include #include +#include #include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT @@ -309,6 +310,13 @@ namespace MaterialEditor void MaterialEditorApplication::ProcessCommandLine(const AZ::CommandLine& commandLine) { + const AZStd::string activateWindowSwitchName = "activatewindow"; + if (commandLine.HasSwitch(activateWindowSwitchName)) + { + MaterialEditor::MaterialEditorWindowRequestBus::Broadcast( + &MaterialEditor::MaterialEditorWindowRequestBus::Handler::ActivateWindow); + } + const AZStd::string timeoputSwitchName = "timeout"; if (commandLine.HasSwitch(timeoputSwitchName)) { @@ -438,6 +446,10 @@ namespace MaterialEditor // Handle commmand line params from connected socket if (buffer.startsWith("ProcessCommandLine:")) { + // Bring the material editor to the foreground + MaterialEditor::MaterialEditorWindowRequestBus::Broadcast( + &MaterialEditor::MaterialEditorWindowRequestBus::Handler::ActivateWindow); + // Remove header and parse commands AZStd::string params(buffer.data(), buffer.size()); params = params.substr(strlen("ProcessCommandLine:")); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp index 1e116b4a22..6e47de189c 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.cpp @@ -129,6 +129,12 @@ namespace MaterialEditor MaterialEditorWindowRequestBus::Handler::BusDisconnect(); } + void MaterialEditorWindow::ActivateWindow() + { + activateWindow(); + raise(); + } + bool MaterialEditorWindow::AddDockWidget(const AZStd::string& name, QWidget* widget, uint32_t area, uint32_t orientation) { auto dockWidgetItr = m_dockWidgets.find(name); diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h index 6bd6e6b165..778e11275f 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindow.h @@ -61,6 +61,7 @@ namespace MaterialEditor private: // MaterialEditorWindowRequestBus::Handler overrides... + void ActivateWindow() override; bool AddDockWidget(const AZStd::string& name, QWidget* widget, uint32_t area, uint32_t orientation) override; void RemoveDockWidget(const AZStd::string& name) override; void SetDockWidgetVisible(const AZStd::string& name, bool visible) override; diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp index a1ff8da635..820cee30f9 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/Window/MaterialEditorWindowComponent.cpp @@ -50,6 +50,7 @@ namespace MaterialEditor ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "Editor") ->Attribute(AZ::Script::Attributes::Module, "materialeditor") + ->Event("ActivateWindow", &MaterialEditorWindowRequestBus::Events::ActivateWindow) ->Event("SetDockWidgetVisible", &MaterialEditorWindowRequestBus::Events::SetDockWidgetVisible) ->Event("IsDockWidgetVisible", &MaterialEditorWindowRequestBus::Events::IsDockWidgetVisible) ->Event("GetDockWidgetNames", &MaterialEditorWindowRequestBus::Events::GetDockWidgetNames) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index c32f124456..4cf51e2f37 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -23,6 +23,8 @@ #include #include +#include + #include #include @@ -125,6 +127,17 @@ namespace AZ QStringList arguments; arguments.append(sourcePath.c_str()); + + // Bring the material editor to the foreground if running + arguments.append("--activatewindow"); + + // Use the same RHI as the main editor + AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); + if (!apiName.IsEmpty()) + { + arguments.append(QString("--rhi=%1").arg(apiName.GetCStr())); + } + AtomToolsFramework::LaunchTool("MaterialEditor", ".exe", arguments); } @@ -139,7 +152,10 @@ namespace AZ { m_openMaterialEditorAction = new QAction("Material Editor"); m_openMaterialEditorAction->setShortcut(QKeySequence(Qt::Key_M)); - QObject::connect(m_openMaterialEditorAction, &QAction::triggered, m_openMaterialEditorAction, [this]() + m_openMaterialEditorAction->setCheckable(false); + m_openMaterialEditorAction->setChecked(false); + QObject::connect( + m_openMaterialEditorAction, &QAction::triggered, m_openMaterialEditorAction, [this]() { OpenInMaterialEditor(""); } From 64f42ba1cba87fb6c47e2662350e3ee09539b805 Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Tue, 4 May 2021 01:24:14 -0700 Subject: [PATCH 065/185] Removed the asset callback from the EditorReflectionProbeComponent, since the component may have been destroyed and recreated between the bake and the asset load. Replaced with an OnTick handler that polls the ReflectionProbeFeatureProcessor to determine when the asset is ready. --- .../ReflectionProbeFeatureProcessor.h | 13 +- ...ReflectionProbeFeatureProcessorInterface.h | 9 +- .../ReflectionProbe/ReflectionProbe.cpp | 3 +- .../Source/ReflectionProbe/ReflectionProbe.h | 5 +- .../ReflectionProbeFeatureProcessor.cpp | 70 +++--- .../EditorReflectionProbeComponent.cpp | 227 +++++++++--------- .../EditorReflectionProbeComponent.h | 6 + .../ReflectionProbeComponentController.cpp | 31 ++- .../ReflectionProbeComponentController.h | 2 +- 9 files changed, 210 insertions(+), 156 deletions(-) diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessor.h index a89875aaa6..ff84f77a3e 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessor.h @@ -36,10 +36,11 @@ namespace AZ void RemoveProbe(ReflectionProbeHandle& probe) override; void SetProbeOuterExtents(const ReflectionProbeHandle& probe, const AZ::Vector3& outerExtents) override; void SetProbeInnerExtents(const ReflectionProbeHandle& probe, const AZ::Vector3& innerExtents) override; - void SetProbeCubeMap(const ReflectionProbeHandle& probe, Data::Instance& cubeMapImage) override; + void SetProbeCubeMap(const ReflectionProbeHandle& probe, Data::Instance& cubeMapImage, const AZStd::string& relativePath) override; void SetProbeTransform(const ReflectionProbeHandle& probe, const AZ::Transform& transform) override; - void BakeProbe(const ReflectionProbeHandle& probe, BuildCubeMapCallback callback) override; - void NotifyCubeMapAssetReady(const AZStd::string relativePath, NotifyCubeMapAssetReadyCallback callback) override; + void BakeProbe(const ReflectionProbeHandle& probe, BuildCubeMapCallback callback, const AZStd::string& relativePath) override; + bool CheckCubeMapAssetNotification(const AZStd::string& relativePath, Data::Asset& outCubeMapAsset, CubeMapAssetNotificationType& outNotificationType) override; + bool IsCubeMapReferenced(const AZStd::string& relativePath) override; bool IsValidProbeHandle(const ReflectionProbeHandle& probe) const override { return (probe.get() != nullptr); } void ShowProbeVisualization(const ReflectionProbeHandle& probe, bool showVisualization) override; @@ -72,10 +73,9 @@ namespace AZ // AssetBus::MultiHandler overrides... void OnAssetReady(Data::Asset asset) override; void OnAssetError(Data::Asset asset) override; - void OnAssetReloaded(Data::Asset asset) override; // notifies and removes the notification entry - void HandleAssetNotification(Data::Asset asset, CubeMapAssetNotificationType notificationTyp); + void HandleAssetNotification(Data::Asset asset, CubeMapAssetNotificationType notificationType); // list of reflection probes const size_t InitialProbeAllocationSize = 64; @@ -86,9 +86,8 @@ namespace AZ { AZStd::string m_relativePath; AZ::Data::AssetId m_assetId; - bool m_existingAsset = false; - NotifyCubeMapAssetReadyCallback m_callback; Data::Asset m_asset; + CubeMapAssetNotificationType m_notificationType = CubeMapAssetNotificationType::None; }; typedef AZStd::vector NotifyCubeMapAssetVector; NotifyCubeMapAssetVector m_notifyCubeMapAssets; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessorInterface.h index 8b277e97c8..03c44d0442 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/ReflectionProbe/ReflectionProbeFeatureProcessorInterface.h @@ -30,11 +30,11 @@ namespace AZ enum CubeMapAssetNotificationType { + None, Ready, Error, Reloaded }; - using NotifyCubeMapAssetReadyCallback = AZStd::function& cubeMapAsset, CubeMapAssetNotificationType notificationType)>; // ReflectionProbeFeatureProcessorInterface provides an interface to the feature processor for code outside of Atom class ReflectionProbeFeatureProcessorInterface @@ -47,10 +47,11 @@ namespace AZ virtual void RemoveProbe(ReflectionProbeHandle& handle) = 0; virtual void SetProbeOuterExtents(const ReflectionProbeHandle& handle, const AZ::Vector3& outerExtents) = 0; virtual void SetProbeInnerExtents(const ReflectionProbeHandle& handle, const AZ::Vector3& innerExtents) = 0; - virtual void SetProbeCubeMap(const ReflectionProbeHandle& handle, Data::Instance& cubeMapImage) = 0; + virtual void SetProbeCubeMap(const ReflectionProbeHandle& handle, Data::Instance& cubeMapImage, const AZStd::string& relativePath) = 0; virtual void SetProbeTransform(const ReflectionProbeHandle& handle, const AZ::Transform& transform) = 0; - virtual void BakeProbe(const ReflectionProbeHandle& handle, BuildCubeMapCallback callback) = 0; - virtual void NotifyCubeMapAssetReady(const AZStd::string relativePath, NotifyCubeMapAssetReadyCallback callback) = 0; + virtual void BakeProbe(const ReflectionProbeHandle& handle, BuildCubeMapCallback callback, const AZStd::string& relativePath) = 0; + virtual bool CheckCubeMapAssetNotification(const AZStd::string& relativePath, Data::Asset& outCubeMapAsset, CubeMapAssetNotificationType& outNotificationType) = 0; + virtual bool IsCubeMapReferenced(const AZStd::string& relativePath) = 0; virtual bool IsValidProbeHandle(const ReflectionProbeHandle& probe) const = 0; virtual void ShowProbeVisualization(const ReflectionProbeHandle& probe, bool showVisualization) = 0; }; diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp index cfce718146..e0b79e23aa 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.cpp @@ -234,9 +234,10 @@ namespace AZ m_updateSrg = true; } - void ReflectionProbe::SetCubeMapImage(const Data::Instance& cubeMapImage) + void ReflectionProbe::SetCubeMapImage(const Data::Instance& cubeMapImage, const AZStd::string& relativePath) { m_cubeMapImage = cubeMapImage; + m_cubeMapRelativePath = relativePath; m_updateSrg = true; } diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h index 42b3ff5c5a..ab0e7a81d3 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbe.h @@ -88,7 +88,9 @@ namespace AZ const Aabb& GetInnerAabbWs() const { return m_innerAabbWs; } const Data::Instance& GetCubeMapImage() const { return m_cubeMapImage; } - void SetCubeMapImage(const Data::Instance& cubeMapImage); + void SetCubeMapImage(const Data::Instance& cubeMapImage, const AZStd::string& relativePath); + + const AZStd::string& GetCubeMapRelativePath() const { return m_cubeMapRelativePath; } bool GetUseParallaxCorrection() const { return m_useParallaxCorrection; } void SetUseParallaxCorrection(bool useParallaxCorrection) { m_useParallaxCorrection = useParallaxCorrection; } @@ -135,6 +137,7 @@ namespace AZ // cubemap Data::Instance m_cubeMapImage; + AZStd::string m_cubeMapRelativePath; bool m_useParallaxCorrection = false; // probe visualization diff --git a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp index a0d3e6ac51..740069fc6b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/ReflectionProbe/ReflectionProbeFeatureProcessor.cpp @@ -178,9 +178,9 @@ namespace AZ if (assetId.IsValid()) { - Data::AssetBus::MultiHandler::BusConnect(assetId); notificationEntry.m_assetId = assetId; notificationEntry.m_asset.Create(assetId, true); + Data::AssetBus::MultiHandler::BusConnect(assetId); } } @@ -257,10 +257,10 @@ namespace AZ m_probeSortRequired = true; } - void ReflectionProbeFeatureProcessor::SetProbeCubeMap(const ReflectionProbeHandle& probe, Data::Instance& cubeMapImage) + void ReflectionProbeFeatureProcessor::SetProbeCubeMap(const ReflectionProbeHandle& probe, Data::Instance& cubeMapImage, const AZStd::string& relativePath) { AZ_Assert(probe.get(), "SetProbeCubeMap called with an invalid handle"); - probe->SetCubeMapImage(cubeMapImage); + probe->SetCubeMapImage(cubeMapImage, relativePath); } void ReflectionProbeFeatureProcessor::SetProbeTransform(const ReflectionProbeHandle& probe, const AZ::Transform& transform) @@ -270,14 +270,11 @@ namespace AZ m_probeSortRequired = true; } - void ReflectionProbeFeatureProcessor::BakeProbe(const ReflectionProbeHandle& probe, BuildCubeMapCallback callback) + void ReflectionProbeFeatureProcessor::BakeProbe(const ReflectionProbeHandle& probe, BuildCubeMapCallback callback, const AZStd::string& relativePath) { AZ_Assert(probe.get(), "BakeProbe called with an invalid handle"); probe->BuildCubeMap(callback); - } - void ReflectionProbeFeatureProcessor::NotifyCubeMapAssetReady(const AZStd::string relativePath, NotifyCubeMapAssetReadyCallback callback) - { // check to see if this is an existing asset AZ::Data::AssetId assetId; AZ::Data::AssetCatalogRequestBus::BroadcastResult( @@ -287,13 +284,44 @@ namespace AZ azrtti_typeid(), false); - bool existingAsset = assetId.IsValid(); - m_notifyCubeMapAssets.push_back({ relativePath, assetId, existingAsset, callback }); + // we only track notifications for new cubemap assets, existing assets are automatically reloaded by the RPI + if (!assetId.IsValid()) + { + m_notifyCubeMapAssets.push_back({ relativePath, assetId }); + } + } + + bool ReflectionProbeFeatureProcessor::CheckCubeMapAssetNotification(const AZStd::string& relativePath, Data::Asset& outCubeMapAsset, CubeMapAssetNotificationType& outNotificationType) + { + for (NotifyCubeMapAssetVector::iterator itNotification = m_notifyCubeMapAssets.begin(); itNotification != m_notifyCubeMapAssets.end(); ++itNotification) + { + if (itNotification->m_relativePath == relativePath) + { + outNotificationType = itNotification->m_notificationType; + if (outNotificationType != CubeMapAssetNotificationType::None) + { + outCubeMapAsset = itNotification->m_asset; + m_notifyCubeMapAssets.erase(itNotification); + } + + return true; + } + } + + return false; + } - if (existingAsset) + bool ReflectionProbeFeatureProcessor::IsCubeMapReferenced(const AZStd::string& relativePath) + { + for (auto& reflectionProbe : m_reflectionProbes) { - Data::AssetBus::MultiHandler::BusConnect(assetId); + if (reflectionProbe->GetCubeMapRelativePath() == relativePath) + { + return true; + } } + + return false; } void ReflectionProbeFeatureProcessor::ShowProbeVisualization(const ReflectionProbeHandle& probe, bool showVisualization) @@ -509,17 +537,9 @@ namespace AZ { if (itNotification->m_assetId == asset.GetId()) { - if (itNotification->m_existingAsset && notificationType == CubeMapAssetNotificationType::Ready) - { - // existing cubemap assets only notify on reload or error - break; - } - - // notify - itNotification->m_callback(Data::static_pointer_cast(asset), notificationType); - - // remove the entry from the list - m_notifyCubeMapAssets.erase(itNotification); + // store the cubemap asset + itNotification->m_asset = Data::static_pointer_cast(asset); + itNotification->m_notificationType = notificationType; // stop notifications on this asset Data::AssetBus::MultiHandler::BusDisconnect(itNotification->m_assetId); @@ -540,11 +560,5 @@ namespace AZ HandleAssetNotification(asset, CubeMapAssetNotificationType::Error); } - - void ReflectionProbeFeatureProcessor::OnAssetReloaded(Data::Asset asset) - { - HandleAssetNotification(asset, CubeMapAssetNotificationType::Reloaded); - } - } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp index 9d34553eba..735eab5368 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.cpp @@ -133,23 +133,14 @@ namespace AZ AzFramework::EntityDebugDisplayEventBus::Handler::BusConnect(GetEntityId()); AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusConnect(GetEntityId()); EditorReflectionProbeBus::Handler::BusConnect(GetEntityId()); + AZ::TickBus::Handler::BusConnect(); ReflectionProbeComponentConfig& configuration = m_controller.m_configuration; - // special handling is required if this component is being cloned in the editor: - // if the entityId in the configuration does not match this component's entityId it is being cloned - AZ::u64 entityId = (AZ::u64)GetEntityId(); - if (configuration.m_entityId != EntityId::InvalidEntityId - && configuration.m_entityId != entityId) - { - // clear the cubeMapRelativePath to prevent the newly cloned reflection probe - // from using the same cubemap path as the original reflection probe - configuration.m_bakedCubeMapRelativePath = ""; - } - // update UI cubemap path display m_bakedCubeMapRelativePath = configuration.m_bakedCubeMapRelativePath; + AZ::u64 entityId = (AZ::u64)GetEntityId(); configuration.m_entityId = entityId; } @@ -158,9 +149,55 @@ namespace AZ EditorReflectionProbeBus::Handler::BusDisconnect(GetEntityId()); AzToolsFramework::EditorComponentSelectionRequestsBus::Handler::BusDisconnect(); AzFramework::EntityDebugDisplayEventBus::Handler::BusDisconnect(); + AZ::TickBus::Handler::BusDisconnect(); BaseClass::Deactivate(); } + void EditorReflectionProbeComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) + { + if (!m_controller.m_featureProcessor) + { + return; + } + + if (m_controller.m_configuration.m_useBakedCubemap) + { + AZStd::string cubeMapRelativePath = m_controller.m_configuration.m_bakedCubeMapRelativePath + ".streamingimage"; + Data::Asset cubeMapAsset; + CubeMapAssetNotificationType notificationType = CubeMapAssetNotificationType::None; + if (m_controller.m_featureProcessor->CheckCubeMapAssetNotification(cubeMapRelativePath, cubeMapAsset, notificationType)) + { + // a cubemap bake is in progress for this entity component + if (notificationType == CubeMapAssetNotificationType::Ready) + { + // bake is complete, update configuration with the new baked cubemap asset + m_controller.m_configuration.m_bakedCubeMapAsset = { cubeMapAsset.GetAs(), AZ::Data::AssetLoadBehavior::PreLoad }; + + // refresh the currently rendered cubemap + m_controller.UpdateCubeMap(); + + // update the UI + AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); + } + else if (notificationType == CubeMapAssetNotificationType::Error) + { + // cubemap bake failed + QMessageBox::information( + QApplication::activeWindow(), + "Reflection Probe", + "Reflection Probe cubemap failed to bake, please check the Asset Processor for more information.", + QMessageBox::Ok); + + // clear relative path, this will allow the user to retry + m_controller.m_configuration.m_bakedCubeMapRelativePath.clear(); + + // update the UI + AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); + } + } + } + } + void EditorReflectionProbeComponent::DisplayEntityViewport([[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { // only draw the bounds if selected @@ -276,122 +313,94 @@ namespace AZ return AZ::Edit::PropertyRefreshLevels::None; } - // callback from the EnvironmentCubeMapPass when the cubemap render is complete - BuildCubeMapCallback buildCubeMapCallback = [this](uint8_t* const* cubeMapFaceTextureData, const RHI::Format cubeMapTextureFormat) - { - if (!m_bakeInProgress) - { - // user canceled the bake - return; - } + char projectPath[AZ_MAX_PATH_LEN]; + AZ::IO::FileIOBase::GetInstance()->ResolvePath("@devassets@", projectPath, AZ_MAX_PATH_LEN); - char projectPath[AZ_MAX_PATH_LEN]; - AZ::IO::FileIOBase::GetInstance()->ResolvePath("@devassets@", projectPath, AZ_MAX_PATH_LEN); + // retrieve the source cubemap path from the configuration + // we need to make sure to use the same source cubemap for each bake + AZStd::string cubeMapRelativePath = m_controller.m_configuration.m_bakedCubeMapRelativePath; + AZStd::string cubeMapFullPath; - // retrieve the source cubemap path from the configuration - // we need to make sure to use the same source cubemap for each bake - AZStd::string cubeMapRelativePath = m_controller.m_configuration.m_bakedCubeMapRelativePath; - AZStd::string cubeMapFullPath; + if (!cubeMapRelativePath.empty()) + { + // test to see if the cubemap file is actually there, if it was removed we need to + // generate a new filename, otherwise it will cause an error in the asset system + AzFramework::StringFunc::Path::Join(projectPath, cubeMapRelativePath.c_str(), cubeMapFullPath, true, true); - if (!cubeMapRelativePath.empty()) + if (!AZ::IO::FileIOBase::GetInstance()->Exists(cubeMapFullPath.c_str())) { - // test to see if the cubemap file is actually there, if it was removed we need to - // generate a new filename, otherwise it will cause an error in the asset system - AzFramework::StringFunc::Path::Join(projectPath, cubeMapRelativePath.c_str(), cubeMapFullPath, true, true); - - if (!AZ::IO::FileIOBase::GetInstance()->Exists(cubeMapFullPath.c_str())) - { - // clear it to force the generation of a new filename - cubeMapRelativePath.clear(); - } + // clear it to force the generation of a new filename + cubeMapRelativePath.clear(); } + } - // build a new cubemap path if necessary - if (cubeMapRelativePath.empty()) - { - // the file name is a combination of the entity name, a UUID, and the filemask - Entity* entity = GetEntity(); - AZ_Assert(entity, "ReflectionProbe entity is null"); - - AZ::Uuid uuid = AZ::Uuid::CreateRandom(); - AZStd::string uuidString; - uuid.ToString(uuidString); + // build a new cubemap path if necessary + if (cubeMapRelativePath.empty()) + { + // the file name is a combination of the entity name, a UUID, and the filemask + Entity* entity = GetEntity(); + AZ_Assert(entity, "ReflectionProbe entity is null"); - cubeMapRelativePath = "ReflectionProbes/" + entity->GetName() + "_" + uuidString + "_iblspecularcm.dds"; + AZ::Uuid uuid = AZ::Uuid::CreateRandom(); + AZStd::string uuidString; + uuid.ToString(uuidString); - // replace any invalid filename characters - auto invalidCharacters = [](char letter) - { - return - letter == ':' || letter == '"' || letter == '\'' || - letter == '{' || letter == '}' || - letter == '<' || letter == '>'; - }; - AZStd::replace_if(cubeMapRelativePath.begin(), cubeMapRelativePath.end(), invalidCharacters, '_'); - - // build the full source path - AzFramework::StringFunc::Path::Join(projectPath, cubeMapRelativePath.c_str(), cubeMapFullPath, true, true); - } + cubeMapRelativePath = "ReflectionProbes/" + entity->GetName() + "_" + uuidString + "_iblspecularcm.dds"; - // make sure the folder is created - AZStd::string reflectionProbeFolder; - AzFramework::StringFunc::Path::GetFolderPath(cubeMapFullPath.data(), reflectionProbeFolder); - AZ::IO::SystemFile::CreateDir(reflectionProbeFolder.c_str()); - - // check out the file in source control - bool checkedOutSuccessfully = false; - using ApplicationBus = AzToolsFramework::ToolsApplicationRequestBus; - ApplicationBus::BroadcastResult( - checkedOutSuccessfully, - &ApplicationBus::Events::RequestEditForFileBlocking, - cubeMapFullPath.c_str(), - "Checking out for edit...", - ApplicationBus::Events::RequestEditProgressCallback()); - - if (!checkedOutSuccessfully) + // replace any invalid filename characters + auto invalidCharacters = [](char letter) { - AZ_Error("ReflectionProbe", false, "Failed to write \"%s\", source control checkout failed", cubeMapFullPath.c_str()); - } - - // write the cubemap data to the .dds file - WriteOutputFile(cubeMapFullPath.c_str(), cubeMapFaceTextureData, cubeMapTextureFormat); - - // save the relative source path in the configuration - AzToolsFramework::ScopedUndoBatch undoBatch("Cubemap path changed."); - m_controller.m_configuration.m_bakedCubeMapRelativePath = cubeMapRelativePath; - SetDirty(); - - // update UI cubemap path display - m_bakedCubeMapRelativePath = cubeMapRelativePath; + return + letter == ':' || letter == '"' || letter == '\'' || + letter == '{' || letter == '}' || + letter == '<' || letter == '>'; + }; + AZStd::replace_if(cubeMapRelativePath.begin(), cubeMapRelativePath.end(), invalidCharacters, '_'); - // call the feature processor to notify when the asset is created and ready - NotifyCubeMapAssetReadyCallback notifyCubeMapAssetReadyCallback = [this](const Data::Asset& cubeMapAsset, CubeMapAssetNotificationType notificationType) - { - // we only need to store the cubemap asset and update the cubemap image on the first bake of the probe, - // otherwise it is a hot-reload of an existing cubemap asset which is handled by the RPI - if (notificationType == CubeMapAssetNotificationType::Ready) - { - // update configuration with the new baked cubemap asset - m_controller.m_configuration.m_bakedCubeMapAsset = { cubeMapAsset.GetAs(), AZ::Data::AssetLoadBehavior::PreLoad }; + // build the full source path + AzFramework::StringFunc::Path::Join(projectPath, cubeMapRelativePath.c_str(), cubeMapFullPath, true, true); + } - // refresh the currently rendered cubemap - m_controller.UpdateCubeMap(); + // make sure the folder is created + AZStd::string reflectionProbeFolder; + AzFramework::StringFunc::Path::GetFolderPath(cubeMapFullPath.data(), reflectionProbeFolder); + AZ::IO::SystemFile::CreateDir(reflectionProbeFolder.c_str()); + + // check out the file in source control + bool checkedOutSuccessfully = false; + using ApplicationBus = AzToolsFramework::ToolsApplicationRequestBus; + ApplicationBus::BroadcastResult( + checkedOutSuccessfully, + &ApplicationBus::Events::RequestEditForFileBlocking, + cubeMapFullPath.c_str(), + "Checking out for edit...", + ApplicationBus::Events::RequestEditProgressCallback()); + + if (!checkedOutSuccessfully) + { + AZ_Error("ReflectionProbe", false, "Failed to write \"%s\", source control checkout failed", cubeMapFullPath.c_str()); + } - // update the UI - AzToolsFramework::PropertyEditorGUIMessages::Bus::Broadcast(&AzToolsFramework::PropertyEditorGUIMessages::RequestRefresh, AzToolsFramework::PropertyModificationRefreshLevel::Refresh_AttributesAndValues); - } + // save the relative source path in the configuration + AzToolsFramework::ScopedUndoBatch undoBatch("Cubemap path changed."); + m_controller.m_configuration.m_bakedCubeMapRelativePath = cubeMapRelativePath; + SetDirty(); - // signal completion - m_bakeInProgress = false; - }; + // update UI cubemap path display + m_bakedCubeMapRelativePath = cubeMapRelativePath; - AZStd::string cubeMapRelativeAssetPath = cubeMapRelativePath + ".streamingimage"; - m_controller.m_featureProcessor->NotifyCubeMapAssetReady(cubeMapRelativeAssetPath, notifyCubeMapAssetReadyCallback); + // callback from the EnvironmentCubeMapPass when the cubemap render is complete + BuildCubeMapCallback buildCubeMapCallback = [=](uint8_t* const* cubeMapFaceTextureData, const RHI::Format cubeMapTextureFormat) + { + // write the cubemap data to the .dds file + WriteOutputFile(cubeMapFullPath.c_str(), cubeMapFaceTextureData, cubeMapTextureFormat); + m_bakeInProgress = false; }; - // initiate the cubemap bake + // initiate the cubemap bake, this will invoke the buildCubeMapCallback when the cubemap data is ready m_bakeInProgress = true; - m_controller.BakeReflectionProbe(buildCubeMapCallback); + AZStd::string cubeMapRelativeAssetPath = cubeMapRelativePath + ".streamingimage"; + m_controller.BakeReflectionProbe(buildCubeMapCallback, cubeMapRelativeAssetPath); // show a dialog box letting the user know the probe is baking QProgressDialog bakeDialog; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h index eba9575ec4..23fd391818 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/EditorReflectionProbeComponent.h @@ -13,6 +13,7 @@ #pragma once #include +#include #include #include #include @@ -29,6 +30,7 @@ namespace AZ , public EditorReflectionProbeBus::Handler , private AzToolsFramework::EditorComponentSelectionRequestsBus::Handler , private AzFramework::EntityDebugDisplayEventBus::Handler + , private AZ::TickBus::Handler { public: using BaseClass = EditorRenderComponentAdapter; @@ -45,8 +47,12 @@ namespace AZ // AzFramework::EntityDebugDisplayEventBus::Handler overrides void DisplayEntityViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; + private: + // AZ::TickBus overrides + void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + // validation AZ::Outcome OnUseBakedCubemapValidate(void* newValue, const AZ::Uuid& valueType); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp index c7349adefa..59d1f7afa7 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.cpp @@ -111,6 +111,18 @@ namespace AZ m_boxShapeInterface = LmbrCentral::BoxShapeComponentRequestsBus::FindFirstHandler(m_entityId); AZ_Assert(m_boxShapeInterface, "ReflectionProbeComponentController was unable to find box shape component"); + // special handling is required if this component is being cloned in the editor: + // if this probe is using a baked cubemap, check to see if it is already referenced by another probe + if (m_configuration.m_useBakedCubemap) + { + if (m_featureProcessor->IsCubeMapReferenced(m_configuration.m_bakedCubeMapRelativePath)) + { + // clear the cubeMapRelativePath to prevent the newly cloned reflection probe + // from using the same cubemap path as the original reflection probe + m_configuration.m_bakedCubeMapRelativePath = ""; + } + } + // add this reflection probe to the feature processor const AZ::Transform& transform = m_transformInterface->GetWorldTM(); m_handle = m_featureProcessor->AddProbe(transform, m_configuration.m_useParallaxCorrection); @@ -130,12 +142,15 @@ namespace AZ m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapAsset : m_configuration.m_authoredCubeMapAsset; Data::AssetBus::MultiHandler::BusConnect(cubeMapAsset.GetId()); + const AZStd::string& relativePath = + m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapRelativePath : m_configuration.m_authoredCubeMapAsset.GetHint(); + if (cubeMapAsset.GetId().IsValid()) { if (cubeMapAsset.IsReady()) { Data::Instance image = RPI::StreamingImage::FindOrCreate(cubeMapAsset); - m_featureProcessor->SetProbeCubeMap(m_handle, image); + m_featureProcessor->SetProbeCubeMap(m_handle, image, relativePath); } else { @@ -169,8 +184,11 @@ namespace AZ return; } + const AZStd::string& relativePath = + m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapRelativePath : m_configuration.m_authoredCubeMapAsset.GetHint(); + Data::Instance image = RPI::StreamingImage::FindOrCreate(asset); - m_featureProcessor->SetProbeCubeMap(m_handle, image); + m_featureProcessor->SetProbeCubeMap(m_handle, image, relativePath); } void ReflectionProbeComponentController::SetConfiguration(const ReflectionProbeComponentConfig& config) @@ -188,8 +206,11 @@ namespace AZ Data::Asset& cubeMapAsset = m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapAsset : m_configuration.m_authoredCubeMapAsset; + const AZStd::string& relativePath = + m_configuration.m_useBakedCubemap ? m_configuration.m_bakedCubeMapRelativePath : m_configuration.m_authoredCubeMapAsset.GetHint(); + Data::Instance image = RPI::StreamingImage::FindOrCreate(cubeMapAsset); - m_featureProcessor->SetProbeCubeMap(m_handle, image); + m_featureProcessor->SetProbeCubeMap(m_handle, image, relativePath); } void ReflectionProbeComponentController::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world) @@ -240,14 +261,14 @@ namespace AZ m_configuration.m_innerHeight = AZStd::min(m_configuration.m_innerHeight, m_configuration.m_outerHeight); } - void ReflectionProbeComponentController::BakeReflectionProbe(BuildCubeMapCallback callback) + void ReflectionProbeComponentController::BakeReflectionProbe(BuildCubeMapCallback callback, const AZStd::string& relativePath) { if (!m_featureProcessor) { return; } - m_featureProcessor->BakeProbe(m_handle, callback); + m_featureProcessor->BakeProbe(m_handle, callback, relativePath); } AZ::Aabb ReflectionProbeComponentController::GetAabb() const diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h index 20d692145c..0a57fde882 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/ReflectionProbe/ReflectionProbeComponentController.h @@ -79,7 +79,7 @@ namespace AZ AZ::Aabb GetAabb() const; // initiate the reflection probe bake, invokes callback when complete - void BakeReflectionProbe(BuildCubeMapCallback callback); + void BakeReflectionProbe(BuildCubeMapCallback callback, const AZStd::string& relativePath); // update the currently rendering cubemap asset for this probe void UpdateCubeMap(); From 3df5f53e5ee465cc3f8f580a9d18095300d8c9d1 Mon Sep 17 00:00:00 2001 From: balibhan Date: Tue, 4 May 2021 15:16:31 +0530 Subject: [PATCH 066/185] 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 70bd3ea0ff0c877d866008a9f5d298aad8b1c6a3 Mon Sep 17 00:00:00 2001 From: Aaron Ruiz Mora Date: Tue, 4 May 2021 12:09:56 +0100 Subject: [PATCH 067/185] Performance pass to Cloth CPU Skinning - Added operator+(Matrix3x4), operator*(float), RetrieveScaleSq and GetReciprocalScaled to Matrix3x4. Used by Cloth CPU Linear Skinning. These operation will be performant as they use SIMD. - Modified so there are no virtual functions calls at vertex level. - Caching indices to simplify the loop when applying skinning. - Caching static variables Matrix3x4 zero and DualQuaternion zero to avoid creating it for every vertex. - Removing branching to skip joints when the weight is zero, these cases are rarely and this improves performance by removing branching from loops at vertex level. - Changing skinning influences so it's a continuous block of memory. - Caching the vector size() if a variable instead of directly using it in a for loop. --- Code/Framework/AzCore/AzCore/Math/Matrix3x4.h | 18 + .../AzCore/AzCore/Math/Matrix3x4.inl | 51 +++ .../AzCore/Tests/Math/Matrix3x4Tests.cpp | 60 +++ .../ClothComponentMesh/ActorClothSkinning.cpp | 365 ++++++++++-------- .../ClothComponentMesh/ActorClothSkinning.h | 51 ++- .../ClothComponentMesh/ClothComponentMesh.cpp | 15 +- .../ActorClothSkinningTest.cpp | 24 +- 7 files changed, 381 insertions(+), 203 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h index 8773d4ea6a..09f443c1cf 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h @@ -231,6 +231,18 @@ namespace AZ //! Compound assignment operator for matrix-matrix multiplication. Matrix3x4& operator*=(const Matrix3x4& rhs); + //! Operator for matrix-matrix addition. + [[nodiscard]] Matrix3x4 operator+(const Matrix3x4& rhs) const; + + //! Compound assignment operator for matrix-matrix addition. + Matrix3x4& operator+=(const Matrix3x4& rhs); + + //! Operator for multiplying all matrix's elements with a scalar + [[nodiscard]] Matrix3x4 operator*(float scalar) const; + + //! Compound assignment operator for multiplying all matrix's elements with a scalar + Matrix3x4& operator*=(float scalar); + //! Operator for transforming a Vector3. [[nodiscard]] Vector3 operator*(const Vector3& rhs) const; @@ -274,12 +286,18 @@ namespace AZ //! Gets the scale part of the transformation (the length of the basis vectors). [[nodiscard]] Vector3 RetrieveScale() const; + //! Gets the squared scale part of the transformation (the squared length of the basis vectors). + [[nodiscard]] Vector3 RetrieveScaleSq() const; + //! Gets the scale part of the transformation as in RetrieveScale, and also removes this scaling from the matrix. Vector3 ExtractScale(); //! Multiplies the basis vectors of the matrix by the elements of the scale specified. void MultiplyByScale(const Vector3& scale); + //! Returns a matrix with the reciprocal scale, keeping the same rotation and translation. + [[nodiscard]] Matrix3x4 GetReciprocalScaled() const; + //! Tests if the 3x3 part of the matrix is orthogonal. bool IsOrthogonal(float tolerance = Constants::Tolerance) const; diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl index bd310d293e..232e8a5b30 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl @@ -487,6 +487,43 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator+(const Matrix3x4& rhs) const + { + return Matrix3x4 + ( + Simd::Vec4::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec4::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec4::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) + ); + } + + + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator+=(const Matrix3x4& rhs) + { + *this = *this + rhs; + return *this; + } + + + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator*(float scalar) const + { + const Vector4 vector4Scalar(scalar); + return Matrix3x4 + ( + Simd::Vec4::Mul(m_rows[0].GetSimdValue(), vector4Scalar.GetSimdValue()), + Simd::Vec4::Mul(m_rows[1].GetSimdValue(), vector4Scalar.GetSimdValue()), + Simd::Vec4::Mul(m_rows[2].GetSimdValue(), vector4Scalar.GetSimdValue()) + ); + } + + + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator*=(float scalar) + { + *this = *this * scalar; + return *this; + } + + AZ_MATH_INLINE Vector3 Matrix3x4::operator*(const Vector3& rhs) const { return Vector3 @@ -583,6 +620,12 @@ namespace AZ } + AZ_MATH_INLINE Vector3 Matrix3x4::RetrieveScaleSq() const + { + return Vector3(GetColumn(0).GetLengthSq(), GetColumn(1).GetLengthSq(), GetColumn(2).GetLengthSq()); + } + + AZ_MATH_INLINE Vector3 Matrix3x4::ExtractScale() { const Vector3 scale = RetrieveScale(); @@ -600,6 +643,14 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x4 Matrix3x4::GetReciprocalScaled() const + { + Matrix3x4 result = *this; + result.MultiplyByScale(RetrieveScaleSq().GetReciprocal()); + return result; + } + + AZ_MATH_INLINE void Matrix3x4::Orthogonalize() { *this = GetOrthogonalized(); diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp index f61b633fc2..353b46874b 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp @@ -484,6 +484,38 @@ namespace UnitTest EXPECT_TRUE(matrix5.IsClose(matrix1 * matrix4)); } + TEST(MATH_Matrix3x4, AddMatrix3x4) + { + const AZ::Matrix3x4 matrix1 = AZ::Matrix3x4::CreateFromValue(1.2f); + const AZ::Matrix3x4 matrix2 = AZ::Matrix3x4::CreateDiagonal(AZ::Vector3(1.3f, 1.5f, 0.4f)); + const AZ::Matrix3x4 matrix3 = AZ::Matrix3x4::CreateFromQuaternionAndTranslation( + AZ::Quaternion(0.42f, 0.46f, -0.66f, 0.42f), AZ::Vector3(2.8f, -3.7f, 1.6f)); + const AZ::Matrix3x4 matrix4 = AZ::Matrix3x4::CreateRotationX(-0.7f) * AZ::Matrix3x4::CreateScale(AZ::Vector3(0.6f, 1.3f, 0.7f)); + AZ::Matrix3x4 matrix5 = matrix1; + matrix5 += matrix4; + EXPECT_THAT(matrix1 + (matrix2 + matrix3), IsClose((matrix1 + matrix2) + matrix3)); + EXPECT_THAT(matrix2 + AZ::Matrix3x4::CreateZero(), IsClose(matrix2)); + EXPECT_THAT(matrix3 + AZ::Matrix3x4::CreateZero(), IsClose(AZ::Matrix3x4::CreateZero() + matrix3)); + EXPECT_THAT(matrix3 + matrix3, IsClose(matrix3 * 2.0f)); + EXPECT_THAT(matrix5, IsClose(matrix1 + matrix4)); + } + + TEST(MATH_Matrix3x4, MultiplyByScalar) + { + const AZ::Vector4 row0(1.488f, 2.56f, 0.096f, 2.3f); + const AZ::Vector4 row1(0.384f, -1.92f, 0.428f, -1.6f); + const AZ::Vector4 row2(1.28f, -2.4f, -0.24f, 3.7f); + const float scalar = 3.2f; + const AZ::Vector4 row0Result = row0 * scalar; + const AZ::Vector4 row1Result = row1 * scalar; + const AZ::Vector4 row2Result = row2 * scalar; + AZ::Matrix3x4 matrix = AZ::Matrix3x4::CreateFromRows(row0, row1, row2); + EXPECT_THAT(matrix * 0.0f, IsClose(AZ::Matrix3x4::CreateZero())); + EXPECT_THAT(matrix * 1.0f, IsClose(matrix)); + EXPECT_THAT(matrix * scalar, IsClose(AZ::Matrix3x4::CreateFromRows(row0Result, row1Result, row2Result))); + EXPECT_THAT(matrix * 2.0f, IsClose(matrix + matrix)); + } + TEST(MATH_Matrix3x4, MultiplyByVector3) { const AZ::Vector4 row0(1.488f, 2.56f, 0.096f, 2.3f); @@ -652,6 +684,34 @@ namespace UnitTest EXPECT_THAT(scaledMatrix.RetrieveScale(), IsClose(AZ::Vector3::CreateOne())); } + TEST_P(Matrix3x4ScaleFixture, ScaleSq) + { + const AZ::Matrix3x4 orthogonalMatrix = GetParam(); + EXPECT_THAT(orthogonalMatrix.RetrieveScaleSq(), IsClose(AZ::Vector3::CreateOne())); + AZ::Matrix3x4 unscaledMatrix = orthogonalMatrix; + unscaledMatrix.ExtractScale(); + EXPECT_THAT(unscaledMatrix.RetrieveScaleSq(), IsClose(AZ::Vector3::CreateOne())); + const AZ::Vector3 scale(2.8f, 0.7f, 1.3f); + AZ::Matrix3x4 scaledMatrix = orthogonalMatrix; + scaledMatrix.MultiplyByScale(scale); + EXPECT_THAT(scaledMatrix.RetrieveScaleSq(), IsClose(scale * scale)); + EXPECT_THAT(scaledMatrix.RetrieveScaleSq(), IsClose(scaledMatrix.RetrieveScale() * scaledMatrix.RetrieveScale())); + scaledMatrix.ExtractScale(); + EXPECT_THAT(scaledMatrix.RetrieveScaleSq(), IsClose(AZ::Vector3::CreateOne())); + } + + TEST_P(Matrix3x4ScaleFixture, GetReciprocalScaled) + { + const AZ::Matrix3x4 orthogonalMatrix = GetParam(); + EXPECT_THAT(orthogonalMatrix.GetReciprocalScaled(), IsClose(orthogonalMatrix)); + const AZ::Vector3 scale(2.8f, 0.7f, 1.3f); + AZ::Matrix3x4 scaledMatrix = orthogonalMatrix; + scaledMatrix.MultiplyByScale(scale); + AZ::Matrix3x4 reciprocalScaledMatrix = orthogonalMatrix; + reciprocalScaledMatrix.MultiplyByScale(scale.GetReciprocal()); + EXPECT_THAT(scaledMatrix.GetReciprocalScaled(), IsClose(reciprocalScaledMatrix)); + } + INSTANTIATE_TEST_CASE_P(MATH_Matrix3x4, Matrix3x4ScaleFixture, ::testing::ValuesIn(MathTestData::OrthogonalMatrix3x4s)); TEST(MATH_Matrix3x4, IsOrthogonal) diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp index c295eca188..8f97b212a3 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.cpp @@ -27,11 +27,11 @@ namespace NvCloth { namespace Internal { - bool ObtainSkinningData( + bool ObtainSkinningInfluences( AZ::EntityId entityId, const MeshNodeInfo& meshNodeInfo, - const size_t numSimParticles, - AZStd::vector& skinningData) + const size_t numVertices, + AZStd::vector& skinningInfluences) { AZ::Data::Asset modelAsset; AZ::Render::MeshComponentRequestBus::EventResult( @@ -67,7 +67,7 @@ namespace NvCloth const auto& skinToSkeletonIndexMap = actor->GetSkinToSkeletonIndexMap(); - skinningData.resize(numSimParticles); + size_t numberOfInfluencesPerVertex = 0; // For each submesh... for (const auto& subMeshInfo : meshNodeInfo.m_subMeshes) @@ -98,28 +98,48 @@ namespace NvCloth if (sourceSkinJointIndices.empty() || sourceSkinWeights.empty()) { - continue; + // Ignoring skinning when there is no skin data. + // All submeshes will either have or not have skin data, since they come from the same mesh. + return false; } AZ_Assert(sourceSkinJointIndices.size() == sourceSkinWeights.size(), "Size of skin joint indices buffer (%zu) different from skin weights buffer (%zu)", sourceSkinJointIndices.size(), sourceSkinWeights.size()); - const size_t influenceCount = sourceSkinWeights.size() / sourcePositions.size(); - if (influenceCount == 0) + const size_t subMeshInfluenceCount = sourceSkinWeights.size() / sourcePositions.size(); + AZ_Assert(subMeshInfluenceCount > 0, + "Submesh %d skinning data has zero joint influences per vertex.", + subMeshInfo.m_primitiveIndex); + + if (numberOfInfluencesPerVertex == 0) { - continue; + // Resize only in the first loop once we know the number of influences per vertex. + // The other submeshes should match the number of influences. + numberOfInfluencesPerVertex = subMeshInfluenceCount; + skinningInfluences.resize(numVertices * numberOfInfluencesPerVertex); + } + else if (subMeshInfluenceCount != numberOfInfluencesPerVertex) + { + AZ_Error("ActorClothSkinning", false, + "Submesh %d number of influences (%d) is different from a previous submesh (%d).", + subMeshInfo.m_primitiveIndex, + subMeshInfluenceCount, + numberOfInfluencesPerVertex); + return false; } for (int vertexIndex = 0; vertexIndex < subMeshInfo.m_numVertices; ++vertexIndex) { - SkinningInfo& skinningInfo = skinningData[subMeshInfo.m_verticesFirstIndex + vertexIndex]; - skinningInfo.m_jointIndices.resize(influenceCount); - skinningInfo.m_jointWeights.resize(influenceCount); + const size_t subMeshVertexIndex = vertexIndex * numberOfInfluencesPerVertex; + const size_t meshVertexIndex = (subMeshInfo.m_verticesFirstIndex + vertexIndex) * numberOfInfluencesPerVertex; - for (size_t influenceIndex = 0; influenceIndex < influenceCount; ++influenceIndex) + for (size_t influenceIndex = 0; influenceIndex < numberOfInfluencesPerVertex; ++influenceIndex) { - const AZ::u16 jointIndex = sourceSkinJointIndices[vertexIndex * influenceCount + influenceIndex]; - const float weight = sourceSkinWeights[vertexIndex * influenceCount + influenceIndex]; + const size_t subMeshVertexInfluenceIndex = subMeshVertexIndex + influenceIndex; + const size_t meshVertexInfluenceIndex = meshVertexIndex + influenceIndex; + + const AZ::u16 jointIndex = sourceSkinJointIndices[subMeshVertexInfluenceIndex]; + const float weight = sourceSkinWeights[subMeshVertexInfluenceIndex]; auto skeletonIndexIt = skinToSkeletonIndexMap.find(jointIndex); if (skeletonIndexIt == skinToSkeletonIndexMap.end()) @@ -130,8 +150,8 @@ namespace NvCloth return false; } - skinningInfo.m_jointIndices[influenceIndex] = skeletonIndexIt->second; - skinningInfo.m_jointWeights[influenceIndex] = weight; + skinningInfluences[meshVertexInfluenceIndex].m_jointIndex = skeletonIndexIt->second; + skinningInfluences[meshVertexInfluenceIndex].m_jointWeight = weight; } } } @@ -198,17 +218,21 @@ namespace NvCloth { } - protected: // ActorClothSkinning overrides ... void UpdateSkinning() override; - bool HasSkinningTransformData() override; - void ComputeVertexSkinnningTransform(const SkinningInfo& skinningInfo) override; - AZ::Vector3 ComputeSkinningPosition(const AZ::Vector3& originalPosition) override; - AZ::Vector3 ComputeSkinningVector(const AZ::Vector3& originalVector) override; + void ApplySkinning( + const AZStd::vector& originalPositions, + AZStd::vector& positions) override; + void ApplySkinningOnNonSimulatedVertices( + const MeshClothInfo& originalData, + ClothComponentMesh::RenderData& renderData) override; private: + AZ::Matrix3x4 ComputeVertexSkinnningTransform(AZ::u32 vertexIndex); + const AZ::Matrix3x4* m_skinningMatrices = nullptr; - AZ::Matrix3x4 m_vertexSkinningTransform = AZ::Matrix3x4::CreateIdentity(); + + inline static const AZ::Matrix3x4 s_zeroMatrix3x4 = AZ::Matrix3x4::CreateZero(); }; void ActorClothSkinningLinear::UpdateSkinning() @@ -218,41 +242,75 @@ namespace NvCloth m_skinningMatrices = Internal::ObtainSkinningMatrices(m_entityId); } - bool ActorClothSkinningLinear::HasSkinningTransformData() + void ActorClothSkinningLinear::ApplySkinning( + const AZStd::vector& originalPositions, + AZStd::vector& positions) { - return m_skinningMatrices != nullptr; + if (!m_skinningMatrices || + originalPositions.empty() || + originalPositions.size() != positions.size() || + originalPositions.size() != m_simulatedVertices.size()) + { + return; + } + + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + + const size_t vertexCount = m_simulatedVertices.size(); + for (size_t index = 0; index < vertexCount; ++index) + { + const AZ::Matrix3x4 vertexSkinningTransform = ComputeVertexSkinnningTransform(m_simulatedVertices[index]); + + const AZ::Vector3 skinnedPosition = vertexSkinningTransform * originalPositions[index].GetAsVector3(); + positions[index].Set(skinnedPosition, positions[index].GetW()); // Avoid overwriting the w component + } } - void ActorClothSkinningLinear::ComputeVertexSkinnningTransform(const SkinningInfo& skinningInfo) + void ActorClothSkinningLinear::ApplySkinningOnNonSimulatedVertices( + const MeshClothInfo& originalData, + ClothComponentMesh::RenderData& renderData) { - m_vertexSkinningTransform = AZ::Matrix3x4::CreateZero(); - for (size_t weightIndex = 0; weightIndex < skinningInfo.m_jointWeights.size(); ++weightIndex) + if (!m_skinningMatrices || + originalData.m_particles.empty() || + originalData.m_particles.size() != renderData.m_particles.size() || + originalData.m_particles.size() != m_skinningInfluences.size() / m_numberOfInfluencesPerVertex) { - const AZ::u16 jointIndex = skinningInfo.m_jointIndices[weightIndex]; - const float jointWeight = skinningInfo.m_jointWeights[weightIndex]; + return; + } - if (AZ::IsClose(jointWeight, 0.0f)) - { - continue; - } + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); - // Blending matrices the same way done in GPU shaders, by adding each weighted matrix element by element. - // This way the skinning results are much similar to the skinning performed in GPU. - for (int i = 0; i < 3; ++i) - { - m_vertexSkinningTransform.SetRow(i, m_vertexSkinningTransform.GetRow(i) + m_skinningMatrices[jointIndex].GetRow(i) * jointWeight); - } + for (const AZ::u32 index : m_nonSimulatedVertices) + { + const AZ::Matrix3x4 vertexSkinningTransform = ComputeVertexSkinnningTransform(index); + + const AZ::Vector3 skinnedPosition = vertexSkinningTransform * originalData.m_particles[index].GetAsVector3(); + renderData.m_particles[index].Set(skinnedPosition, renderData.m_particles[index].GetW()); // Avoid overwriting the w component + + // Calculate the reciprocal scale version of the matrix to transform the vectors. + const AZ::Matrix3x4 vertexSkinningTransformReciprocalScale = vertexSkinningTransform.GetReciprocalScaled(); + + renderData.m_tangents[index] = vertexSkinningTransformReciprocalScale.TransformVector(originalData.m_tangents[index]).GetNormalized(); + renderData.m_bitangents[index] = vertexSkinningTransformReciprocalScale.TransformVector(originalData.m_bitangents[index]).GetNormalized(); + renderData.m_normals[index] = vertexSkinningTransformReciprocalScale.TransformVector(originalData.m_normals[index]).GetNormalized(); } } - AZ::Vector3 ActorClothSkinningLinear::ComputeSkinningPosition(const AZ::Vector3& originalPosition) + AZ::Matrix3x4 ActorClothSkinningLinear::ComputeVertexSkinnningTransform(AZ::u32 vertexIndex) { - return m_vertexSkinningTransform * originalPosition; - } + AZ::Matrix3x4 vertexSkinningTransform = s_zeroMatrix3x4; + for (size_t influenceIndex = 0; influenceIndex < m_numberOfInfluencesPerVertex; ++influenceIndex) + { + const size_t vertexInfluenceIndex = vertexIndex * m_numberOfInfluencesPerVertex + influenceIndex; - AZ::Vector3 ActorClothSkinningLinear::ComputeSkinningVector(const AZ::Vector3& originalVector) - { - return (m_vertexSkinningTransform * AZ::Vector4::CreateFromVector3AndFloat(originalVector, 0.0f)).GetAsVector3().GetNormalized(); + const AZ::u16 jointIndex = m_skinningInfluences[vertexInfluenceIndex].m_jointIndex; + const float jointWeight = m_skinningInfluences[vertexInfluenceIndex].m_jointWeight; + + // Blending matrices the same way done in GPU shaders, by adding each weighted matrix element by element. + // This way the skinning results are much similar to the skinning performed in GPU. + vertexSkinningTransform += m_skinningMatrices[jointIndex] * jointWeight; + } + return vertexSkinningTransform; } // Specialized class that applies dual quaternion blending skinning @@ -265,17 +323,21 @@ namespace NvCloth { } - protected: // ActorClothSkinning overrides ... void UpdateSkinning() override; - bool HasSkinningTransformData() override; - void ComputeVertexSkinnningTransform(const SkinningInfo& skinningInfo) override; - AZ::Vector3 ComputeSkinningPosition(const AZ::Vector3& originalPosition) override; - AZ::Vector3 ComputeSkinningVector(const AZ::Vector3& originalVector) override; + void ApplySkinning( + const AZStd::vector& originalPositions, + AZStd::vector& positions) override; + void ApplySkinningOnNonSimulatedVertices( + const MeshClothInfo& originalData, + ClothComponentMesh::RenderData& renderData) override; private: + MCore::DualQuaternion ComputeVertexSkinnningTransform(AZ::u32 vertexIndex); + AZStd::unordered_map m_skinningDualQuaternions; - MCore::DualQuaternion m_vertexSkinningTransform; + + inline static const MCore::DualQuaternion s_zeroDualQuaternion = MCore::DualQuaternion(AZ::Quaternion::CreateZero(), AZ::Quaternion::CreateZero()); }; void ActorClothSkinningDualQuaternion::UpdateSkinning() @@ -285,55 +347,90 @@ namespace NvCloth m_skinningDualQuaternions = Internal::ObtainSkinningDualQuaternions(m_entityId, m_jointIndices); } - bool ActorClothSkinningDualQuaternion::HasSkinningTransformData() + void ActorClothSkinningDualQuaternion::ApplySkinning( + const AZStd::vector& originalPositions, + AZStd::vector& positions) { - return !m_skinningDualQuaternions.empty(); + if (m_skinningDualQuaternions.empty() || + originalPositions.empty() || + originalPositions.size() != positions.size() || + originalPositions.size() != m_simulatedVertices.size()) + { + return; + } + + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + + const size_t vertexCount = m_simulatedVertices.size(); + for (size_t index = 0; index < vertexCount; ++index) + { + const MCore::DualQuaternion vertexSkinningTransform = ComputeVertexSkinnningTransform(m_simulatedVertices[index]); + + const AZ::Vector3 skinnedPosition = vertexSkinningTransform.TransformPoint(originalPositions[index].GetAsVector3()); + positions[index].Set(skinnedPosition, positions[index].GetW()); // Avoid overwriting the w component + } } - void ActorClothSkinningDualQuaternion::ComputeVertexSkinnningTransform(const SkinningInfo& skinningInfo) + void ActorClothSkinningDualQuaternion::ApplySkinningOnNonSimulatedVertices( + const MeshClothInfo& originalData, + ClothComponentMesh::RenderData& renderData) { - m_vertexSkinningTransform = MCore::DualQuaternion(AZ::Quaternion::CreateZero(), AZ::Quaternion::CreateZero()); - for (size_t weightIndex = 0; weightIndex < skinningInfo.m_jointWeights.size(); ++weightIndex) + if (m_skinningDualQuaternions.empty() || + originalData.m_particles.empty() || + originalData.m_particles.size() != renderData.m_particles.size() || + originalData.m_particles.size() != m_skinningInfluences.size() / m_numberOfInfluencesPerVertex) { - const AZ::u16 jointIndex = skinningInfo.m_jointIndices[weightIndex]; - const float jointWeight = skinningInfo.m_jointWeights[weightIndex]; + return; + } - if (AZ::IsClose(jointWeight, 0.0f)) - { - continue; - } + AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + + for (const AZ::u32 index : m_nonSimulatedVertices) + { + const MCore::DualQuaternion vertexSkinningTransform = ComputeVertexSkinnningTransform(index); + + const AZ::Vector3 skinnedPosition = vertexSkinningTransform.TransformPoint(originalData.m_particles[index].GetAsVector3()); + renderData.m_particles[index].Set(skinnedPosition, renderData.m_particles[index].GetW()); // Avoid overwriting the w component + + // ComputeVertexSkinnningTransform is normalizing the dual quaternion, so it won't have scale + // and there is no need to compute the reciprocal scale version for transforming vectors. - m_vertexSkinningTransform += m_skinningDualQuaternions.at(jointIndex) * jointWeight; + renderData.m_tangents[index] = vertexSkinningTransform.TransformVector(originalData.m_tangents[index]).GetNormalized(); + renderData.m_bitangents[index] = vertexSkinningTransform.TransformVector(originalData.m_bitangents[index]).GetNormalized(); + renderData.m_normals[index] = vertexSkinningTransform.TransformVector(originalData.m_normals[index]).GetNormalized(); } - m_vertexSkinningTransform.Normalize(); } - AZ::Vector3 ActorClothSkinningDualQuaternion::ComputeSkinningPosition(const AZ::Vector3& originalPosition) + MCore::DualQuaternion ActorClothSkinningDualQuaternion::ComputeVertexSkinnningTransform(AZ::u32 vertexIndex) { - return m_vertexSkinningTransform.TransformPoint(originalPosition); - } + MCore::DualQuaternion vertexSkinningTransform = s_zeroDualQuaternion; + for (size_t influenceIndex = 0; influenceIndex < m_numberOfInfluencesPerVertex; ++influenceIndex) + { + const size_t vertexInfluenceIndex = vertexIndex * m_numberOfInfluencesPerVertex + influenceIndex; - AZ::Vector3 ActorClothSkinningDualQuaternion::ComputeSkinningVector(const AZ::Vector3& originalVector) - { - return m_vertexSkinningTransform.TransformVector(originalVector).GetNormalized(); + const AZ::u16 jointIndex = m_skinningInfluences[vertexInfluenceIndex].m_jointIndex; + const float jointWeight = m_skinningInfluences[vertexInfluenceIndex].m_jointWeight; + + const MCore::DualQuaternion& skinningDualQuaternion = m_skinningDualQuaternions.at(jointIndex); + + float flip = AZ::GetSign(vertexSkinningTransform.mReal.Dot(skinningDualQuaternion.mReal)); + vertexSkinningTransform += skinningDualQuaternion * jointWeight * flip; + } + // Normalizing the dual quaternion as the GPU shaders do. This will remove the scale from the transform. + vertexSkinningTransform.Normalize(); + return vertexSkinningTransform; } AZStd::unique_ptr ActorClothSkinning::Create( AZ::EntityId entityId, const MeshNodeInfo& meshNodeInfo, - const size_t numSimParticles) + const size_t numVertices, + const size_t numSimulatedVertices, + const AZStd::vector& meshRemappedVertices) { - AZStd::vector skinningData; - if (!Internal::ObtainSkinningData(entityId, meshNodeInfo, numSimParticles, skinningData)) - { - return nullptr; - } - - if (numSimParticles != skinningData.size()) + AZStd::vector skinningInfluences; + if (!Internal::ObtainSkinningInfluences(entityId, meshNodeInfo, numVertices, skinningInfluences)) { - AZ_Error("ActorClothSkinning", false, - "Number of simulation particles (%zu) doesn't match with skinning data obtained (%zu)", - numSimParticles, skinningData.size()); return nullptr; } @@ -355,97 +452,47 @@ namespace NvCloth return nullptr; } - // Insert the indices of the joints that influence the particle (weight is not 0) - AZStd::set jointIndices; - for (size_t particleIndex = 0; particleIndex < numSimParticles; ++particleIndex) + actorClothSkinning->m_numberOfInfluencesPerVertex = skinningInfluences.size() / numVertices; + if (actorClothSkinning->m_numberOfInfluencesPerVertex == 0) { - const SkinningInfo& skinningInfo = skinningData[particleIndex]; - for (size_t weightIndex = 0; weightIndex < skinningInfo.m_jointWeights.size(); ++weightIndex) - { - const AZ::u16 jointIndex = skinningInfo.m_jointIndices[weightIndex]; - const float jointWeight = skinningInfo.m_jointWeights[weightIndex]; - - if (AZ::IsClose(jointWeight, 0.0f)) - { - continue; - } - - jointIndices.insert(jointIndex); - } + AZ_Error("ActorClothSkinning", false, + "Number of skinning joint influences per vertex is zero."); + return nullptr; } - actorClothSkinning->m_jointIndices.assign(jointIndices.begin(), jointIndices.end()); - actorClothSkinning->m_skinningData = AZStd::move(skinningData); - - return actorClothSkinning; - } - - ActorClothSkinning::ActorClothSkinning(AZ::EntityId entityId) - : m_entityId(entityId) - { - } - - void ActorClothSkinning::ApplySkinning( - const AZStd::vector& originalPositions, - AZStd::vector& positions, - const AZStd::vector& meshRemappedVertices) - { - if (!HasSkinningTransformData() || - originalPositions.empty() || - originalPositions.size() != positions.size() || - m_skinningData.size() != meshRemappedVertices.size()) + // Collect all indices of the joints that influence the vertices + AZStd::set jointIndices; + for (const auto& skinningInfluence : skinningInfluences) { - return; + jointIndices.insert(skinningInfluence.m_jointIndex); } + actorClothSkinning->m_jointIndices.assign(jointIndices.begin(), jointIndices.end()); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); - - AZStd::unordered_set skinnedIndices; - for (size_t index = 0; index < meshRemappedVertices.size(); ++index) + // Collect the indices for simulated and non-simulated vertices + actorClothSkinning->m_simulatedVertices.resize(numSimulatedVertices); + actorClothSkinning->m_nonSimulatedVertices.reserve(numVertices); + for (size_t vertexIndex = 0; vertexIndex < numVertices; ++vertexIndex) { - const int remappedIndex = meshRemappedVertices[index]; - if (remappedIndex >= 0 && !skinnedIndices.contains(remappedIndex)) + const int remappedIndex = meshRemappedVertices[vertexIndex]; + if (remappedIndex >= 0) { - ComputeVertexSkinnningTransform(m_skinningData[index]); - - const AZ::Vector3 skinnedPosition = ComputeSkinningPosition(originalPositions[remappedIndex].GetAsVector3()); - positions[remappedIndex].Set(skinnedPosition, positions[remappedIndex].GetW()); // Avoid overwriting the w component - - skinnedIndices.emplace(remappedIndex); // Avoid computing this index again + actorClothSkinning->m_simulatedVertices[remappedIndex] = vertexIndex; + } + else + { + actorClothSkinning->m_nonSimulatedVertices.emplace_back(vertexIndex); } } - } - - void ActorClothSkinning::ApplySkinninOnRemovedVertices( - const MeshClothInfo& originalData, - ClothComponentMesh::RenderData& renderData, - const AZStd::vector& meshRemappedVertices) - { - if (!HasSkinningTransformData() || - originalData.m_particles.empty() || - originalData.m_particles.size() != renderData.m_particles.size() || - originalData.m_particles.size() != m_skinningData.size() || - m_skinningData.size() != meshRemappedVertices.size()) - { - return; - } + actorClothSkinning->m_nonSimulatedVertices.shrink_to_fit(); - AZ_PROFILE_FUNCTION(AZ::Debug::ProfileCategory::Cloth); + actorClothSkinning->m_skinningInfluences = AZStd::move(skinningInfluences); - for (size_t index = 0; index < originalData.m_particles.size(); ++index) - { - if (meshRemappedVertices[index] < 0) - { - ComputeVertexSkinnningTransform(m_skinningData[index]); - - const AZ::Vector3 skinnedPosition = ComputeSkinningPosition(originalData.m_particles[index].GetAsVector3()); - renderData.m_particles[index].Set(skinnedPosition, renderData.m_particles[index].GetW()); // Avoid overwriting the w component + return actorClothSkinning; + } - renderData.m_tangents[index] = ComputeSkinningVector(originalData.m_tangents[index]); - renderData.m_bitangents[index] = ComputeSkinningVector(originalData.m_bitangents[index]); - renderData.m_normals[index] = ComputeSkinningVector(originalData.m_normals[index]); - } - } + ActorClothSkinning::ActorClothSkinning(AZ::EntityId entityId) + : m_entityId(entityId) + { } void ActorClothSkinning::UpdateActorVisibility() diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.h b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.h index 8cf139c75a..01df1f87ef 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.h +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ActorClothSkinning.h @@ -12,6 +12,7 @@ #pragma once +#include #include #include @@ -22,14 +23,14 @@ namespace NvCloth { struct MeshNodeInfo; - //! Skinning information of a particle. - struct SkinningInfo + //! One skinning influence of a vertex. + struct SkinningInfluence { - //! Weights of each joint that influence the particle. - AZStd::vector m_jointWeights; + //! Weight of the joint that influences the vertex. + float m_jointWeight = 0.0f; - //! List of joints that influence the particle. - AZStd::vector m_jointIndices; + //! Index of the joint that influences the vertex. + AZ::u16 m_jointIndex = AZStd::numeric_limits::max(); }; //! Class to retrieve skinning information from an actor on the same entity @@ -44,7 +45,9 @@ namespace NvCloth static AZStd::unique_ptr Create( AZ::EntityId entityId, const MeshNodeInfo& meshNodeInfo, - const size_t numSimParticles); + const size_t numVertices, + const size_t numSimulatedVertices, + const AZStd::vector& meshRemappedVertices); explicit ActorClothSkinning(AZ::EntityId entityId); @@ -53,17 +56,15 @@ namespace NvCloth //! Applies skinning to a list of positions. //! @note w components are not affected. - void ApplySkinning( + virtual void ApplySkinning( const AZStd::vector& originalPositions, - AZStd::vector& positions, - const AZStd::vector& meshRemappedVertices); + AZStd::vector& positions) = 0; //! Applies skinning to a list of positions and vectors whose vertices - //! have not been used for simulation (remapped index is negative). - void ApplySkinninOnRemovedVertices( + //! have not been used for simulation. + virtual void ApplySkinningOnNonSimulatedVertices( const MeshClothInfo& originalData, - ClothComponentMesh::RenderData& renderData, - const AZStd::vector& meshRemappedVertices); + ClothComponentMesh::RenderData& renderData) = 0; //! Updates visibility variables. void UpdateActorVisibility(); @@ -75,24 +76,20 @@ namespace NvCloth bool WasActorVisible() const; protected: - //! Returns true if it has valid skinning trasform data. - virtual bool HasSkinningTransformData() = 0; - - //! Computes the skinnning transformation to apply to a vertex data. - virtual void ComputeVertexSkinnningTransform(const SkinningInfo& skinningInfo) = 0; + AZ::EntityId m_entityId; - //! Computes skinning on a position. - virtual AZ::Vector3 ComputeSkinningPosition(const AZ::Vector3& originalPosition) = 0; + size_t m_numberOfInfluencesPerVertex = 0; - //! Computes skinning on a vector. - virtual AZ::Vector3 ComputeSkinningVector(const AZ::Vector3& originalVector) = 0; + // Skinning influences of all vertices + AZStd::vector m_skinningInfluences; - AZ::EntityId m_entityId; + // Indices to skinning influences that are part of the simulation + AZStd::vector m_simulatedVertices; - // Skinning information of all particles - AZStd::vector m_skinningData; + // Indices to skinning influences that are not part of the simulation + AZStd::vector m_nonSimulatedVertices; - // Collection of skeleton joint indices that influence the particles + // Collection of skeleton joint indices that influence the vertices AZStd::vector m_jointIndices; // Visibility variables diff --git a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp index 740518b61a..52c93ea672 100644 --- a/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp +++ b/Gems/NvCloth/Code/Source/Components/ClothComponentMesh/ClothComponentMesh.cpp @@ -184,7 +184,12 @@ namespace NvCloth m_actorClothColliders = ActorClothColliders::Create(m_entityId); // It will return a valid instance if it's an actor with skinning data. - m_actorClothSkinning = ActorClothSkinning::Create(m_entityId, m_meshNodeInfo, m_meshClothInfo.m_particles.size()); + m_actorClothSkinning = ActorClothSkinning::Create( + m_entityId, + m_meshNodeInfo, + m_meshClothInfo.m_particles.size(), + m_cloth->GetParticles().size(), + m_meshRemappedVertices); m_numberOfClothSkinningUpdates = 0; m_clothConstraints = ClothConstraints::Create( @@ -363,7 +368,7 @@ namespace NvCloth { // Update skinning for all particles and apply it to cloth AZStd::vector particles = m_cloth->GetParticles(); - m_actorClothSkinning->ApplySkinning(m_cloth->GetInitialParticles(), particles, m_meshRemappedVertices); + m_actorClothSkinning->ApplySkinning(m_cloth->GetInitialParticles(), particles); m_cloth->SetParticles(AZStd::move(particles)); m_cloth->DiscardParticleDelta(); } @@ -379,8 +384,8 @@ namespace NvCloth if (m_actorClothSkinning) { - m_actorClothSkinning->ApplySkinning(m_clothConstraints->GetMotionConstraints(), m_motionConstraints, m_meshRemappedVertices); - m_actorClothSkinning->ApplySkinning(m_clothConstraints->GetSeparationConstraints(), m_separationConstraints, m_meshRemappedVertices); + m_actorClothSkinning->ApplySkinning(m_clothConstraints->GetMotionConstraints(), m_motionConstraints); + m_actorClothSkinning->ApplySkinning(m_clothConstraints->GetSeparationConstraints(), m_separationConstraints); } m_cloth->GetClothConfigurator()->SetMotionConstraints(m_motionConstraints); @@ -404,7 +409,7 @@ namespace NvCloth if (m_config.m_removeStaticTriangles && m_actorClothSkinning) { // Apply skinning to the non-simulated part of the mesh. - m_actorClothSkinning->ApplySkinninOnRemovedVertices(m_meshClothInfo, renderData, m_meshRemappedVertices); + m_actorClothSkinning->ApplySkinningOnNonSimulatedVertices(m_meshClothInfo, renderData); } // Calculate normals of the cloth particles (simplified mesh). diff --git a/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ActorClothSkinningTest.cpp b/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ActorClothSkinningTest.cpp index 75cff2da04..3fba04f695 100644 --- a/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ActorClothSkinningTest.cpp +++ b/Gems/NvCloth/Code/Tests/Components/ClothComponentMesh/ActorClothSkinningTest.cpp @@ -98,7 +98,7 @@ namespace UnitTest { AZ::EntityId entityId; AZStd::unique_ptr actorClothSkinning = - NvCloth::ActorClothSkinning::Create(entityId, {}, 0); + NvCloth::ActorClothSkinning::Create(entityId, {}, 0, 0, {}); EXPECT_TRUE(actorClothSkinning.get() == nullptr); } @@ -107,7 +107,7 @@ namespace UnitTest { AZ::EntityId entityId; AZStd::unique_ptr actorClothSkinning = - NvCloth::ActorClothSkinning::Create(entityId, MeshNodeInfo, MeshRemappedVertices.size()); + NvCloth::ActorClothSkinning::Create(entityId, MeshNodeInfo, MeshVertices.size(), MeshVertices.size(), MeshRemappedVertices); EXPECT_TRUE(actorClothSkinning.get() == nullptr); } @@ -122,7 +122,7 @@ namespace UnitTest } AZStd::unique_ptr actorClothSkinning = - NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), {}, 0); + NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), {}, 0, 0, {}); EXPECT_TRUE(actorClothSkinning.get() == nullptr); } @@ -139,7 +139,7 @@ namespace UnitTest } AZStd::unique_ptr actorClothSkinning = - NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size()); + NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size(), MeshVertices.size(), MeshRemappedVertices); EXPECT_TRUE(actorClothSkinning.get() == nullptr); } @@ -156,7 +156,7 @@ namespace UnitTest } AZStd::unique_ptr actorClothSkinning = - NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size()); + NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size(), MeshVertices.size(), MeshRemappedVertices); EXPECT_TRUE(actorClothSkinning.get() != nullptr); } @@ -184,7 +184,7 @@ namespace UnitTest } AZStd::unique_ptr actorClothSkinning = - NvCloth::ActorClothSkinning::Create(actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size()); + NvCloth::ActorClothSkinning::Create(actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size(), MeshVertices.size(), MeshRemappedVertices); ASSERT_TRUE(actorClothSkinning.get() != nullptr); const AZStd::vector clothParticles = {{ @@ -195,7 +195,7 @@ namespace UnitTest AZStd::vector skinnedClothParticles(clothParticles.size(), NvCloth::SimParticleFormat(0.0f, 0.0f, 0.0f, 1.0f)); actorClothSkinning->UpdateSkinning(); - actorClothSkinning->ApplySkinning(clothParticles, skinnedClothParticles, MeshRemappedVertices); + actorClothSkinning->ApplySkinning(clothParticles, skinnedClothParticles); EXPECT_THAT(skinnedClothParticles, ::testing::Pointwise(ContainerIsCloseTolerance(Tolerance), clothParticles)); @@ -208,7 +208,7 @@ namespace UnitTest AZStd::vector newSkinnedClothParticles(clothParticles.size(), NvCloth::SimParticleFormat(0.0f, 0.0f, 0.0f, 1.0f)); actorClothSkinning->UpdateSkinning(); - actorClothSkinning->ApplySkinning(clothParticles, newSkinnedClothParticles, MeshRemappedVertices); + actorClothSkinning->ApplySkinning(clothParticles, newSkinnedClothParticles); const AZ::Transform diffTransform = AZ::Transform::CreateRotationY(AZ::DegToRad(90.0f)); const AZStd::vector clothParticlesResult = {{ @@ -245,7 +245,7 @@ namespace UnitTest } AZStd::unique_ptr actorClothSkinning = - NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size()); + NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size(), MeshVertices.size(), MeshRemappedVertices); ASSERT_TRUE(actorClothSkinning.get() != nullptr); const AZStd::vector clothParticles = {{ @@ -256,7 +256,7 @@ namespace UnitTest AZStd::vector skinnedClothParticles(clothParticles.size(), NvCloth::SimParticleFormat(0.0f, 0.0f, 0.0f, 1.0f)); actorClothSkinning->UpdateSkinning(); - actorClothSkinning->ApplySkinning(clothParticles, skinnedClothParticles, MeshRemappedVertices); + actorClothSkinning->ApplySkinning(clothParticles, skinnedClothParticles); EXPECT_THAT(skinnedClothParticles, ::testing::Pointwise(ContainerIsCloseTolerance(Tolerance), clothParticles)); @@ -271,7 +271,7 @@ namespace UnitTest AZStd::vector newSkinnedClothParticles(clothParticles.size(), NvCloth::SimParticleFormat(0.0f, 0.0f, 0.0f, 1.0f)); actorClothSkinning->UpdateSkinning(); - actorClothSkinning->ApplySkinning(clothParticles, newSkinnedClothParticles, MeshRemappedVertices); + actorClothSkinning->ApplySkinning(clothParticles, newSkinnedClothParticles); const AZStd::vector clothParticlesResult = {{ NvCloth::SimParticleFormat(-48.4177f, -31.9446f, 45.2279f, 1.0f), @@ -294,7 +294,7 @@ namespace UnitTest } AZStd::unique_ptr actorClothSkinning = - NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size()); + NvCloth::ActorClothSkinning::Create(m_actorComponent->GetEntityId(), MeshNodeInfo, MeshVertices.size(), MeshVertices.size(), MeshRemappedVertices); ASSERT_TRUE(actorClothSkinning.get() != nullptr); EXPECT_FALSE(actorClothSkinning->IsActorVisible()); From d705864f8882039492133cb1e3e29bb06bf303b8 Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 13:09:23 +0100 Subject: [PATCH 068/185] fix for input being 'stuck' on --- .../AzFramework/Viewport/CameraInput.cpp | 13 ++++++------- .../AzFramework/AzFramework/Viewport/CameraInput.h | 5 +++++ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 851522c701..069c9d5fc9 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -276,7 +276,7 @@ namespace AzFramework } else if (input->m_state == InputChannel::State::Ended) { - m_translation ^= translationFromKey(input->m_channelId); + m_translation &= ~(translationFromKey(input->m_channelId)); if (m_translation == TranslationType::Nil) { EndActivation(); @@ -521,20 +521,19 @@ namespace AzFramework return button == inputChannelId; }); - if (inputChannelId == InputDeviceMouse::SystemCursorPosition) + if (inputChannelId == InputDeviceMouse::Movement::X || inputChannelId == InputDeviceMouse::Movement::Y) { - AZ::Vector2 systemCursorPositionNormalized = AZ::Vector2::CreateZero(); - InputSystemCursorRequestBus::EventResult( - systemCursorPositionNormalized, inputDeviceId, &InputSystemCursorRequestBus::Events::GetSystemCursorPositionNormalized); + const auto* position = inputChannel.GetCustomData(); + AZ_Assert(position, "Expected PositionData2D but found nullptr"); return CursorMotionEvent{ScreenPoint( - systemCursorPositionNormalized.GetX() * windowSize.m_width, systemCursorPositionNormalized.GetY() * windowSize.m_height)}; + position->m_normalizedPosition.GetX() * windowSize.m_width, position->m_normalizedPosition.GetY() * windowSize.m_height)}; } else if (inputChannelId == InputDeviceMouse::Movement::Z) { return ScrollEvent{inputChannel.GetValue()}; } - else if ((InputDeviceMouse::IsMouseDevice(inputDeviceId) && wasMouseButton) || InputDeviceKeyboard::IsKeyboardDevice(inputDeviceId)) + else if (wasMouseButton || InputDeviceKeyboard::IsKeyboardDevice(inputDeviceId)) { return DiscreteInputEvent{inputChannelId, inputChannel.GetState()}; } diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index 4c076b887d..dee8bcd600 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -372,6 +372,11 @@ namespace AzFramework return lhs; } + friend TranslationType operator~(const TranslationType lhs) + { + return static_cast(~static_cast>(lhs)); + } + static TranslationType translationFromKey(InputChannelId channelId); TranslationType m_translation = TranslationType::Nil; From 16b16706b5a9e60fc0196f1b63f0fe93f3143266 Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 14:50:01 +0100 Subject: [PATCH 069/185] add logic to convert matrix3x3 to euler angles --- .../AzFramework/Viewport/CameraInput.cpp | 42 +++++++++++++++++++ .../AzFramework/Viewport/CameraInput.h | 5 +++ .../Editor/ModernViewportCameraController.cpp | 21 ++-------- 3 files changed, 50 insertions(+), 18 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 069c9d5fc9..46b2e48f81 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -24,6 +24,48 @@ AZ_CVAR( namespace AzFramework { + // Based on paper by David Eberly - https://www.geometrictools.com/Documentation/EulerAngles.pdf + AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation) + { + float x; + float y; + float z; + + // 2.4 Factor as RzRyRx + if (orientation.GetElement(2, 0) < 1.0f) + { + if (orientation.GetElement(2, 0) > -1.0f) + { + x = std::atan2(orientation.GetElement(2, 1), orientation.GetElement(2, 2)); + y = std::asin(-orientation.GetElement(2, 0)); + z = std::atan2(orientation.GetElement(1, 0), orientation.GetElement(0, 0)); + } + else + { + x = 0.0f; + y = AZ::Constants::Pi * 0.5f; + z = -std::atan2(-orientation.GetElement(2, 1), orientation.GetElement(1, 1)); + } + } + else + { + x = 0.0f; + y = -AZ::Constants::Pi * 0.5f; + z = std::atan2(-orientation.GetElement(1, 2), orientation.GetElement(1, 1)); + } + + return {x, y, z}; + } + + void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform) + { + const auto eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(transform)); + + camera.m_lookAt = transform.GetTranslation(); + camera.m_pitch = eulerAngles.GetX(); + camera.m_yaw = eulerAngles.GetZ(); + } + bool CameraSystem::HandleEvents(const InputEvent& event) { if (const auto& cursor_motion = AZStd::get_if(&event)) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index dee8bcd600..daad86ef81 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -43,6 +43,9 @@ namespace AzFramework using ModernViewportCameraControllerRequestBus = AZ::EBus; + // https://www.geometrictools.com/Documentation/EulerAngles.pdf + AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation); + struct Camera { AZ::Vector3 m_lookAt = AZ::Vector3::CreateZero(); //!< Position of camera when m_lookDist is zero, @@ -83,6 +86,8 @@ namespace AzFramework return Transform().GetTranslation(); } + void UpdateCameraFromTransform(Camera& camera, const AZ::Transform& transform); + struct CursorMotionEvent { ScreenPoint m_position; diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index f94f067a21..06d8ad286d 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -20,8 +20,6 @@ #include #include -AZ_CVAR(bool, ed_newCameraSystemDebug, false, nullptr, AZ::ConsoleFunctorFlags::Null, "Enable debug drawing for the new camera system"); - namespace SandboxEditor { static AZ::RPI::ViewportContextPtr RetrieveViewportContext(const AzFramework::ViewportId viewportId) @@ -68,16 +66,6 @@ namespace SandboxEditor m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); m_cameraSystem.m_cameras.AddCamera(orbitCamera); - if (const auto viewportContext = RetrieveViewportContext(viewportId)) - { - // set position but not orientation - m_targetCamera.m_lookAt = viewportContext->GetCameraTransform().GetTranslation(); - - // LYN-2315 TODO https://www.geometrictools.com/Documentation/EulerAngles.pdf - - m_camera = m_targetCamera; - } - AzFramework::ViewportDebugDisplayEventBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); AzFramework::ModernViewportCameraControllerRequestBus::Handler::BusConnect(viewportId); } @@ -111,15 +99,12 @@ namespace SandboxEditor void ModernViewportCameraControllerInstance::DisplayViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - if (ed_newCameraSystemDebug) - { - debugDisplay.SetColor(AZ::Colors::White); - debugDisplay.DrawWireSphere(m_targetCamera.m_lookAt, 0.5f); - } + debugDisplay.SetColor(1.0f, 1.0f, 1.0f, AZStd::min(-m_camera.m_lookDist / 5.0f, 1.0f)); + debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); } void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) { - m_targetCamera.m_lookAt = transform.GetTranslation(); + AzFramework::UpdateCameraFromTransform(m_targetCamera, transform); } } // namespace SandboxEditor From 9568cdd0f2cafb321b0a1a3bc3cf1407815ba584 Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 16:15:55 +0100 Subject: [PATCH 070/185] fix color drawing --- Code/Sandbox/Editor/ModernViewportCameraController.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 06d8ad286d..1334dae20c 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -89,8 +89,7 @@ namespace SandboxEditor if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); - m_camera = - AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); + m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); viewportContext->SetCameraTransform(m_camera.Transform()); } @@ -99,8 +98,11 @@ namespace SandboxEditor void ModernViewportCameraControllerInstance::DisplayViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { - debugDisplay.SetColor(1.0f, 1.0f, 1.0f, AZStd::min(-m_camera.m_lookDist / 5.0f, 1.0f)); - debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); + if (const float alpha = AZStd::min(-m_camera.m_lookDist / 5.0f, 1.0f); alpha > AZ::Constants::FloatEpsilon) + { + debugDisplay.SetColor(1.0f, 1.0f, 1.0f, alpha); + debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); + } } void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) From 14fc356d6e1d35b319b868e9e500427f9381904a Mon Sep 17 00:00:00 2001 From: hultonha Date: Fri, 30 Apr 2021 17:23:07 +0100 Subject: [PATCH 071/185] add animation camera behaviour to new controller (WIP) --- .../Editor/ModernViewportCameraController.cpp | 74 ++++++++++++++++++- .../Editor/ModernViewportCameraController.h | 11 +++ 2 files changed, 82 insertions(+), 3 deletions(-) diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 1334dae20c..571ae04997 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -22,6 +22,23 @@ namespace SandboxEditor { + static void DrawPreviewAxis( + AzFramework::DebugDisplayRequests& display, const AZ::Transform& transform, const float axisLength) + { + display.SetColor(AZ::Colors::Red); + display.DrawLine( + transform.GetTranslation(), + transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * axisLength); + display.SetColor(AZ::Colors::Green); + display.DrawLine( + transform.GetTranslation(), + transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * axisLength); + display.SetColor(AZ::Colors::Blue); + display.DrawLine( + transform.GetTranslation(), + transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength); + } + static AZ::RPI::ViewportContextPtr RetrieveViewportContext(const AzFramework::ViewportId viewportId) { auto viewportContextManager = AZ::Interface::Get(); @@ -81,6 +98,28 @@ namespace SandboxEditor AzFramework::WindowSize windowSize; AzFramework::WindowRequestBus::EventResult( windowSize, event.m_windowHandle, &AzFramework::WindowRequestBus::Events::GetClientAreaSize); + + if (m_cameraMode == CameraMode::Control) + { + if (AzFramework::InputDeviceKeyboard::IsKeyboardDevice(event.m_inputChannel.GetInputDevice().GetInputDeviceId())) + { + if (event.m_inputChannel.GetInputChannelId() == AzFramework::InputDeviceKeyboard::Key::AlphanumericR) + { + m_transformEnd = m_camera.Transform(); + + return true; + } + else if (event.m_inputChannel.GetInputChannelId() == AzFramework::InputDeviceKeyboard::Key::AlphanumericP) + { + m_animationT = 0.0f; + m_cameraMode = CameraMode::Animation; + m_transformStart = m_camera.Transform(); + + return true; + } + } + } + return m_cameraSystem.HandleEvents(AzFramework::BuildInputEvent(event.m_inputChannel, windowSize)); } @@ -88,10 +127,37 @@ namespace SandboxEditor { if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { - m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); - m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); + if (m_cameraMode == CameraMode::Control) + { + m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); + m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); + + viewportContext->SetCameraTransform(m_camera.Transform()); + } + else if (m_cameraMode == CameraMode::Animation) + { + const auto smootherStepFn = [](const float t) { return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); }; + const float transitionT = smootherStepFn(m_animationT); + + const AZ::Transform current = AZ::Transform::CreateFromQuaternionAndTranslation( + m_transformStart.GetRotation().Slerp(m_transformEnd.GetRotation(), transitionT), + m_transformStart.GetTranslation().Lerp(m_transformEnd.GetTranslation(), transitionT)); + + const AZ::Vector3 eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(current)); + m_camera.m_pitch = eulerAngles.GetX(); + m_camera.m_yaw = eulerAngles.GetZ(); + m_camera.m_lookAt = current.GetTranslation(); + m_targetCamera = m_camera; - viewportContext->SetCameraTransform(m_camera.Transform()); + if (m_animationT >= 1.0f) + { + m_cameraMode = CameraMode::Control; + } + + m_animationT = AZ::GetClamp(m_animationT + event.m_deltaTime.count(), 0.0f, 1.0f); + + viewportContext->SetCameraTransform(current); + } } } @@ -103,6 +169,8 @@ namespace SandboxEditor debugDisplay.SetColor(1.0f, 1.0f, 1.0f, alpha); debugDisplay.DrawWireSphere(m_camera.m_lookAt, 0.5f); } + + DrawPreviewAxis(debugDisplay, m_transformEnd, 2.0f); } void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index a3d4f8cea6..cbdcf5cd22 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -37,10 +37,21 @@ namespace SandboxEditor void SetTargetCameraTransform(const AZ::Transform& transform) override; private: + enum class CameraMode + { + Control, + Animation + }; + AzFramework::Camera m_camera; AzFramework::Camera m_targetCamera; AzFramework::SmoothProps m_smoothProps; AzFramework::CameraSystem m_cameraSystem; + + AZ::Transform m_transformStart; + AZ::Transform m_transformEnd; + float m_animationT = 0.0f; + CameraMode m_cameraMode = CameraMode::Control; }; using ModernViewportCameraController = AzFramework::MultiViewportController; From 36d502b560c0aa95409b796b0bfe95447e7d6a5b Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 13:53:18 +0100 Subject: [PATCH 072/185] update controls for camera and move settings to cfg file --- .../AzFramework/Viewport/CameraInput.cpp | 159 ++++++++++++++---- .../AzFramework/Viewport/CameraInput.h | 90 +++------- Code/Sandbox/Editor/CryEditDoc.cpp | 11 +- Code/Sandbox/Editor/EditorViewportWidget.cpp | 1 + .../Editor/ModernViewportCameraController.cpp | 62 ++++--- .../Editor/ModernViewportCameraController.h | 13 +- 6 files changed, 189 insertions(+), 147 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp index 46b2e48f81..e9dace3433 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.cpp @@ -15,15 +15,104 @@ #include #include #include +#include #include #include -AZ_CVAR( - float, ed_newCameraSystemDefaultPlaneHeight, 34.0f, nullptr, AZ::ConsoleFunctorFlags::Null, - "The default height of the ground plane to do intersection tests against when orbiting"); - namespace AzFramework { + AZ_CVAR( + float, ed_cameraSystemDefaultPlaneHeight, 34.0f, nullptr, AZ::ConsoleFunctorFlags::Null, + "The default height of the ground plane to do intersection tests against when orbiting"); + AZ_CVAR(float, ed_cameraSystemBoostMultiplier, 3.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemTranslateSpeed, 10.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemOrbitDollyScrollSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemOrbitDollyCursorSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemScrollTranslateSpeed, 0.02f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemDefaultOrbitDistance, 60.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemMaxOrbitDistance, 100.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemLookSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemTranslateSmoothness, 5.0f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemRotateSpeed, 0.005f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(float, ed_cameraSystemPanSpeed, 0.01f, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(bool, ed_cameraSystemPanInvertX, true, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(bool, ed_cameraSystemPanInvertY, true, nullptr, AZ::ConsoleFunctorFlags::Null, ""); + + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateForwardKey, "keyboard_key_alphanumeric_W", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateBackwardKey, "keyboard_key_alphanumeric_S", nullptr, AZ::ConsoleFunctorFlags::Null, + ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateLeftKey, "keyboard_key_alphanumeric_A", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateRightKey, "keyboard_key_alphanumeric_D", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemTranslateUpKey, "keyboard_key_alphanumeric_E", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateDownKey, "keyboard_key_alphanumeric_Q", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR( + AZ::CVarFixedString, ed_cameraSystemTranslateBoostKey, "keyboard_key_modifier_shift_l", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemOrbitKey, "keyboard_key_modifier_alt_l", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemFreeLookButton, "mouse_button_right", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemFreePanButton, "mouse_button_middle", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemOrbitLookButton, "mouse_button_left", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemOrbitDollyButton, "mouse_button_right", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + AZ_CVAR(AZ::CVarFixedString, ed_cameraSystemOrbitPanButton, "mouse_button_middle", nullptr, AZ::ConsoleFunctorFlags::Null, ""); + + static InputChannelId CameraTranslateForwardId; + static InputChannelId CameraTranslateBackwardId; + static InputChannelId CameraTranslateLeftId; + static InputChannelId CameraTranslateRightId; + static InputChannelId CameraTranslateDownId; + static InputChannelId CameraTranslateUpId; + static InputChannelId CameraTranslateBoostId; + static InputChannelId CameraOrbitId; + + // externed elsewhere + InputChannelId CameraFreeLookButton; + InputChannelId CameraFreePanButton; + InputChannelId CameraOrbitLookButton; + InputChannelId CameraOrbitDollyButton; + InputChannelId CameraOrbitPanButton; + + void ReloadCameraKeyBindings() + { + const AZ::CVarFixedString& forward = ed_cameraSystemTranslateForwardKey; + CameraTranslateForwardId = InputChannelId(forward.c_str()); + const AZ::CVarFixedString& backward = ed_cameraSystemTranslateBackwardKey; + CameraTranslateBackwardId = InputChannelId(backward.c_str()); + const AZ::CVarFixedString& left = ed_cameraSystemTranslateLeftKey; + CameraTranslateLeftId = InputChannelId(left.c_str()); + const AZ::CVarFixedString& right = ed_cameraSystemTranslateRightKey; + CameraTranslateRightId = InputChannelId(right.c_str()); + const AZ::CVarFixedString& down = ed_cameraSystemTranslateDownKey; + CameraTranslateDownId = InputChannelId(down.c_str()); + const AZ::CVarFixedString& up = ed_cameraSystemTranslateUpKey; + CameraTranslateUpId = InputChannelId(up.c_str()); + const AZ::CVarFixedString& boost = ed_cameraSystemTranslateBoostKey; + CameraTranslateBoostId = InputChannelId(boost.c_str()); + const AZ::CVarFixedString& orbit = ed_cameraSystemOrbitKey; + CameraOrbitId = InputChannelId(orbit.c_str()); + const AZ::CVarFixedString& freeLook = ed_cameraSystemFreeLookButton; + CameraFreeLookButton = InputChannelId(freeLook.c_str()); + const AZ::CVarFixedString& freePan = ed_cameraSystemFreePanButton; + CameraFreePanButton = InputChannelId(freePan.c_str()); + const AZ::CVarFixedString& orbitLook = ed_cameraSystemOrbitLookButton; + CameraOrbitLookButton = InputChannelId(orbitLook.c_str()); + const AZ::CVarFixedString& orbitDolly = ed_cameraSystemOrbitDollyButton; + CameraOrbitDollyButton = InputChannelId(orbitDolly.c_str()); + const AZ::CVarFixedString& orbitPan = ed_cameraSystemOrbitPanButton; + CameraOrbitPanButton = InputChannelId(orbitPan.c_str()); + } + + static void ReloadCameraKeyBindingsConsole(const AZ::ConsoleCommandContainer&) + { + ReloadCameraKeyBindings(); + } + + AZ_CONSOLEFREEFUNC(ReloadCameraKeyBindingsConsole, AZ::ConsoleFunctorFlags::Null, "Reload keybindings for the modern camera system"); + // Based on paper by David Eberly - https://www.geometrictools.com/Documentation/EulerAngles.pdf AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation) { @@ -186,7 +275,7 @@ namespace AzFramework { if (const auto& input = AZStd::get_if(&event)) { - if (input->m_channelId == m_channelId) + if (input->m_channelId == m_rotateChannelId) { if (input->m_state == InputChannel::State::Began) { @@ -206,8 +295,8 @@ namespace AzFramework { Camera nextCamera = targetCamera; - nextCamera.m_pitch -= float(cursorDelta.m_y) * m_props.m_rotateSpeed; - nextCamera.m_yaw -= float(cursorDelta.m_x) * m_props.m_rotateSpeed; + nextCamera.m_pitch -= float(cursorDelta.m_y) * ed_cameraSystemRotateSpeed; + nextCamera.m_yaw -= float(cursorDelta.m_x) * ed_cameraSystemRotateSpeed; const auto clampRotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; @@ -222,7 +311,7 @@ namespace AzFramework { if (const auto& input = AZStd::get_if(&event)) { - if (input->m_channelId == InputDeviceMouse::Button::Middle) + if (input->m_channelId == m_panChannelId) { if (input->m_state == InputChannel::State::Began) { @@ -244,49 +333,48 @@ namespace AzFramework const auto panAxes = m_panAxesFn(nextCamera); - const auto deltaPanX = float(cursorDelta.m_x) * panAxes.m_horizontalAxis * m_props.m_panSpeed; - const auto deltaPanY = float(cursorDelta.m_y) * panAxes.m_verticalAxis * m_props.m_panSpeed; + const auto deltaPanX = float(cursorDelta.m_x) * panAxes.m_horizontalAxis * ed_cameraSystemPanSpeed; + const auto deltaPanY = float(cursorDelta.m_y) * panAxes.m_verticalAxis * ed_cameraSystemPanSpeed; const auto inv = [](const bool invert) { constexpr float Dir[] = {1.0f, -1.0f}; return Dir[static_cast(invert)]; }; - nextCamera.m_lookAt += deltaPanX * inv(m_props.m_panInvertX); - nextCamera.m_lookAt += deltaPanY * -inv(m_props.m_panInvertY); + nextCamera.m_lookAt += deltaPanX * inv(ed_cameraSystemPanInvertX); + nextCamera.m_lookAt += deltaPanY * -inv(ed_cameraSystemPanInvertY); return nextCamera; } TranslateCameraInput::TranslationType TranslateCameraInput::translationFromKey(InputChannelId channelId) { - // note: remove hard-coded InputDevice keys - if (channelId == InputDeviceKeyboard::Key::AlphanumericW) + if (channelId == CameraTranslateForwardId) { return TranslationType::Forward; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericS) + if (channelId == CameraTranslateBackwardId) { return TranslationType::Backward; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericA) + if (channelId == CameraTranslateLeftId) { return TranslationType::Left; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericD) + if (channelId == CameraTranslateRightId) { return TranslationType::Right; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericQ) + if (channelId == CameraTranslateDownId) { return TranslationType::Down; } - if (channelId == InputDeviceKeyboard::Key::AlphanumericE) + if (channelId == CameraTranslateUpId) { return TranslationType::Up; } @@ -311,7 +399,7 @@ namespace AzFramework BeginActivation(); } - if (input->m_channelId == InputDeviceKeyboard::Key::ModifierShiftL) + if (input->m_channelId == CameraTranslateBoostId) { m_boost = true; } @@ -323,7 +411,7 @@ namespace AzFramework { EndActivation(); } - if (input->m_channelId == InputDeviceKeyboard::Key::ModifierShiftL) + if (input->m_channelId == CameraTranslateBoostId) { m_boost = false; } @@ -342,8 +430,8 @@ namespace AzFramework const auto axisY = translationBasis.GetBasisY(); const auto axisZ = translationBasis.GetBasisZ(); - const float speed = [boost = m_boost, props = m_props]() { - return props.m_translateSpeed * (boost ? props.m_boostMultiplier : 1.0f); + const float speed = [boost = m_boost]() { + return ed_cameraSystemTranslateSpeed * (boost ? ed_cameraSystemBoostMultiplier : 1.0f); }(); if ((m_translation & TranslationType::Forward) == TranslationType::Forward) @@ -394,7 +482,7 @@ namespace AzFramework { if (const auto* input = AZStd::get_if(&event)) { - if (input->m_channelId == InputDeviceKeyboard::Key::ModifierAltL) + if (input->m_channelId == CameraOrbitId) { if (input->m_state == InputChannel::State::Began) { @@ -421,18 +509,17 @@ namespace AzFramework if (Beginning()) { float hit_distance = 0.0f; - if (AZ::Plane::CreateFromNormalAndPoint( - AZ::Vector3::CreateAxisZ(), AZ::Vector3::CreateAxisZ(ed_newCameraSystemDefaultPlaneHeight)) + if (AZ::Plane::CreateFromNormalAndPoint(AZ::Vector3::CreateAxisZ(), AZ::Vector3::CreateAxisZ(ed_cameraSystemDefaultPlaneHeight)) .CastRay(targetCamera.Translation(), targetCamera.Rotation().GetBasisY(), hit_distance)) { - hit_distance = AZStd::min(hit_distance, m_props.m_maxOrbitDistance); + hit_distance = AZStd::min(hit_distance, ed_cameraSystemMaxOrbitDistance); nextCamera.m_lookDist = -hit_distance; nextCamera.m_lookAt = targetCamera.Translation() + targetCamera.Rotation().GetBasisY() * hit_distance; } else { - nextCamera.m_lookDist = -m_props.m_defaultOrbitDistance; - nextCamera.m_lookAt = targetCamera.Translation() + targetCamera.Rotation().GetBasisY() * m_props.m_defaultOrbitDistance; + nextCamera.m_lookDist = -ed_cameraSystemMaxOrbitDistance; + nextCamera.m_lookAt = targetCamera.Translation() + targetCamera.Rotation().GetBasisY() * ed_cameraSystemMaxOrbitDistance; } } @@ -465,7 +552,7 @@ namespace AzFramework [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; - nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + scrollDelta * m_props.m_dollySpeed, 0.0f); + nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + scrollDelta * ed_cameraSystemOrbitDollyScrollSpeed, 0.0f); EndActivation(); return nextCamera; } @@ -474,7 +561,7 @@ namespace AzFramework { if (const auto& input = AZStd::get_if(&event)) { - if (input->m_channelId == InputDeviceMouse::Button::Right) + if (input->m_channelId == m_dollyChannelId) { if (input->m_state == InputChannel::State::Began) { @@ -493,7 +580,7 @@ namespace AzFramework [[maybe_unused]] const float deltaTime) { Camera nextCamera = targetCamera; - nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + float(cursorDelta.m_y) * m_props.m_dollySpeed, 0.0f); + nextCamera.m_lookDist = AZ::GetMin(nextCamera.m_lookDist + float(cursorDelta.m_y) * ed_cameraSystemOrbitDollyCursorSpeed, 0.0f); return nextCamera; } @@ -514,14 +601,14 @@ namespace AzFramework const auto translation_basis = LookTranslation(nextCamera); const auto axisY = translation_basis.GetBasisY(); - nextCamera.m_lookAt += axisY * scrollDelta * m_props.m_translateSpeed; + nextCamera.m_lookAt += axisY * scrollDelta * ed_cameraSystemScrollTranslateSpeed; EndActivation(); return nextCamera; } - Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const SmoothProps& props, const float deltaTime) + Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const float deltaTime) { const auto clamp_rotation = [](const float angle) { return std::fmod(angle + AZ::Constants::TwoPi, AZ::Constants::TwoPi); }; @@ -542,11 +629,11 @@ namespace AzFramework Camera camera; // note: the math for the lerp smoothing implementation for camera rotation and translation was inspired by this excellent // article by Scott Lembcke: https://www.gamasutra.com/blogs/ScottLembcke/20180404/316046/Improved_Lerp_Smoothing.php - const float lookRate = std::exp2(props.m_lookSmoothness); + const float lookRate = std::exp2(ed_cameraSystemLookSmoothness); const float lookT = std::exp2(-lookRate * deltaTime); camera.m_pitch = AZ::Lerp(targetCamera.m_pitch, currentCamera.m_pitch, lookT); camera.m_yaw = AZ::Lerp(targetYaw, currentYaw, lookT); - const float moveRate = std::exp2(props.m_moveSmoothness); + const float moveRate = std::exp2(ed_cameraSystemTranslateSmoothness); const float moveT = std::exp2(-moveRate * deltaTime); camera.m_lookDist = AZ::Lerp(targetCamera.m_lookDist, currentCamera.m_lookDist, moveT); camera.m_lookAt = targetCamera.m_lookAt.Lerp(currentCamera.m_lookAt, moveT); diff --git a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h index daad86ef81..6ccd7c43eb 100644 --- a/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h +++ b/Code/Framework/AzFramework/AzFramework/Viewport/CameraInput.h @@ -12,38 +12,20 @@ #pragma once -#include #include #include #include #include #include -#include -#include #include #include namespace AzFramework { - struct WindowSize; - - // to be moved - class ModernViewportCameraControllerRequests : public AZ::EBusTraits - { - public: - using BusIdType = AzFramework::ViewportId; ///< ViewportId - used to address requests to this EBus. - static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; - static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; - - virtual void SetTargetCameraTransform(const AZ::Transform& transform) = 0; - - protected: - ~ModernViewportCameraControllerRequests() = default; - }; + //! Update camera key bindings that can be overridden with AZ console vars (invoke from console to update) + void ReloadCameraKeyBindings(); - using ModernViewportCameraControllerRequestBus = AZ::EBus; - - // https://www.geometrictools.com/Documentation/EulerAngles.pdf + //! Return Euler angles (pitch, roll, yaw) for the incoming orientation. AZ::Vector3 EulerAngles(const AZ::Matrix3x3& orientation); struct Camera @@ -182,13 +164,7 @@ namespace AzFramework Activation m_activation = Activation::Idle; }; - struct SmoothProps - { - float m_lookSmoothness = 5.0f; - float m_moveSmoothness = 5.0f; - }; - - Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, const SmoothProps& props, float deltaTime); + Camera SmoothCamera(const Camera& currentCamera, const Camera& targetCamera, float deltaTime); class Cameras { @@ -220,19 +196,16 @@ namespace AzFramework class RotateCameraInput : public CameraInput { public: - explicit RotateCameraInput(const InputChannelId channelId) - : m_channelId(channelId) + explicit RotateCameraInput(const InputChannelId rotateChannelId) + : m_rotateChannelId(rotateChannelId) { } + void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - InputChannelId m_channelId; - - struct Props - { - float m_rotateSpeed = 0.005f; - } m_props; + private: + InputChannelId m_rotateChannelId; }; struct PanAxes @@ -265,22 +238,17 @@ namespace AzFramework class PanCameraInput : public CameraInput { public: - explicit PanCameraInput(PanAxesFn panAxesFn) + PanCameraInput(const InputChannelId panChannelId, PanAxesFn panAxesFn) : m_panAxesFn(AZStd::move(panAxesFn)) + , m_panChannelId(panChannelId) { } void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - struct Props - { - float m_panSpeed = 0.01f; - bool m_panInvertX = true; - bool m_panInvertY = true; - } m_props; - private: PanAxesFn m_panAxesFn; + InputChannelId m_panChannelId; }; using TranslationAxesFn = AZStd::function; @@ -321,12 +289,6 @@ namespace AzFramework Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; void ResetImpl() override; - struct Props - { - float m_translateSpeed = 10.0f; - float m_boostMultiplier = 3.0f; - } m_props; - private: enum class TranslationType { @@ -394,23 +356,19 @@ namespace AzFramework public: void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - - struct Props - { - float m_dollySpeed = 0.02f; - } m_props; }; class OrbitDollyCursorMoveCameraInput : public CameraInput { public: + explicit OrbitDollyCursorMoveCameraInput(const InputChannelId dollyChannelId) + : m_dollyChannelId(dollyChannelId) {} + void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - struct Props - { - float m_dollySpeed = 0.1f; - } m_props; + private: + InputChannelId m_dollyChannelId; }; class ScrollTranslationCameraInput : public CameraInput @@ -418,11 +376,6 @@ namespace AzFramework public: void HandleEvents(const InputEvent& event) override; Camera StepCamera(const Camera& targetCamera, const ScreenVector& cursorDelta, float scrollDelta, float deltaTime) override; - - struct Props - { - float m_translateSpeed = 0.02f; - } m_props; }; class OrbitCameraInput : public CameraInput @@ -436,13 +389,10 @@ namespace AzFramework } Cameras m_orbitCameras; - - struct Props - { - float m_defaultOrbitDistance = 60.0f; - float m_maxOrbitDistance = 100.0f; - } m_props; }; + struct WindowSize; + + //! Map from a generic InputChannel event to a camera specific InputEvent. InputEvent BuildInputEvent(const InputChannel& inputChannel, const WindowSize& windowSize); } // namespace AzFramework diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 86491c3e1d..ea40e3c1d6 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -652,21 +652,14 @@ void CCryEditDoc::SerializeViewSettings(CXmlArchive& xmlAr) CViewport* pVP = GetIEditor()->GetViewManager()->GetView(i); - Matrix34 tm = Matrix34::CreateRotationXYZ(va); - tm.SetTranslation(vp); if (pVP) { + Matrix34 tm = Matrix34::CreateRotationXYZ(va); + tm.SetTranslation(vp); pVP->SetViewTM(tm); } - if (auto viewportContext = AZ::Interface::Get()->GetDefaultViewportContext()) - { - AzFramework::ModernViewportCameraControllerRequestBus::Event( - viewportContext->GetId(), &AzFramework::ModernViewportCameraControllerRequestBus::Events::SetTargetCameraTransform, - LYTransformToAZTransform(tm)); - } - // Load grid. auto gridName = QString("Grid%1").arg(useOldViewFormat ? "" : QString::number(i)); XmlNodeRef gridNode = xmlAr.root->newChild(gridName.toUtf8().constData()); diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index 691d53ba3d..3c42b2db32 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -1234,6 +1234,7 @@ void EditorViewportWidget::SetViewportId(int id) if (ed_useNewCameraSystem) { + AzFramework::ReloadCameraKeyBindings(); m_renderViewport->GetControllerList()->Add(AZStd::make_shared()); } else diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.cpp b/Code/Sandbox/Editor/ModernViewportCameraController.cpp index 571ae04997..4725721f0e 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.cpp +++ b/Code/Sandbox/Editor/ModernViewportCameraController.cpp @@ -16,27 +16,31 @@ #include #include #include +#include +#include #include #include #include +namespace AzFramework +{ + extern InputChannelId CameraFreeLookButton; + extern InputChannelId CameraFreePanButton; + extern InputChannelId CameraOrbitLookButton; + extern InputChannelId CameraOrbitDollyButton; + extern InputChannelId CameraOrbitPanButton; +} + namespace SandboxEditor { - static void DrawPreviewAxis( - AzFramework::DebugDisplayRequests& display, const AZ::Transform& transform, const float axisLength) + static void DrawPreviewAxis(AzFramework::DebugDisplayRequests& display, const AZ::Transform& transform, const float axisLength) { display.SetColor(AZ::Colors::Red); - display.DrawLine( - transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * axisLength); + display.DrawLine(transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * axisLength); display.SetColor(AZ::Colors::Green); - display.DrawLine( - transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * axisLength); + display.DrawLine(transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * axisLength); display.SetColor(AZ::Colors::Blue); - display.DrawLine( - transform.GetTranslation(), - transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength); + display.DrawLine(transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength); } static AZ::RPI::ViewportContextPtr RetrieveViewportContext(const AzFramework::ViewportId viewportId) @@ -60,17 +64,21 @@ namespace SandboxEditor : MultiViewportControllerInstanceInterface(viewportId) { // LYN-2315 TODO - move setup out of constructor, pass cameras in - auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::InputDeviceMouse::Button::Right); - auto firstPersonPanCamera = AZStd::make_shared(AzFramework::LookPan); + auto firstPersonRotateCamera = AZStd::make_shared(AzFramework::CameraFreeLookButton); + auto firstPersonPanCamera = + AZStd::make_shared(AzFramework::CameraFreePanButton, AzFramework::LookPan); auto firstPersonTranslateCamera = AZStd::make_shared(AzFramework::LookTranslation); auto firstPersonWheelCamera = AZStd::make_shared(); auto orbitCamera = AZStd::make_shared(); - auto orbitRotateCamera = AZStd::make_shared(AzFramework::InputDeviceMouse::Button::Left); + auto orbitRotateCamera = AZStd::make_shared(AzFramework::CameraOrbitLookButton); auto orbitTranslateCamera = AZStd::make_shared(AzFramework::OrbitTranslation); auto orbitDollyWheelCamera = AZStd::make_shared(); - auto orbitDollyMoveCamera = AZStd::make_shared(); - auto orbitPanCamera = AZStd::make_shared(AzFramework::OrbitPan); + auto orbitDollyMoveCamera = + AZStd::make_shared(AzFramework::CameraOrbitDollyButton); + auto orbitPanCamera = + AZStd::make_shared(AzFramework::CameraOrbitPanButton, AzFramework::OrbitPan); + orbitCamera->m_orbitCameras.AddCamera(orbitRotateCamera); orbitCamera->m_orbitCameras.AddCamera(orbitTranslateCamera); orbitCamera->m_orbitCameras.AddCamera(orbitDollyWheelCamera); @@ -83,13 +91,24 @@ namespace SandboxEditor m_cameraSystem.m_cameras.AddCamera(firstPersonWheelCamera); m_cameraSystem.m_cameras.AddCamera(orbitCamera); + if (auto viewportContext = RetrieveViewportContext(GetViewportId())) + { + auto handleCameraChange = [this](const AZ::Matrix4x4& matrix) { + UpdateCameraFromTransform( + m_targetCamera, + AZ::Transform::CreateFromMatrix3x3AndTranslation(AZ::Matrix3x3::CreateFromMatrix4x4(matrix), matrix.GetTranslation())); + }; + + m_cameraViewMatrixChangeHandler = AZ::RPI::ViewportContext::MatrixChangedEvent::Handler(handleCameraChange); + + viewportContext->ConnectViewMatrixChangedHandler(m_cameraViewMatrixChangeHandler); + } + AzFramework::ViewportDebugDisplayEventBus::Handler::BusConnect(AzToolsFramework::GetEntityContextId()); - AzFramework::ModernViewportCameraControllerRequestBus::Handler::BusConnect(viewportId); } ModernViewportCameraControllerInstance::~ModernViewportCameraControllerInstance() { - AzFramework::ModernViewportCameraControllerRequestBus::Handler::BusDisconnect(); AzFramework::ViewportDebugDisplayEventBus::Handler::BusDisconnect(); } @@ -130,7 +149,7 @@ namespace SandboxEditor if (m_cameraMode == CameraMode::Control) { m_targetCamera = m_cameraSystem.StepCamera(m_targetCamera, event.m_deltaTime.count()); - m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, m_smoothProps, event.m_deltaTime.count()); + m_camera = AzFramework::SmoothCamera(m_camera, m_targetCamera, event.m_deltaTime.count()); viewportContext->SetCameraTransform(m_camera.Transform()); } @@ -172,9 +191,4 @@ namespace SandboxEditor DrawPreviewAxis(debugDisplay, m_transformEnd, 2.0f); } - - void ModernViewportCameraControllerInstance::SetTargetCameraTransform(const AZ::Transform& transform) - { - AzFramework::UpdateCameraFromTransform(m_targetCamera, transform); - } } // namespace SandboxEditor diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index cbdcf5cd22..0bc8cea831 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -19,8 +19,7 @@ namespace SandboxEditor { class ModernViewportCameraControllerInstance final : public AzFramework::MultiViewportControllerInstanceInterface, - private AzFramework::ViewportDebugDisplayEventBus::Handler, - private AzFramework::ModernViewportCameraControllerRequestBus::Handler + private AzFramework::ViewportDebugDisplayEventBus::Handler { public: explicit ModernViewportCameraControllerInstance(AzFramework::ViewportId viewportId); @@ -33,9 +32,6 @@ namespace SandboxEditor // AzFramework::ViewportDebugDisplayEventBus overrides ... void DisplayViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; - // ModernViewportCameraControllerRequestBus overrides ... - void SetTargetCameraTransform(const AZ::Transform& transform) override; - private: enum class CameraMode { @@ -45,13 +41,14 @@ namespace SandboxEditor AzFramework::Camera m_camera; AzFramework::Camera m_targetCamera; - AzFramework::SmoothProps m_smoothProps; AzFramework::CameraSystem m_cameraSystem; - AZ::Transform m_transformStart; - AZ::Transform m_transformEnd; + AZ::Transform m_transformStart = AZ::Transform::CreateIdentity(); + AZ::Transform m_transformEnd = AZ::Transform::CreateIdentity(); float m_animationT = 0.0f; CameraMode m_cameraMode = CameraMode::Control; + + AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraViewMatrixChangeHandler; }; using ModernViewportCameraController = AzFramework::MultiViewportController; From 5df82caef68d104d35455c4b6974405570f747ee Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 4 May 2021 09:04:18 -0500 Subject: [PATCH 073/185] [LYN-3464] Vegetation unit tests intermittently failed due to an AssetManager bug. Inside the AssetContainer, if the root asset finished loading during the container initialization, the CheckReady() call at the end of initialization would detect the loaded asset, but would skip sending out notifications because the initialized flag wasn't set yet. This would lead to an extra asset reference remaining in the AssetManager itself, would would then cause errors when the asset handler for that asset got removed. By setting the initialization flag before the CheckReady() call, the notifications get sent correctly, and no extra asset references remain. This checkin also includes a unit test for the AssetManager that specifically forces this condition to happen and validates that it works correctly. --- .../AzCore/AzCore/Asset/AssetContainer.cpp | 7 +- .../Asset/AssetManagerStreamingTests.cpp | 161 +++++++++++++++++- .../AzCore/Tests/Asset/TestAssetTypes.h | 7 + .../DynamicSliceInstanceSpawnerTests.cpp | 6 +- 4 files changed, 176 insertions(+), 5 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp index 4e7a19c197..50c382d7da 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp @@ -239,8 +239,13 @@ namespace AZ return; } - CheckReady(); m_initComplete = true; + + // *After* setting initComplete to true, check to see if the assets are already ready. + // This check needs to wait until after setting initComplete because if they *are* ready, we want the final call to + // RemoveWaitingAsset to trigger the OnAssetContainer* event. If we call CheckReady() *before* setting initComplete, + // if all the assets are ready, the event will never get triggered. + CheckReady(); } bool AssetContainer::IsReady() const diff --git a/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp b/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp index 807288ff82..f5e2a880d5 100644 --- a/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp +++ b/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp @@ -330,4 +330,163 @@ namespace UnitTest } } -} + // The AssetManagerStreamerImmediateCompletionTests class adjusts the asset loading to force it to complete immediately, + // while still within the callstack for GetAsset(). This can be used to test various conditions in which the load thread + // completes more rapidly than expected, and can expose subtle race conditions. + // There are a few key things that this class does to make this work: + // - The file I/O streamer is mocked + // - The asset stream data is mocked to a 0-byte length for the asset so that the stream load will bypass the I/O streamer and + // just immediately return completion. + // - The number of JobManager threads is set to 0, forcing jobs to execute synchronously inline when they are started. + // With these changes, GetAssetInternal() will queue the stream, which will immediately call the callback that creates LoadAssetJob, + // which immediately executes in-place to process the asset due to the synchronous JobManager. + // Note that if we just created the asset in a Ready state, most of the asset loading code is completely bypassed, and so we + // wouldn't be able to test for race conditions in the AssetContainer. + // + // This class also unregisters the catalog and asset handler before shutting down the asset manager. This is done to catch + // any outstanding asset references that exist due to loads not completing and cleaning up successfully. + struct AssetManagerStreamerImmediateCompletionTests : public BaseAssetManagerTest, + public AZ::Data::AssetCatalogRequestBus::Handler, + public AZ::Data::AssetHandler, + public AZ::Data::AssetCatalog + { + static inline const AZ::Uuid TestAssetId{"{E970B177-5F45-44EB-A2C4-9F29D9A0B2A2}"}; + static inline const char* TestAssetPath{"test"}; + + void SetUp() override + { + BaseAssetManagerTest::SetUp(); + AssetManager::Descriptor desc; + AssetManager::Create(desc); + + // Register the handler and catalog after creation, because we intend to destroy them before AssetManager destruction. + // The specific asset we load is irrelevant, so register EmptyAsset. + AZ::Data::AssetManager::Instance().RegisterHandler(this, AZ::AzTypeInfo::Uuid()); + AZ::Data::AssetManager::Instance().RegisterCatalog(this, AZ::AzTypeInfo::Uuid()); + + // Intercept messages for finding assets by name so that we can mock out the asset we're loading. + AZ::Data::AssetCatalogRequestBus::Handler::BusConnect(); + } + + void TearDown() override + { + // Unregister before destroying AssetManager. + // This will catch any assets that got stuck in a loading state without getting cleaned up. + AZ::Data::AssetManager::Instance().UnregisterCatalog(this); + AZ::Data::AssetManager::Instance().UnregisterHandler(this); + + AZ::Data::AssetCatalogRequestBus::Handler::BusDisconnect(); + + AssetManager::Destroy(); + BaseAssetManagerTest::TearDown(); + } + + size_t GetNumJobManagerThreads() const override + { + // Return 0 threads so that the Job Manager executes jobs synchronously inline. This lets us finish a load while still + // in the callstack that initiates the load. + return 0; + } + + // Create a mock streamer instead of a real one, since we don't really want to load an asset. + IO::IStreamer* CreateStreamer() override + { + m_mockStreamer = AZStd::make_unique(); + return &(m_mockStreamer->m_mockStreamer); + } + + void DestroyStreamer([[maybe_unused]] IO::IStreamer* streamer) override + { + m_mockStreamer = nullptr; + } + + // AssetHandler implementation + + // Minimalist mock to create a new EmptyAsset with the desired asset ID. + AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, [[maybe_unused]] const AZ::Data::AssetType& type) override + { + return new EmptyAsset(id); + } + + void DestroyAsset(AZ::Data::AssetPtr ptr) override + { + delete ptr; + } + + // The mocked-out Asset Catalog handles EmptyAsset types. + void GetHandledAssetTypes(AZStd::vector& assetTypes) override + { + assetTypes.push_back(AZ::AzTypeInfo::Uuid()); + } + + // This is a mocked-out load, so just immediately return completion without doing anything. + AZ::Data::AssetHandler::LoadResult LoadAssetData( + [[maybe_unused]] const AZ::Data::Asset& asset, + [[maybe_unused]] AZStd::shared_ptr stream, + [[maybe_unused]] const AZ::Data::AssetFilterCB& assetLoadFilterCB) + { + return AZ::Data::AssetHandler::LoadResult::LoadComplete; + } + + // AssetCatalogRequestBus implementation + + // Minimalist mocks to provide our desired asset path or asset id + AZStd::string GetAssetPathById([[maybe_unused]] const AZ::Data::AssetId& id) override + { + return TestAssetPath; + } + AZ::Data::AssetId GetAssetIdByPath( + [[maybe_unused]] const char* path, [[maybe_unused]] const AZ::Data::AssetType& typeToRegister, + [[maybe_unused]] bool autoRegisterIfNotFound) override + { + return TestAssetId; + } + + // Return the mocked-out information for our test asset + AZ::Data::AssetInfo GetAssetInfoById([[maybe_unused]] const AZ::Data::AssetId& id) override + { + AZ::Data::AssetInfo assetInfo; + assetInfo.m_assetId = TestAssetId; + assetInfo.m_assetType = AZ::AzTypeInfo::Uuid(); + assetInfo.m_relativePath = TestAssetPath; + return assetInfo; + } + + // AssetCatalog implementation + + // Set the mocked-out asset load to have a 0-byte length so that the load skips I/O and immediately returns success + AZ::Data::AssetStreamInfo GetStreamInfoForLoad( + [[maybe_unused]] const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override + { + EXPECT_TRUE(type == AZ::AzTypeInfo::Uuid()); + AZ::Data::AssetStreamInfo info; + info.m_dataOffset = 0; + info.m_streamName = TestAssetPath; + info.m_dataLen = 0; + info.m_streamFlags = AZ::IO::OpenMode::ModeRead; + + return info; + } + + AZStd::unique_ptr m_mockStreamer; + }; + + // This test will verify that even if the asset loading stream/job returns immediately, all of the loading + // code works successfully. The test here is fairly simple - it just loads the asset and verifies that it + // loaded successfully. The bulk of the test is really in the setup class above, where the load is forced + // to complete immediately. Also, the true failure condition is caught in the setup class too, which is + // the presence of any assets at the point that the asset handler is unregistered. If they're present, then + // the immediate load wasn't truly successful, as it left around extra references to the asset that haven't + // been cleaned up. + TEST_F(AssetManagerStreamerImmediateCompletionTests, LoadAssetWithImmediateJobCompletion_WorksSuccessfully) + { + AZ::Data::AssetLoadParameters loadParams; + + auto testAsset = + AssetManager::Instance().GetAsset(TestAssetId, AZ::Data::AssetLoadBehavior::Default, loadParams); + + AZ::Data::AssetManager::Instance().DispatchEvents(); + EXPECT_TRUE(testAsset.IsReady()); + } + +} // namespace UnitTest diff --git a/Code/Framework/AzCore/Tests/Asset/TestAssetTypes.h b/Code/Framework/AzCore/Tests/Asset/TestAssetTypes.h index 83f3909676..d4267972ec 100644 --- a/Code/Framework/AzCore/Tests/Asset/TestAssetTypes.h +++ b/Code/Framework/AzCore/Tests/Asset/TestAssetTypes.h @@ -24,6 +24,13 @@ namespace UnitTest public: AZ_CLASS_ALLOCATOR(EmptyAsset, AZ::SystemAllocator, 0); AZ_RTTI(EmptyAsset, "{098E3F7F-13AC-414B-9B4E-49B5AD1BD7FE}", AZ::Data::AssetData); + + EmptyAsset( + const AZ::Data::AssetId& assetId = AZ::Data::AssetId(), + AZ::Data::AssetData::AssetStatus status = AZ::Data::AssetData::AssetStatus::NotLoaded) + : AZ::Data::AssetData(assetId, status) + { + } }; // EmptyAssetWithNoHandler: no data contained within, and no AssetHandler registered for this type diff --git a/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp b/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp index ef2b52f05d..8c922359cf 100644 --- a/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp +++ b/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp @@ -275,7 +275,7 @@ namespace UnitTest } // [SPEC-6600] This test intermittently fails on automated builds, so disabling temporarily until root cause identified - TEST_F(DynamicSliceInstanceSpawnerTests, DISABLED_DifferentSpawnersAreNotEqual) + TEST_F(DynamicSliceInstanceSpawnerTests, DifferentSpawnersAreNotEqual) { // Two spawners with different data should *not* be data-equivalent. @@ -291,7 +291,7 @@ namespace UnitTest // [LY-118267] This test intermittently fails on automated builds, so disabling temporarily until the root cause // can be identified - TEST_F(DynamicSliceInstanceSpawnerTests, DISABLED_LoadAndUnloadAssets) + TEST_F(DynamicSliceInstanceSpawnerTests, LoadAndUnloadAssets) { // The spawner should successfully load/unload assets without errors. @@ -312,7 +312,7 @@ namespace UnitTest } // [SPEC-6600] This test intermittently fails on automated builds, so disabling temporarily until root cause identified - TEST_F(DynamicSliceInstanceSpawnerTests, DISABLED_CreateAndDestroyInstance) + TEST_F(DynamicSliceInstanceSpawnerTests, CreateAndDestroyInstance) { // The spawner should successfully create and destroy an instance without errors. From 53a6e5ac6becd69d9c76ea63ae5e60b86ae4ad42 Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 4 May 2021 10:08:59 -0500 Subject: [PATCH 074/185] Addressed feedback. --- Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp | 4 ++-- .../AzCore/Tests/Asset/AssetManagerStreamingTests.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp b/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp index 50c382d7da..2ff6143912 100644 --- a/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp +++ b/Code/Framework/AzCore/AzCore/Asset/AssetContainer.cpp @@ -243,8 +243,8 @@ namespace AZ // *After* setting initComplete to true, check to see if the assets are already ready. // This check needs to wait until after setting initComplete because if they *are* ready, we want the final call to - // RemoveWaitingAsset to trigger the OnAssetContainer* event. If we call CheckReady() *before* setting initComplete, - // if all the assets are ready, the event will never get triggered. + // RemoveWaitingAsset to trigger the OnAssetContainerReady/Canceled event. If we call CheckReady() *before* setting + // initComplete, if all the assets are ready, the event will never get triggered. CheckReady(); } diff --git a/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp b/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp index f5e2a880d5..c55a95cf2a 100644 --- a/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp +++ b/Code/Framework/AzCore/Tests/Asset/AssetManagerStreamingTests.cpp @@ -351,7 +351,7 @@ namespace UnitTest public AZ::Data::AssetCatalog { static inline const AZ::Uuid TestAssetId{"{E970B177-5F45-44EB-A2C4-9F29D9A0B2A2}"}; - static inline const char* TestAssetPath{"test"}; + static inline constexpr AZStd::string_view TestAssetPath = "test"; void SetUp() override { From 8686997deff782701801bb6861e9c0ab6fbb2c18 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 16:28:35 +0100 Subject: [PATCH 075/185] add missing include --- Code/Sandbox/Editor/ModernViewportCameraController.h | 1 + 1 file changed, 1 insertion(+) diff --git a/Code/Sandbox/Editor/ModernViewportCameraController.h b/Code/Sandbox/Editor/ModernViewportCameraController.h index 0bc8cea831..56345ad0da 100644 --- a/Code/Sandbox/Editor/ModernViewportCameraController.h +++ b/Code/Sandbox/Editor/ModernViewportCameraController.h @@ -12,6 +12,7 @@ #pragma once +#include #include #include #include From 6b1f0c53a5193bc6b26a00ffb9058a0318f815c0 Mon Sep 17 00:00:00 2001 From: guthadam Date: Tue, 4 May 2021 10:30:27 -0500 Subject: [PATCH 076/185] Injecting --activateWindow every time new process sends command line Updated comments --- .../Code/Source/MaterialEditorApplication.cpp | 10 ++++++---- .../Source/Material/EditorMaterialSystemComponent.cpp | 3 --- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp index 3ffe2af1a6..1f32c2a66b 100644 --- a/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp +++ b/Gems/Atom/Tools/MaterialEditor/Code/Source/MaterialEditorApplication.cpp @@ -432,10 +432,16 @@ namespace MaterialEditor // Forward commandline options to other application instance. QByteArray buffer; buffer.append("ProcessCommandLine:"); + + // Add the command line options from this process to the message, skipping the executable path for (int argi = 1; argi < m_argC; ++argi) { buffer.append(QString(m_argV[argi]).append("\n").toUtf8()); } + + // Inject command line option to always bring the main window to the foreground + buffer.append("--activatewindow\n"); + m_socket.Send(buffer); m_socket.Disconnect(); return false; @@ -446,10 +452,6 @@ namespace MaterialEditor // Handle commmand line params from connected socket if (buffer.startsWith("ProcessCommandLine:")) { - // Bring the material editor to the foreground - MaterialEditor::MaterialEditorWindowRequestBus::Broadcast( - &MaterialEditor::MaterialEditorWindowRequestBus::Handler::ActivateWindow); - // Remove header and parse commands AZStd::string params(buffer.data(), buffer.size()); params = params.substr(strlen("ProcessCommandLine:")); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp index 4cf51e2f37..e9a81f2e9f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialSystemComponent.cpp @@ -128,9 +128,6 @@ namespace AZ QStringList arguments; arguments.append(sourcePath.c_str()); - // Bring the material editor to the foreground if running - arguments.append("--activatewindow"); - // Use the same RHI as the main editor AZ::Name apiName = AZ::RHI::Factory::Get().GetName(); if (!apiName.IsEmpty()) From 61840b5f861cc2e44718478977fdedff7e8d58ec Mon Sep 17 00:00:00 2001 From: mbalfour Date: Tue, 4 May 2021 11:04:51 -0500 Subject: [PATCH 077/185] Removed outdated comments. --- .../Code/Tests/DynamicSliceInstanceSpawnerTests.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp b/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp index 8c922359cf..c3aa910b47 100644 --- a/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp +++ b/Gems/Vegetation/Code/Tests/DynamicSliceInstanceSpawnerTests.cpp @@ -274,7 +274,6 @@ namespace UnitTest EXPECT_TRUE(instanceSpawner1 == instanceSpawner2); } - // [SPEC-6600] This test intermittently fails on automated builds, so disabling temporarily until root cause identified TEST_F(DynamicSliceInstanceSpawnerTests, DifferentSpawnersAreNotEqual) { // Two spawners with different data should *not* be data-equivalent. @@ -289,8 +288,6 @@ namespace UnitTest EXPECT_TRUE(!(instanceSpawner1 == instanceSpawner2)); } - // [LY-118267] This test intermittently fails on automated builds, so disabling temporarily until the root cause - // can be identified TEST_F(DynamicSliceInstanceSpawnerTests, LoadAndUnloadAssets) { // The spawner should successfully load/unload assets without errors. @@ -311,7 +308,6 @@ namespace UnitTest Vegetation::DescriptorNotificationBus::Handler::BusDisconnect(); } - // [SPEC-6600] This test intermittently fails on automated builds, so disabling temporarily until root cause identified TEST_F(DynamicSliceInstanceSpawnerTests, CreateAndDestroyInstance) { // The spawner should successfully create and destroy an instance without errors. From 0f6d57a2670cbb66f62f9492c79979d38e979628 Mon Sep 17 00:00:00 2001 From: Aristo7 <5432499+Aristo7@users.noreply.github.com> Date: Tue, 4 May 2021 11:24:49 -0500 Subject: [PATCH 078/185] Fixed up a compile issue --- Code/Sandbox/Editor/CryEditDoc.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Code/Sandbox/Editor/CryEditDoc.cpp b/Code/Sandbox/Editor/CryEditDoc.cpp index 04e82d3299..a84f2ea85e 100644 --- a/Code/Sandbox/Editor/CryEditDoc.cpp +++ b/Code/Sandbox/Editor/CryEditDoc.cpp @@ -62,6 +62,9 @@ #include "StatObjBus.h" // LmbrCentral +#include +#include +#include #include // for LmbrCentral::EditorLightComponentRequestBus From a206896074d29e93901e883805f486cf55b8a360 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 16:13:38 +0100 Subject: [PATCH 079/185] 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 1474b56e12134f433d2a129d11fa9cb95254b1d0 Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Tue, 4 May 2021 09:55:07 -0700 Subject: [PATCH 080/185] Deployment postprocessing should be enabled only for release builds --- cmake/Platform/iOS/LYWrappers_ios.cmake | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cmake/Platform/iOS/LYWrappers_ios.cmake b/cmake/Platform/iOS/LYWrappers_ios.cmake index 53783e5c0a..97b7c70d35 100644 --- a/cmake/Platform/iOS/LYWrappers_ios.cmake +++ b/cmake/Platform/iOS/LYWrappers_ios.cmake @@ -16,7 +16,9 @@ function(ly_apply_platform_properties target) set_target_properties(${target} PROPERTIES - XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING "YES" + XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=debug] "NO" + XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=profile] "NO" + XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=release] "YES" ) if(${target_type} STREQUAL "SHARED_LIBRARY") From bb76bccc06249d2bb9db6863335d0ffdc81f1f73 Mon Sep 17 00:00:00 2001 From: hultonha Date: Tue, 4 May 2021 17:55:09 +0100 Subject: [PATCH 081/185] 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 082/185] fixed C18243589_Joints_BallSoftLimitsConstrained test failure --- ...243589_Joints_BallSoftLimitsConstrained.py | 37 ++++++++++++++++--- .../Gem/PythonTests/physics/JointsHelper.py | 7 ++++ 2 files changed, 38 insertions(+), 6 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 - - # 4) Wait for several seconds - general.idle_wait(1.0) # wait for lead and follower to move + + 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) + + 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 b99d0fb36ad590cf27f1d4794bec3c13b4c46b93 Mon Sep 17 00:00:00 2001 From: amzn-sj Date: Tue, 4 May 2021 10:20:51 -0700 Subject: [PATCH 083/185] Move symbol stripping attributes to iOS configuration file --- cmake/Platform/iOS/Configurations_ios.cmake | 5 +++++ cmake/Platform/iOS/LYWrappers_ios.cmake | 7 ------- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/cmake/Platform/iOS/Configurations_ios.cmake b/cmake/Platform/iOS/Configurations_ios.cmake index aa935c853f..6522c6a098 100644 --- a/cmake/Platform/iOS/Configurations_ios.cmake +++ b/cmake/Platform/iOS/Configurations_ios.cmake @@ -41,6 +41,11 @@ endif() # Signing ly_set(CMAKE_XCODE_ATTRIBUTE_OTHER_CODE_SIGN_FLAGS --deep) +# Symbol Stripping +ly_set(CMAKE_XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=debug] "NO") +ly_set(CMAKE_XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=profile] "NO") +ly_set(CMAKE_XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=release] "YES") + # Generate scheme files for Xcode ly_set(CMAKE_XCODE_GENERATE_SCHEME TRUE) diff --git a/cmake/Platform/iOS/LYWrappers_ios.cmake b/cmake/Platform/iOS/LYWrappers_ios.cmake index 97b7c70d35..8da421ad5c 100644 --- a/cmake/Platform/iOS/LYWrappers_ios.cmake +++ b/cmake/Platform/iOS/LYWrappers_ios.cmake @@ -14,13 +14,6 @@ include(cmake/Platform/Common/LYWrappers_default.cmake) function(ly_apply_platform_properties target) get_target_property(target_type ${target} TYPE) - set_target_properties(${target} - PROPERTIES - XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=debug] "NO" - XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=profile] "NO" - XCODE_ATTRIBUTE_DEPLOYMENT_POSTPROCESSING[variant=release] "YES" - ) - if(${target_type} STREQUAL "SHARED_LIBRARY") # Some projects use an "_" in their target name which is not allowed in a bundle identifier get_target_property(target_name ${target} NAME) From d9b3b7ccfaae7bdb976f19cb786d09f81fa5170e Mon Sep 17 00:00:00 2001 From: greerdv Date: Tue, 4 May 2021 18:31:43 +0100 Subject: [PATCH 084/185] adding non-uniform scale component via button on transform component and forcing it to be adjacent in the component sort order and visible --- .../Serialization/EditContextConstants.inl | 3 + .../Components/NonUniformScaleComponent.cpp | 2 + .../API/EntityPropertyEditorRequestsBus.h | 4 + .../EditorNonUniformScaleComponent.cpp | 7 +- .../ToolsComponents/TransformComponent.cpp | 39 ++++----- .../PropertyEditor/EntityPropertyEditor.cpp | 84 +++++++++++++++++-- .../PropertyEditor/EntityPropertyEditor.hxx | 6 ++ 7 files changed, 113 insertions(+), 32 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl b/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl index 90b9ba5afd..454d998321 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl +++ b/Code/Framework/AzCore/AzCore/Serialization/EditContextConstants.inl @@ -53,6 +53,9 @@ namespace AZ //! RemoveableByUser : A bool which determines if the component can be removed by the user. //! Setting this to false prevents the user from removing this component. Default behavior is removeable by user. const static AZ::Crc32 RemoveableByUser = AZ_CRC("RemoveableByUser", 0x32c7fd50); + //! A bool which determines if the component can be dragged to change where it appears in the entity sort order. + //! Setting this to false prevents the user from dragging the component. Default behaviour is draggable by user. + const static AZ::Crc32 DraggableByUser = AZ_CRC_CE("DraggableByUser"); const static AZ::Crc32 AppearsInAddComponentMenu = AZ_CRC("AppearsInAddComponentMenu", 0x53790e31); const static AZ::Crc32 ForceAutoExpand = AZ_CRC("ForceAutoExpand", 0x1a5c79d2); // Ignores expansion state set by user, enforces expansion. const static AZ::Crc32 AutoExpand = AZ_CRC("AutoExpand", 0x306ff5c0); // Expands automatically unless user changes expansion state. diff --git a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp index 095d986fa1..57f14ddb38 100644 --- a/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp +++ b/Code/Framework/AzFramework/AzFramework/Components/NonUniformScaleComponent.cpp @@ -36,6 +36,8 @@ namespace AzFramework void NonUniformScaleComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + incompatible.push_back(AZ_CRC_CE("DebugDrawObbService")); incompatible.push_back(AZ_CRC_CE("DebugDrawService")); incompatible.push_back(AZ_CRC_CE("EMotionFXActorService")); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EntityPropertyEditorRequestsBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EntityPropertyEditorRequestsBus.h index 35b2e485b5..1959183fa0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EntityPropertyEditorRequestsBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EntityPropertyEditorRequestsBus.h @@ -31,6 +31,10 @@ namespace AzToolsFramework //! Allows a component to get the list of selected entities //! \param selectedEntityIds the return vector holding the entities required virtual void GetSelectedEntities(EntityIdList& selectedEntityIds) = 0; + + //! Explicitly sets a component as having been the most recently added. + //! This means that the next time the UI refreshes, that component will be ensured to be visible. + virtual void SetNewComponentId(AZ::ComponentId componentId) = 0; }; using EntityPropertyEditorRequestBus = AZ::EBus; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp index 5e928a382a..d28f23c847 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp @@ -39,9 +39,8 @@ namespace AzToolsFramework editContext->Class("Non-uniform Scale", "Non-uniform scale for this entity only (does not propagate through hierarchy)") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Non-uniform Scale") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) + ->Attribute(AZ::Edit::Attributes::RemoveableByUser, true) + ->Attribute(AZ::Edit::Attributes::DraggableByUser, false) ->DataElement( AZ::Edit::UIHandlers::Default, &EditorNonUniformScaleComponent::m_scale, "Non-uniform Scale", "Non-uniform scale for this entity only (does not propagate through hierarchy)") @@ -61,6 +60,8 @@ namespace AzToolsFramework void EditorNonUniformScaleComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) { + incompatible.push_back(AZ_CRC_CE("NonUniformScaleService")); + incompatible.push_back(AZ_CRC_CE("DebugDrawObbService")); incompatible.push_back(AZ_CRC_CE("DebugDrawService")); incompatible.push_back(AZ_CRC_CE("EMotionFXActorService")); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index 7d8b802622..a025c02c32 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -26,12 +26,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include #include @@ -39,8 +41,6 @@ #include -#pragma optimize("", off) - namespace AzToolsFramework { namespace Components @@ -1232,33 +1232,28 @@ namespace AzToolsFramework AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(outcome, &AzToolsFramework::EntityCompositionRequests::AddComponentsToEntities, entityList, componentsToAdd); - auto nonUniformScaleComponent = GetEntity()->FindComponent(); + AZStd::vector pendingComponents; + AzToolsFramework::EditorPendingCompositionRequestBus::Event(GetEntityId(), + &AzToolsFramework::EditorPendingCompositionRequests::GetPendingComponents, pendingComponents); - if (!outcome.IsSuccess() || nonUniformScaleComponent == nullptr) + AZ::ComponentId nonUniformScaleComponentId = AZ::InvalidComponentId; + for (const auto pendingComponent : pendingComponents) { - AZ_Warning("Transform component", false, "Failed to add non-uniform scale component."); - return AZ::Edit::PropertyRefreshLevels::None; + if (pendingComponent->RTTI_IsTypeOf(AzToolsFramework::Components::EditorNonUniformScaleComponent::RTTI_Type())) + { + nonUniformScaleComponentId = pendingComponent->GetId(); + } } - AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::Bus::Events::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); - - ComponentOrderArray componentOrderArray; - EditorInspectorComponentRequestBus::EventResult(componentOrderArray, GetEntityId(), - &EditorInspectorComponentRequests::GetComponentOrderArray); - - // find the id for the non-uniform scale component and move it immediately after the transform component in the sort order - auto nonUniformScaleComponentIter = AZStd::find(componentOrderArray.begin(), componentOrderArray.end(), nonUniformScaleComponent->GetId()); - auto transformComponentIter = AZStd::find(componentOrderArray.begin(), componentOrderArray.end(), GetId()); - if (nonUniformScaleComponentIter != componentOrderArray.end() && transformComponentIter != componentOrderArray.end()) + if (!outcome.IsSuccess() || nonUniformScaleComponentId == AZ::InvalidComponentId) { - componentOrderArray.erase(nonUniformScaleComponentIter); - transformComponentIter = AZStd::find(componentOrderArray.begin(), componentOrderArray.end(), GetId()); - componentOrderArray.insert(++transformComponentIter, nonUniformScaleComponent->GetId()); - EditorInspectorComponentRequestBus::Event(GetEntityId(), - &EditorInspectorComponentRequests::SetComponentOrderArray, componentOrderArray); + AZ_Warning("Transform component", false, "Failed to add non-uniform scale component."); + return AZ::Edit::PropertyRefreshLevels::None; } + AzToolsFramework::EntityPropertyEditorRequestBus::Broadcast( + &AzToolsFramework::EntityPropertyEditorRequests::SetNewComponentId, nonUniformScaleComponentId); + return AZ::Edit::PropertyRefreshLevels::EntireTree; } diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp index 181f5b9a9d..0fdd55f24e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp @@ -63,6 +63,7 @@ AZ_POP_DISABLE_WARNING #include #include #include +#include #include #include #include @@ -494,6 +495,11 @@ namespace AzToolsFramework } } + void EntityPropertyEditor::SetNewComponentId(AZ::ComponentId componentId) + { + m_newComponentId = componentId; + } + void EntityPropertyEditor::SetOverrideEntityIds(const AzToolsFramework::EntityIdSet& entities) { m_overrideSelectedEntityIds = entities; @@ -1052,6 +1058,19 @@ namespace AzToolsFramework return false; } + // If component 1 is a non-uniform scale component, it is sorted earlier (it should appear immediately after transform) + if (component1.m_component->RTTI_IsTypeOf(AzToolsFramework::Components::EditorNonUniformScaleComponent::RTTI_Type())) + { + return true; + } + + // If component 2 is a non-uniform scale component, component 1 is never sorted earlier + // (transform will already dominate in the check above) + if (component2.m_component->RTTI_IsTypeOf(AzToolsFramework::Components::EditorNonUniformScaleComponent::RTTI_Type())) + { + return false; + } + if (!IsComponentRemovable(component1.m_component) && IsComponentRemovable(component2.m_component)) { return true; @@ -1128,10 +1147,7 @@ namespace AzToolsFramework { if (auto attributeData = azdynamic_cast*>(attribute)) { - if (!attributeData->Get(nullptr)) - { - return false; - } + return attributeData->Get(nullptr); } } } @@ -1166,6 +1182,34 @@ namespace AzToolsFramework return true; } + bool EntityPropertyEditor::IsComponentDraggable(const AZ::Component* component) + { + auto componentClassData = component ? GetComponentClassData(component) : nullptr; + if (componentClassData && componentClassData->m_editData) + { + if (auto editorDataElement = componentClassData->m_editData->FindElementData(AZ::Edit::ClassElements::EditorData)) + { + if (auto attribute = editorDataElement->FindAttribute(AZ::Edit::Attributes::DraggableByUser)) + { + if (auto attributeData = azdynamic_cast*>(attribute)) + { + if (!attributeData->Get(nullptr)) + { + return false; + } + } + } + } + } + + return true; + } + + bool EntityPropertyEditor::AreComponentsDraggable(const AZ::Entity::ComponentArrayType& components) const + { + return AZStd::all_of(components.begin(), components.end(), [](AZ::Component* component) {return IsComponentDraggable(component); }); + } + bool EntityPropertyEditor::AreComponentsCopyable(const AZ::Entity::ComponentArrayType& components) const { return AreComponentsCopyable(components, m_componentFilter); @@ -3367,7 +3411,9 @@ namespace AzToolsFramework sourceComponents.size() == m_selectedEntityIds.size() && targetComponents.size() == m_selectedEntityIds.size() && AreComponentsRemovable(sourceComponents) && - AreComponentsRemovable(targetComponents); + AreComponentsRemovable(targetComponents) && + AreComponentsDraggable(sourceComponents) && + AreComponentsDraggable(targetComponents); } bool EntityPropertyEditor::IsMoveComponentsUpAllowed() const @@ -3681,14 +3727,38 @@ namespace AzToolsFramework void EntityPropertyEditor::ScrollToNewComponent() { - //force new components to be visible, assuming they are added to the end of the list and layout - auto componentEditor = GetComponentEditorsFromIndex(m_componentEditorsUsed - 1); + // force new components to be visible + // if no component has been explicitly set at the most recently added, + // assume new components are added to the end of the list and layout + AZ::s32 newComponentIndex = m_componentEditorsUsed - 1; + + // if there is a component id explicitly set as the most recently added, try to find it and make sure it is visible + if (m_newComponentId.has_value()) + { + AZ::ComponentId newComponentId = m_newComponentId.value(); + for (AZ::s32 componentIndex = 0; componentIndex < m_componentEditorsUsed; ++componentIndex) + { + if (m_componentEditors[componentIndex]) + { + for (const auto component : m_componentEditors[componentIndex]->GetComponents()) + { + if (component->GetId() == newComponentId) + { + newComponentIndex = componentIndex; + } + } + } + } + } + + auto componentEditor = GetComponentEditorsFromIndex(newComponentIndex); if (componentEditor) { m_gui->m_componentList->ensureWidgetVisible(componentEditor); } m_shouldScrollToNewComponents = false; m_shouldScrollToNewComponentsQueued = false; + m_newComponentId.reset(); } void EntityPropertyEditor::QueueScrollToNewComponent() diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx index 677dc98277..2fb1c7e03a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx @@ -211,6 +211,7 @@ namespace AzToolsFramework // EntityPropertEditorRequestBus void GetSelectedAndPinnedEntities(EntityIdList& selectedEntityIds) override; void GetSelectedEntities(EntityIdList& selectedEntityIds) override; + void SetNewComponentId(AZ::ComponentId componentId) override; bool IsEntitySelected(const AZ::EntityId& id) const; bool IsSingleEntitySelected(const AZ::EntityId& id) const; @@ -237,6 +238,8 @@ namespace AzToolsFramework static bool DoesComponentPassFilter(const AZ::Component* component, const ComponentFilter& filter); static bool IsComponentRemovable(const AZ::Component* component); bool AreComponentsRemovable(const AZ::Entity::ComponentArrayType& components) const; + static bool IsComponentDraggable(const AZ::Component* component); + bool AreComponentsDraggable(const AZ::Entity::ComponentArrayType& components) const; bool AreComponentsCopyable(const AZ::Entity::ComponentArrayType& components) const; void AddMenuOptionsForComponents(QMenu& menu, const QPoint& position); @@ -568,6 +571,9 @@ namespace AzToolsFramework void ConnectToEntityBuses(const AZ::EntityId& entityId); void DisconnectFromEntityBuses(const AZ::EntityId& entityId); + //! Stores a component id to be focused on next time the UI updates. + AZStd::optional m_newComponentId; + private slots: void OnPropertyRefreshRequired(); // refresh is needed for a property. void UpdateContents(); From 8b1251c9f79d5b7f52781f78c339a13e96f11c8d Mon Sep 17 00:00:00 2001 From: jackalbe <23512001+jackalbe@users.noreply.github.com> Date: Tue, 4 May 2021 12:55:47 -0500 Subject: [PATCH 085/185] {LYN-2185} Helios - Added GraphObjectProxy::GetMethodList() function (#392) * {LYN-2185} Helios - Added GraphObjectProxy::GetMethodList() function * Updated the EditorPythonConsoleInterface to get Python type name info * Added PythonBehaviorInfo to the GraphObjectProxy object to reflect abstract calls that can be invoked * removed SCENE_DATA_API from Reflect() function Jira: https://jira.agscollab.com/browse/LYN-2185 Tests: Added tests GraphObjectProxy_GetClassInfo_Loads & GraphObjectProxy_GetClassInfo_CorrectFormats to regress test * fix compile error * etchPythonTypeName() returns AZStd::string * put None into a const char --- .../API/EditorPythonConsoleBus.h | 8 + .../SceneCore/Containers/GraphObjectProxy.cpp | 141 ++++++++++++++++++ .../SceneCore/Containers/GraphObjectProxy.h | 6 + .../Tests/Containers/SceneBehaviorTests.cpp | 62 ++++++++ .../SceneData/GraphData/BlendShapeData.h | 2 +- .../Code/Source/PythonLogSymbolsComponent.cpp | 10 +- .../Code/Source/PythonLogSymbolsComponent.h | 2 +- .../Tests/PythonLogSymbolsComponentTests.cpp | 4 +- 8 files changed, 226 insertions(+), 9 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorPythonConsoleBus.h b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorPythonConsoleBus.h index 4f5a349518..de4ff396b2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorPythonConsoleBus.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/API/EditorPythonConsoleBus.h @@ -13,6 +13,12 @@ #include #include +#include + +namespace AZ +{ + struct BehaviorParameter; +} namespace AzToolsFramework { @@ -40,6 +46,8 @@ namespace AzToolsFramework }; using GlobalFunctionCollection = AZStd::vector; virtual void GetGlobalFunctionList(GlobalFunctionCollection& globalFunctionCollection) const = 0; + + virtual AZStd::string FetchPythonTypeName(const AZ::BehaviorParameter& param) = 0; }; //! Interface to signal the phases for the Python virtual machine diff --git a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp index f2fda63ec4..989eccd526 100644 --- a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.cpp @@ -13,9 +13,135 @@ #include #include #include +#include +#include +#include namespace AZ { + namespace Python + { + static const char* const None = "None"; + + class PythonBehaviorInfo final + { + public: + AZ_RTTI(PythonBehaviorInfo, "{8055BD03-5B3B-490D-AEC5-1B1E2616D529}"); + AZ_CLASS_ALLOCATOR(PythonBehaviorInfo, AZ::SystemAllocator, 0); + + static void Reflect(AZ::ReflectContext* context); + + PythonBehaviorInfo(const AZ::BehaviorClass* behaviorClass); + PythonBehaviorInfo() = delete; + + protected: + bool IsMemberLike(const AZ::BehaviorMethod& method, const AZ::TypeId& typeId) const; + AZStd::string FetchPythonType(const AZ::BehaviorParameter& param) const; + void WriteMethod(AZStd::string_view methodName, const AZ::BehaviorMethod& behaviorMethod); + + private: + const AZ::BehaviorClass* m_behaviorClass = nullptr; + AZStd::vector m_methodList; + }; + + PythonBehaviorInfo::PythonBehaviorInfo(const AZ::BehaviorClass* behaviorClass) + : m_behaviorClass(behaviorClass) + { + AZ_Assert(m_behaviorClass, "PythonBehaviorInfo requires a valid behaviorClass pointer"); + for (const auto& entry : behaviorClass->m_methods) + { + WriteMethod(entry.first, *entry.second); + } + } + + void PythonBehaviorInfo::Reflect(AZ::ReflectContext* context) + { + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->Class() + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Module, "scene.graph") + ->Property("className", [](const PythonBehaviorInfo& self) + { return self.m_behaviorClass->m_name; }, nullptr) + ->Property("classUuid", [](const PythonBehaviorInfo& self) + { return self.m_behaviorClass->m_typeId.ToString(); }, nullptr) + ->Property("methodList", BehaviorValueGetter(&PythonBehaviorInfo::m_methodList), nullptr); + } + } + + bool PythonBehaviorInfo::IsMemberLike(const AZ::BehaviorMethod& method, const AZ::TypeId& typeId) const + { + return method.IsMember() || (method.GetNumArguments() > 0 && method.GetArgument(0)->m_typeId == typeId); + } + + AZStd::string PythonBehaviorInfo::FetchPythonType(const AZ::BehaviorParameter& param) const + { + using namespace AzToolsFramework; + EditorPythonConsoleInterface* editorPythonConsoleInterface = AZ::Interface::Get(); + if (editorPythonConsoleInterface) + { + return editorPythonConsoleInterface->FetchPythonTypeName(param); + } + return None; + } + + void PythonBehaviorInfo::WriteMethod(AZStd::string_view methodName, const AZ::BehaviorMethod& behaviorMethod) + { + // if the method is a static method then it is not a part of the abstract class + const bool isMemberLike = IsMemberLike(behaviorMethod, m_behaviorClass->m_typeId); + if (isMemberLike == false) + { + return; + } + + AZStd::string buffer; + AZStd::vector pythonArgs; + + AzFramework::StringFunc::Append(buffer, "def "); + AzFramework::StringFunc::Append(buffer, methodName.data()); + AzFramework::StringFunc::Append(buffer, "("); + + pythonArgs.emplace_back("self"); + + AZStd::string bufferArg; + for (size_t argIndex = 1; argIndex < behaviorMethod.GetNumArguments(); ++argIndex) + { + const AZStd::string* name = behaviorMethod.GetArgumentName(argIndex); + if (!name || name->empty()) + { + bufferArg = AZStd::string::format(" arg%zu", argIndex); + } + else + { + bufferArg = *name; + } + + AZStd::string_view type = FetchPythonType(*behaviorMethod.GetArgument(argIndex)); + if (!type.empty()) + { + AzFramework::StringFunc::Append(bufferArg, ": "); + AzFramework::StringFunc::Append(bufferArg, type.data()); + } + + pythonArgs.push_back(bufferArg); + bufferArg.clear(); + } + + AZStd::string resultValue{ None }; + if (behaviorMethod.HasResult() && behaviorMethod.GetResult()) + { + resultValue = FetchPythonType(*behaviorMethod.GetResult()); + } + + AZStd::string argsList; + AzFramework::StringFunc::Join(buffer, pythonArgs.begin(), pythonArgs.end(), ","); + AzFramework::StringFunc::Append(buffer, ") -> "); + AzFramework::StringFunc::Append(buffer, resultValue.c_str()); + m_methodList.emplace_back(buffer); + } + } + namespace SceneAPI { namespace Containers @@ -25,6 +151,8 @@ namespace AZ AZ::BehaviorContext* behaviorContext = azrtti_cast(context); if (behaviorContext) { + Python::PythonBehaviorInfo::Reflect(context); + behaviorContext->Class(); behaviorContext->Class() @@ -33,6 +161,19 @@ namespace AZ ->Attribute(AZ::Script::Attributes::ExcludeFrom, AZ::Script::Attributes::ExcludeFlags::All) ->Method("CastWithTypeName", &GraphObjectProxy::CastWithTypeName) ->Method("Invoke", &GraphObjectProxy::Invoke) + ->Method("GetClassInfo", [](GraphObjectProxy& self) -> Python::PythonBehaviorInfo* + { + if (self.m_pythonBehaviorInfo) + { + return self.m_pythonBehaviorInfo.get(); + } + if (self.m_behaviorClass) + { + self.m_pythonBehaviorInfo = AZStd::make_shared(self.m_behaviorClass); + return self.m_pythonBehaviorInfo.get(); + } + return nullptr; + }) ; } } diff --git a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.h b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.h index 094b896364..d83a147e5f 100644 --- a/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.h +++ b/Code/Tools/SceneAPI/SceneCore/Containers/GraphObjectProxy.h @@ -16,6 +16,11 @@ namespace AZ { + namespace Python + { + class PythonBehaviorInfo; + } + namespace SceneAPI { namespace Containers @@ -44,6 +49,7 @@ namespace AZ private: AZStd::shared_ptr m_graphObject; const AZ::BehaviorClass* m_behaviorClass = nullptr; + AZStd::shared_ptr m_pythonBehaviorInfo; }; } // Containers diff --git a/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp b/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp index cb23e73b0e..8d7fb63baf 100644 --- a/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp +++ b/Code/Tools/SceneAPI/SceneCore/Tests/Containers/SceneBehaviorTests.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -378,6 +379,25 @@ namespace AZ MOCK_CONST_METHOD1(QueryApplicationType, void(AZ::ApplicationTypeQuery&)); }; + class MockEditorPythonConsoleInterface final + : public AzToolsFramework::EditorPythonConsoleInterface + { + public: + MockEditorPythonConsoleInterface() + { + AZ::Interface::Register(this); + } + + ~MockEditorPythonConsoleInterface() + { + AZ::Interface::Unregister(this); + } + + MOCK_CONST_METHOD1(GetModuleList, void(AZStd::vector&)); + MOCK_CONST_METHOD1(GetGlobalFunctionList, void(GlobalFunctionCollection&)); + MOCK_METHOD1(FetchPythonTypeName, AZStd::string(const AZ::BehaviorParameter&)); + }; + // // SceneGraphBehaviorScriptTest // @@ -386,6 +406,7 @@ namespace AZ { public: AZStd::unique_ptr m_componentApplication; + AZStd::unique_ptr m_editorPythonConsoleInterface; AZStd::unique_ptr m_scriptContext; AZStd::unique_ptr m_behaviorContext; AZStd::unique_ptr m_serializeContext; @@ -454,6 +475,15 @@ namespace AZ { return this->m_serializeContext.get(); })); + + m_editorPythonConsoleInterface = AZStd::make_unique(); + } + + void SetupEditorPythonConsoleInterface() + { + EXPECT_CALL(*m_editorPythonConsoleInterface, FetchPythonTypeName(::testing::_)) + .Times(4) + .WillRepeatedly(::testing::Invoke([](const AZ::BehaviorParameter&) {return "int"; })); } void TearDown() override @@ -562,6 +592,38 @@ namespace AZ ExpectExecute("TestExpectEquals(value, 17)"); } + TEST_F(SceneGraphBehaviorScriptTest, GraphObjectProxy_GetClassInfo_Loads) + { + SetupEditorPythonConsoleInterface(); + + ExpectExecute("builder = MockBuilder()"); + ExpectExecute("builder:BuildSceneGraph()"); + ExpectExecute("scene = builder:GetScene()"); + ExpectExecute("nodeG = scene.graph:FindWithPath('A.C.E.G')"); + ExpectExecute("proxy = scene.graph:GetNodeContent(nodeG)"); + ExpectExecute("TestExpectTrue(proxy:CastWithTypeName('MockIGraphObject'))"); + ExpectExecute("info = proxy:GetClassInfo()"); + ExpectExecute("TestExpectTrue(info ~= nil)"); + } + + TEST_F(SceneGraphBehaviorScriptTest, GraphObjectProxy_GetClassInfo_CorrectFormats) + { + SetupEditorPythonConsoleInterface(); + + ExpectExecute("builder = MockBuilder()"); + ExpectExecute("builder:BuildSceneGraph()"); + ExpectExecute("scene = builder:GetScene()"); + ExpectExecute("nodeG = scene.graph:FindWithPath('A.C.E.G')"); + ExpectExecute("proxy = scene.graph:GetNodeContent(nodeG)"); + ExpectExecute("TestExpectTrue(proxy:CastWithTypeName('MockIGraphObject'))"); + ExpectExecute("info = proxy:GetClassInfo()"); + ExpectExecute("TestExpectTrue(info.className == 'MockIGraphObject')"); + ExpectExecute("TestExpectTrue(info.classUuid == '{66A082CC-851D-4E1F-ABBD-45B58A216CFA}')"); + ExpectExecute("TestExpectTrue(info.methodList[1] == 'def GetId(self) -> int')"); + ExpectExecute("TestExpectTrue(info.methodList[2] == 'def SetId(self, arg1: int) -> None')"); + ExpectExecute("TestExpectTrue(info.methodList[3] == 'def AddAndSet(self, arg1: int, arg2: int) -> None')"); + } + // // SceneManifestBehaviorScriptTest is meant to test the script abilities of the SceneManifest // diff --git a/Code/Tools/SceneAPI/SceneData/GraphData/BlendShapeData.h b/Code/Tools/SceneAPI/SceneData/GraphData/BlendShapeData.h index 9ae287da46..403ab867f2 100644 --- a/Code/Tools/SceneAPI/SceneData/GraphData/BlendShapeData.h +++ b/Code/Tools/SceneAPI/SceneData/GraphData/BlendShapeData.h @@ -31,7 +31,7 @@ namespace AZ public: AZ_RTTI(BlendShapeData, "{FF875C22-2E4F-4CE3-BA49-09BF78C70A09}", SceneAPI::DataTypes::IBlendShapeData) - SCENE_DATA_API static void Reflect(ReflectContext* context); + static void Reflect(ReflectContext* context); // Maximum number of color sets matches limitation set in assImp (AI_MAX_NUMBER_OF_COLOR_SETS) static constexpr AZ::u8 MaxNumColorSets = 8; diff --git a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp index 2b7676e4db..a22064cfe2 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp +++ b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.cpp @@ -161,7 +161,7 @@ namespace EditorPythonBindings bufferArg = *name; } - AZStd::string_view type = FetchPythonType(*behaviorMethod.GetArgument(argIndex)); + AZStd::string type = FetchPythonTypeName(*behaviorMethod.GetArgument(argIndex)); if (!type.empty()) { AzFramework::StringFunc::Append(bufferArg, ": "); @@ -289,7 +289,7 @@ namespace EditorPythonBindings bool isBroadcast = false; if (sender.m_event) { - AZStd::string_view addressType = FetchPythonType(behaviorEBus->m_idParam); + AZStd::string addressType = FetchPythonTypeName(behaviorEBus->m_idParam); if (addressType.empty()) { AzFramework::StringFunc::Append(buffer, "(busCallType: int, busEventName: str, address: Any, args: Tuple[Any])"); @@ -338,7 +338,7 @@ namespace EditorPythonBindings } const AZ::BehaviorParameter* resultParam = behaviorMethod->GetResult(); - AZStd::string_view returnType = FetchPythonType(*resultParam); + AZStd::string returnType = FetchPythonTypeName(*resultParam); AZStd::string returnTypeStr = AZStd::string::format(") -> " AZ_STRING_FORMAT" \n", AZ_STRING_ARG(returnType)); AzFramework::StringFunc::Append(inOutStrBuffer, returnTypeStr.c_str()); }; @@ -664,9 +664,9 @@ namespace EditorPythonBindings return m_typeCache[typeId]; } - AZStd::string_view PythonLogSymbolsComponent::FetchPythonType(const AZ::BehaviorParameter& param) + AZStd::string PythonLogSymbolsComponent::FetchPythonTypeName(const AZ::BehaviorParameter& param) { - AZStd::string_view pythonType = FetchPythonTypeAndTraits(param.m_typeId, param.m_traits); + AZStd::string pythonType = FetchPythonTypeAndTraits(param.m_typeId, param.m_traits); if (pythonType.empty()) { diff --git a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h index 2972e3c9e0..e52cb00570 100644 --- a/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h +++ b/Gems/EditorPythonBindings/Code/Source/PythonLogSymbolsComponent.h @@ -62,6 +62,7 @@ namespace EditorPythonBindings void LogGlobalMethod(AZStd::string_view moduleName, AZStd::string_view methodName, AZ::BehaviorMethod* behaviorMethod) override; void LogGlobalProperty(AZStd::string_view moduleName, AZStd::string_view propertyName, AZ::BehaviorProperty* behaviorProperty) override; void Finalize() override; + AZStd::string FetchPythonTypeName(const AZ::BehaviorParameter& param) override; //////////////////////////////////////////////////////////////////////// // EditorPythonConsoleInterface @@ -71,7 +72,6 @@ namespace EditorPythonBindings //////////////////////////////////////////////////////////////////////// // Python type deduction AZStd::string_view FetchPythonTypeAndTraits(const AZ::TypeId& typeId, AZ::u32 traits); - AZStd::string_view FetchPythonType(const AZ::BehaviorParameter& param); private: using ModuleSet = AZStd::unordered_set; diff --git a/Gems/EditorPythonBindings/Code/Tests/PythonLogSymbolsComponentTests.cpp b/Gems/EditorPythonBindings/Code/Tests/PythonLogSymbolsComponentTests.cpp index 97f4dd02d0..8297bad094 100644 --- a/Gems/EditorPythonBindings/Code/Tests/PythonLogSymbolsComponentTests.cpp +++ b/Gems/EditorPythonBindings/Code/Tests/PythonLogSymbolsComponentTests.cpp @@ -41,9 +41,9 @@ namespace UnitTest return FetchPythonTypeAndTraits(typeId, traits); } - AZStd::string_view FetchPythonTypeWrapper(const AZ::BehaviorParameter& param) + AZStd::string FetchPythonTypeWrapper(const AZ::BehaviorParameter& param) { - return FetchPythonType(param); + return FetchPythonTypeName(param); } }; From 5e94c9c838a66b4b8bf59187f36bb2595174f4f7 Mon Sep 17 00:00:00 2001 From: greerdv Date: Tue, 4 May 2021 18:59:04 +0100 Subject: [PATCH 086/185] fixing highlighting behaviour when trying to drag components above non-uniform scale component --- .../UI/PropertyEditor/EntityPropertyEditor.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp index 0fdd55f24e..51d4ed5026 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.cpp @@ -4143,7 +4143,8 @@ namespace AzToolsFramework { if (!componentEditor || !componentEditor->isVisible() || - !AreComponentsRemovable(componentEditor->GetComponents())) + !AreComponentsRemovable(componentEditor->GetComponents()) || + !AreComponentsDraggable(componentEditor->GetComponents())) { return false; } @@ -4293,6 +4294,7 @@ namespace AzToolsFramework while (targetComponentEditor && (targetComponentEditor->IsDragged() || !AreComponentsRemovable(targetComponentEditor->GetComponents()) + || !AreComponentsDraggable(targetComponentEditor->GetComponents()) || (globalRect.center().y() > GetWidgetGlobalRect(targetComponentEditor).center().y()))) { if (targetItr == m_componentEditors.end() || targetComponentEditor == m_componentEditors.back() || !targetComponentEditor->isVisible()) From 1f6ec22e6e3040e3d1abcfc88d3adc6eeb845bf0 Mon Sep 17 00:00:00 2001 From: Terry Michaels <81711813+tjmichaels@users.noreply.github.com> Date: Tue, 4 May 2021 12:59:49 -0500 Subject: [PATCH 087/185] Removed deprecated assets (GeomCache files) --- Assets/Editor/Presets/GeomCache/game.cbc | 1 - Assets/Editor/Presets/GeomCache/game_lz4hc.cbc | 1 - Assets/Editor/Presets/GeomCache/game_z_up.cbc | 1 - .../Presets/GeomCache/game_z_up_lz4hc.cbc | 1 - Assets/Editor/Presets/GeomCache/prerendered.cbc | 1 - .../Presets/GeomCache/prerendered_z_up.cbc | 1 - Assets/Editor/Presets/GeomCache/rigids_only.cbc | 1 - .../Presets/GeomCache/rigids_only_z_up.cbc | 1 - .../Editor/Presets/GeomCache/uncompressed.cbc | 1 - .../Presets/GeomCache/uncompressed_z_up.cbc | 1 - .../GeomCaches/defaultGeomCache.abc | 3 --- .../GeomCaches/defaultGeomCache.cbc | 1 - .../EngineAssets/GeomCaches/defaultGeomCache.ma | 3 --- .../GeomCaches/defaultGeomCache.mtl | 17 ----------------- 14 files changed, 34 deletions(-) delete mode 100644 Assets/Editor/Presets/GeomCache/game.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/game_lz4hc.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/game_z_up.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/prerendered.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/rigids_only.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/uncompressed.cbc delete mode 100644 Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc delete mode 100644 Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc delete mode 100644 Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc delete mode 100644 Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma delete mode 100644 Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl diff --git a/Assets/Editor/Presets/GeomCache/game.cbc b/Assets/Editor/Presets/GeomCache/game.cbc deleted file mode 100644 index 9b98f3460f..0000000000 --- a/Assets/Editor/Presets/GeomCache/game.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc b/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc deleted file mode 100644 index dbd0499175..0000000000 --- a/Assets/Editor/Presets/GeomCache/game_lz4hc.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/game_z_up.cbc b/Assets/Editor/Presets/GeomCache/game_z_up.cbc deleted file mode 100644 index ec2555a3e3..0000000000 --- a/Assets/Editor/Presets/GeomCache/game_z_up.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc b/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc deleted file mode 100644 index c2e30a6386..0000000000 --- a/Assets/Editor/Presets/GeomCache/game_z_up_lz4hc.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/prerendered.cbc b/Assets/Editor/Presets/GeomCache/prerendered.cbc deleted file mode 100644 index c09785111d..0000000000 --- a/Assets/Editor/Presets/GeomCache/prerendered.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc b/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc deleted file mode 100644 index e42a915e58..0000000000 --- a/Assets/Editor/Presets/GeomCache/prerendered_z_up.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/rigids_only.cbc b/Assets/Editor/Presets/GeomCache/rigids_only.cbc deleted file mode 100644 index e8620bc11e..0000000000 --- a/Assets/Editor/Presets/GeomCache/rigids_only.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc b/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc deleted file mode 100644 index d1f8bc2db3..0000000000 --- a/Assets/Editor/Presets/GeomCache/rigids_only_z_up.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/uncompressed.cbc b/Assets/Editor/Presets/GeomCache/uncompressed.cbc deleted file mode 100644 index e21d52d9d1..0000000000 --- a/Assets/Editor/Presets/GeomCache/uncompressed.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc b/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc deleted file mode 100644 index 273ce1fbb1..0000000000 --- a/Assets/Editor/Presets/GeomCache/uncompressed_z_up.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc deleted file mode 100644 index 8ca759d342..0000000000 --- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.abc +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9c36d7bc993ddf616f478115a123efabda5b4b833a4e6524312f43c228ae0902 -size 487003 diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc deleted file mode 100644 index 3c99ab1627..0000000000 --- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.cbc +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma deleted file mode 100644 index 65aade11a0..0000000000 --- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.ma +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:96a21446422b834ea90a5d38eaaca309fdee31dc3cc03c0e9c094b39ec3a459d -size 4715164 diff --git a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl b/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl deleted file mode 100644 index 05dfe70b09..0000000000 --- a/Assets/Engine/EngineAssets/GeomCaches/defaultGeomCache.mtl +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - - - - - - - - - - - From 11b79f567af12658b6f6958d8d89a32e925b40ce Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Tue, 4 May 2021 11:10:46 -0700 Subject: [PATCH 088/185] Smart and raw pointer support in Json Serialization now behave similarly. The behavior of smart pointers was not updated after the changes to raw pointers, in particular with how default JSON Objects were handled. They both now treat an empty JSON Object (a.k.a. the id for default instances) as meaning to create a default instance on the pointer even if the default is a nullptr. To have a nullptr a JSON Null has to be explicitly written. --- .../Serialization/Json/JsonDeserializer.cpp | 38 +++-- .../Serialization/Json/JsonSerialization.h | 11 ++ .../Json/SmartPointerSerializer.cpp | 15 +- .../Json/BaseJsonSerializerTests.cpp | 105 +++++++++++++- .../Json/SmartPointerSerializerTests.cpp | 130 ++++++++++++++---- 5 files changed, 240 insertions(+), 59 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp index f2e9bb866f..8d0da9e54a 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp @@ -97,7 +97,8 @@ namespace AZ return context.Report(Tasks::RetrieveInfo, Outcomes::Unknown, AZStd::string::format("Failed to retrieve rtti information for %s.", classData->m_name)); } - AZ_Assert(classData->m_azRtti->GetTypeId() == typeId, "Type id mismatch during deserialization of a json file. (%s vs %s)"); + AZ_Assert(classData->m_azRtti->GetTypeId() == typeId, "Type id mismatch during deserialization of a json file. (%s vs %s)", + classData->m_azRtti->GetTypeId().ToString().c_str(), typeId.ToString().c_str()); void** objectPtr = reinterpret_cast(object); bool isNull = *objectPtr == nullptr; @@ -512,27 +513,24 @@ namespace AZ if (*object) { const AZ::Uuid& actualClassId = rtti.GetActualUuid(*object); - if (actualClassId != objectType) + const SerializeContext::ClassData* actualClassData = context.GetSerializeContext()->FindClassData(actualClassId); + if (!actualClassData) { - const SerializeContext::ClassData* actualClassData = context.GetSerializeContext()->FindClassData(actualClassId); - if (!actualClassData) - { - status = context.Report(Tasks::RetrieveInfo, Outcomes::Unknown, - AZStd::string::format("Unable to find serialization information for type %s.", actualClassId.ToString().c_str())); - return ResolvePointerResult::FullyProcessed; - } + status = context.Report(Tasks::RetrieveInfo, Outcomes::Unknown, + AZStd::string::format("Unable to find serialization information for type %s.", actualClassId.ToString().c_str())); + return ResolvePointerResult::FullyProcessed; + } - if (actualClassData->m_factory) - { - actualClassData->m_factory->Destroy(*object); - *object = nullptr; - } - else - { - status = context.Report(Tasks::RetrieveInfo, Outcomes::Catastrophic, - "Unable to find the factory needed to clear out the default value."); - return ResolvePointerResult::FullyProcessed; - } + if (actualClassData->m_factory) + { + actualClassData->m_factory->Destroy(*object); + *object = nullptr; + } + else + { + status = context.Report(Tasks::RetrieveInfo, Outcomes::Catastrophic, + "Unable to find the factory needed to clear out the default value."); + return ResolvePointerResult::FullyProcessed; } } status = ResultCode(Tasks::ReadField, Outcomes::Success); diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h index 5746005832..b92eae7d6b 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h @@ -38,6 +38,17 @@ namespace AZ }; //! Core class to handle serialization to and from json documents. + //! The Json Serialization works by taking a default constructed object and then apply the information found in the JSON document + //! on top of that object. This allows the Json Serialization to avoid storing default values and helps guarantee that the final + //! object is in a valid state even if non-fatal issues are encountered. + //! Note on containers: Containers such as vector or map are always considered to be empty even if there's entries in the provided + //! default object. During deserialization entries will be appended to any existing values. A flag is provided to automatically + //! clear containers during deserialization. + //! Note on maps: If the key for map containers such as unordered_map can be interpret as a string the Json Serialization will use + //! a JSON Object to store the data in instead of an array with key/value objects. + //! Note on pointers: The Json Serialization assumes that are always constructed, so a default JSON value of "{}" is interpret as + //! creating a new default instance even if the default value is a null pointer. A JSON Null needs to be explicitly stored in + //! the JSON Document in order to default or explicitly set a pointer to null. class JsonSerialization final { public: diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/SmartPointerSerializer.cpp b/Code/Framework/AzCore/AzCore/Serialization/Json/SmartPointerSerializer.cpp index 0180e99592..9e707f8644 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/SmartPointerSerializer.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/SmartPointerSerializer.cpp @@ -23,13 +23,6 @@ namespace AZ { namespace JSR = JsonSerializationResult; - if (IsExplicitDefault(inputValue)) - { - // Do nothing if the input is an explicit default. - return context.Report(JSR::Tasks::ReadField, JSR::Outcomes::DefaultsUsed, - "Default value for smart pointer requested so no change was made."); - } - const SerializeContext::ClassData* containerClass = context.GetSerializeContext()->FindClassData(outputValueTypeId); if (!containerClass) { @@ -153,8 +146,7 @@ namespace AZ if (defaultValue) { - bool typesMatch = false; - auto defaultInputCallback = [&defaultValue, &inputPtrType, &typesMatch] + auto defaultInputCallback = [&defaultValue] (void* elementPtr, const Uuid&, const SerializeContext::ClassData*, const SerializeContext::ClassElement*) { defaultValue = elementPtr; @@ -164,11 +156,6 @@ namespace AZ } JSR::ResultCode result = ContinueStoring(outputValue, inputValue, defaultValue, inputPtrType, context, Flags::ResolvePointer); - if (result.GetOutcome() == JSR::Outcomes::DefaultsUsed) - { - outputValue = GetExplicitDefault(); - return context.Report(result, "Smart pointer used all defaults."); - } return context.Report(result, result.GetProcessing() != JSR::Processing::Halted ? "Successfully processed smart pointer." : "A problem occurred while processing a smart pointer."); } diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp index 417cb10c8c..62622ef7ab 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp @@ -110,7 +110,7 @@ namespace JsonSerializationTests EXPECT_EQ(42, value); } - TEST_F(BaseJsonSerializerTests, ContinueLoading_PointerInstance_ValueLoadedCorrectly) + TEST_F(BaseJsonSerializerTests, ContinueLoading_ToPointerInstance_ValueLoadedCorrectly) { using namespace AZ::JsonSerializationResult; @@ -126,6 +126,51 @@ namespace JsonSerializationTests EXPECT_EQ(42, value); } + TEST_F(BaseJsonSerializerTests, ContinueLoading_ToNullPointer_ValueLoadedCorrectly) + { + using namespace AZ::JsonSerializationResult; + + rapidjson::Value json; + json.Set(42); + int* ptrValue = nullptr; + + ResultCode result = ContinueLoading(&ptrValue, azrtti_typeid(), json, *m_jsonDeserializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + ASSERT_NE(nullptr, ptrValue); + EXPECT_EQ(42, *ptrValue); + + azfree(ptrValue, AZ::SystemAllocator, sizeof(int), AZStd::alignment_of::value); + } + + TEST_F(BaseJsonSerializerTests, ContinueLoading_DefaultToNullPointer_ValueLoadedCorrectly) + { + using namespace AZ::JsonSerializationResult; + + rapidjson::Value json(rapidjson::kObjectType); + int* ptrValue = nullptr; + + ResultCode result = ContinueLoading(&ptrValue, azrtti_typeid(), json, *m_jsonDeserializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + ASSERT_NE(nullptr, ptrValue); + + azfree(ptrValue, AZ::SystemAllocator, sizeof(int), AZStd::alignment_of::value); + } + + TEST_F(BaseJsonSerializerTests, ContinueLoading_NullDeletesObject_ValueLoadedCorrectly) + { + using namespace AZ::JsonSerializationResult; + + rapidjson::Value json(rapidjson::kNullType); + int* ptrValue = reinterpret_cast(azmalloc(sizeof(int), AZStd::alignment_of::value, AZ::SystemAllocator)); + + ResultCode result = ContinueLoading(&ptrValue, azrtti_typeid(), json, *m_jsonDeserializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + ASSERT_EQ(nullptr, ptrValue); + } + // // ContinueStoring // @@ -156,6 +201,64 @@ namespace JsonSerializationTests Expect_DocStrEq("42"); } + TEST_F(BaseJsonSerializerTests, ContinueStoring_StorePointerToFullDefaultedInstance_ValueStoredCorrectly) + { + using namespace AZ::JsonSerializationResult; + + int value = 42; + int* ptrValue = &value; + int value2 = 42; + int* defaultPtrValue = &value2; + + ResultCode result = + ContinueStoring(*m_jsonDocument, &ptrValue, &defaultPtrValue, azrtti_typeid(), *m_jsonSerializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + Expect_DocStrEq("{}"); + } + + TEST_F(BaseJsonSerializerTests, ContinueStoring_StorePointerToNullptr_ValueStoredCorrectly) + { + using namespace AZ::JsonSerializationResult; + + int* ptrValue = nullptr; + + ResultCode result = ContinueStoring( + *m_jsonDocument, &ptrValue, nullptr, azrtti_typeid(), *m_jsonSerializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + Expect_DocStrEq("null"); + } + + TEST_F(BaseJsonSerializerTests, ContinueStoring_StorePointerToNullptrWithValueDefault_ValueStoredCorrectly) + { + using namespace AZ::JsonSerializationResult; + + int* ptrValue = nullptr; + int value2 = 42; + int* defaultPtrValue = &value2; + + ResultCode result = + ContinueStoring(*m_jsonDocument, &ptrValue, &defaultPtrValue, azrtti_typeid(), *m_jsonSerializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + Expect_DocStrEq("null"); + } + + TEST_F(BaseJsonSerializerTests, ContinueStoring_StorePointerToNullptrWithNullPtrDefault_NullPtrIsStored) + { + using namespace AZ::JsonSerializationResult; + + int* ptrValue = nullptr; + int* defaultPtrValue = nullptr; + + ResultCode result = + ContinueStoring(*m_jsonDocument, &ptrValue, &defaultPtrValue, azrtti_typeid(), *m_jsonSerializationContext, Flags::ResolvePointer); + + EXPECT_EQ(Processing::Completed, result.GetProcessing()); + Expect_DocStrEq("null"); + } + TEST_F(BaseJsonSerializerTests, ContinueStoring_ReplaceDefault_ValueStoredCorrectly) { using namespace AZ::JsonSerializationResult; diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp index df340a2e61..2fc131aae2 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/SmartPointerSerializerTests.cpp @@ -32,11 +32,6 @@ namespace JsonSerializationTests return AZStd::make_shared(); } - AZStd::shared_ptr CreateDefaultInstance() override - { - return AZStd::make_shared(); - } - void Reflect(AZStd::unique_ptr& context) override { context->RegisterGenericType(); @@ -51,6 +46,13 @@ namespace JsonSerializationTests using SmartPointer = T; using Base = SmartPointerBaseTestDescription; + AZStd::shared_ptr CreateDefaultInstance() override + { + auto result = AZStd::make_shared(); + *result = SmartPointer(aznew SimpleClass()); + return result; + } + AZStd::shared_ptr CreateFullySetInstance() override { auto result = AZStd::make_shared(); @@ -107,27 +109,19 @@ namespace JsonSerializationTests }; template class T> - class SmartPointerSimpleClassWithInstanceTestDescription : - public SmartPointerSimpleClassTestDescription + class SmartPointerSimpleDerivedClassTestDescription : + public SmartPointerBaseTestDescription> { public: - using SmartPointer = typename SmartPointerSimpleClassTestDescription::SmartPointer; + using SmartPointer = T; + using Base = SmartPointerBaseTestDescription; AZStd::shared_ptr CreateDefaultInstance() override { auto result = AZStd::make_shared(); - *result = SmartPointer(aznew SimpleClass()); + *result = SmartPointer(aznew BaseClass()); return result; } - }; - - template class T> - class SmartPointerSimpleDerivedClassTestDescription : - public SmartPointerBaseTestDescription> - { - public: - using SmartPointer = T; - using Base = SmartPointerBaseTestDescription; AZStd::shared_ptr CreateFullySetInstance() override { @@ -272,6 +266,13 @@ namespace JsonSerializationTests using SmartPointer = T; using Base = SmartPointerBaseTestDescription; + AZStd::shared_ptr CreateDefaultInstance() override + { + auto result = AZStd::make_shared(); + *result = SmartPointer(aznew BaseClass2()); + return result; + } + AZStd::shared_ptr CreateFullySetInstance() override { auto* instance = aznew MultipleInheritence(); @@ -424,9 +425,6 @@ namespace JsonSerializationTests SmartPointerSimpleClassTestDescription, SmartPointerSimpleClassTestDescription, SmartPointerSimpleClassTestDescription, - SmartPointerSimpleClassWithInstanceTestDescription, - SmartPointerSimpleClassWithInstanceTestDescription, - SmartPointerSimpleClassWithInstanceTestDescription, // Simple derived class, include single inheritance. SmartPointerSimpleDerivedClassTestDescription, SmartPointerSimpleDerivedClassTestDescription, @@ -551,6 +549,37 @@ namespace JsonSerializationTests EXPECT_EQ(nullptr, *instance); } + TEST_F(JsonSmartPointerSerializerTests, Load_DefaultInstanceToNullptr_ReturnsSuccess) + { + namespace JSR = AZ::JsonSerializationResult; + + SmartPointer instance; + AZStd::shared_ptr compare = m_description.CreateDefaultInstance(); + m_jsonDocument->SetObject(); + + JSR::ResultCode result = + m_serializer.Load(&instance, azrtti_typeid(), *m_jsonDocument, *m_jsonDeserializationContext); + + EXPECT_EQ(JSR::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, instance); + EXPECT_TRUE(m_description.AreEqual(instance, *compare)); + } + + TEST_F(JsonSmartPointerSerializerTests, Load_DefaultObjectDoesNotUpdateInstance_ReturnsSuccess) + { + namespace JSR = AZ::JsonSerializationResult; + + AZStd::shared_ptr instance = m_description.CreateFullySetInstance(); + AZStd::shared_ptr compare = m_description.CreateFullySetInstance(); + m_jsonDocument->SetObject(); + + JSR::ResultCode result = + m_serializer.Load(instance.get(), azrtti_typeid(), *m_jsonDocument, *m_jsonDeserializationContext); + + EXPECT_EQ(JSR::Processing::Completed, result.GetProcessing()); + EXPECT_TRUE(m_description.AreEqual(*instance, *compare)); + } + TEST_F(JsonSmartPointerSerializerTests, Load_InstanceBeingReplacedWithDifferentType_ReturnsSuccess) { namespace JSR = AZ::JsonSerializationResult; @@ -720,13 +749,66 @@ namespace JsonSerializationTests namespace JSR = AZ::JsonSerializationResult; AZStd::shared_ptr instance = m_description.CreateFullySetInstance(); - SmartPointer nullPtr; - JSR::ResultCode result = m_serializer.Store(*m_jsonDocument, instance.get(), &nullPtr, + SmartPointer defaultInstance; + JSR::ResultCode result = m_serializer.Store( + *m_jsonDocument, instance.get(), &defaultInstance, azrtti_typeid(), *m_jsonSerializationContext); EXPECT_EQ(JSR::Outcomes::Success, result.GetOutcome()); } + TEST_F(JsonSmartPointerSerializerTests, Store_ValuePointerIsNullPtr_ReturnsSuccessAndStoresNull) + { + namespace JSR = AZ::JsonSerializationResult; + + SmartPointer instance; + AZStd::shared_ptr defaultInstance = m_description.CreateFullySetInstance(); + JSR::ResultCode result = m_serializer.Store( + *m_jsonDocument, &instance, defaultInstance.get(), azrtti_typeid(), *m_jsonSerializationContext); + + EXPECT_EQ(JSR::Outcomes::Success, result.GetOutcome()); + EXPECT_TRUE(m_jsonDocument->IsNull()); + } + + TEST_F(JsonSmartPointerSerializerTests, Store_ValueAndDefaultPointersAreNullPtr_ReturnsSuccessAndStoresNull) + { + namespace JSR = AZ::JsonSerializationResult; + + SmartPointer instance; + SmartPointer defaultInstance; + JSR::ResultCode result = + m_serializer.Store(*m_jsonDocument, &instance, &defaultInstance, azrtti_typeid(), *m_jsonSerializationContext); + + EXPECT_EQ(JSR::Outcomes::DefaultsUsed, result.GetOutcome()); + EXPECT_TRUE(m_jsonDocument->IsNull()); + } + + TEST_F(JsonSmartPointerSerializerTests, Store_ValueAndDefaultPointersAreBothDefault_ReturnsSuccess) + { + namespace JSR = AZ::JsonSerializationResult; + + AZStd::shared_ptr instance = m_description.CreateDefaultInstance(); + AZStd::shared_ptr defaultInstance = m_description.CreateDefaultInstance(); + JSR::ResultCode result = + m_serializer.Store(*m_jsonDocument, instance.get(), defaultInstance.get(), azrtti_typeid(), *m_jsonSerializationContext); + + EXPECT_EQ(JSR::Outcomes::DefaultsUsed, result.GetOutcome()); + Expect_ExplicitDefault(*m_jsonDocument); + } + + TEST_F(JsonSmartPointerSerializerTests, Store_ValueHasDefaultValuesAndDefaultHasNullPointer_ReturnsSuccess) + { + namespace JSR = AZ::JsonSerializationResult; + + AZStd::shared_ptr instance = m_description.CreateDefaultInstance(); + SmartPointer defaultInstance; + JSR::ResultCode result = m_serializer.Store( + *m_jsonDocument, instance.get(), &defaultInstance, azrtti_typeid(), *m_jsonSerializationContext); + + EXPECT_EQ(JSR::Outcomes::DefaultsUsed, result.GetOutcome()); + Expect_ExplicitDefault(*m_jsonDocument); + } + TEST_F(JsonSmartPointerSerializerTests, Store_DefaultPointerIsOtherClass_CompletesButDoesNotReturnDefaults) { namespace JSR = AZ::JsonSerializationResult; @@ -749,7 +831,7 @@ namespace JsonSerializationTests EXPECT_EQ(JSR::Processing::Completed, result.GetProcessing()); } - TEST_F(JsonSmartPointerSerializerTests, Store_SaveAnClassThatIsNotReflected_ReturnsUnknown) + TEST_F(JsonSmartPointerSerializerTests, Store_ClassThatIsNotReflected_ReturnsUnknown) { namespace JSR = AZ::JsonSerializationResult; 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 089/185] 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 f770e4aa7a8efcc26d1540bb7b221129726c2eb6 Mon Sep 17 00:00:00 2001 From: Aaron Ruiz Mora Date: Tue, 4 May 2021 19:12:01 +0100 Subject: [PATCH 090/185] Unifying operators in Matrix3x3, Matrix3x4 and Matrix4x4 - Add operators +, -, * and / too all matrix classes - Add RetrieveScaleSq and GetReciprocalScaled to all matrix classes - Add unit tests to all matrix classes - Fix a bug that causes release configuration not to compile. --- Code/Framework/AzCore/AzCore/Math/Matrix3x3.h | 49 +++-- .../AzCore/AzCore/Math/Matrix3x3.inl | 111 ++++++---- Code/Framework/AzCore/AzCore/Math/Matrix3x4.h | 41 +++- .../AzCore/AzCore/Math/Matrix3x4.inl | 81 ++++++-- Code/Framework/AzCore/AzCore/Math/Matrix4x4.h | 44 +++- .../AzCore/AzCore/Math/Matrix4x4.inl | 107 ++++++++-- .../AzCore/Tests/Math/Matrix3x3Tests.cpp | 131 +++++++----- .../AzCore/Tests/Math/Matrix3x4Tests.cpp | 177 +++++++++++----- .../AzCore/Tests/Math/Matrix4x4Tests.cpp | 194 ++++++++++++++++-- .../ValuePointerReferenceExample.cpp | 2 +- 10 files changed, 728 insertions(+), 209 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x3.h b/Code/Framework/AzCore/AzCore/Math/Matrix3x3.h index e1736e1444..973bb52df3 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x3.h +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x3.h @@ -142,27 +142,44 @@ namespace AZ void SetBasis(const Vector3& basisX, const Vector3& basisY, const Vector3& basisZ); //! @} - Matrix3x3 operator*(const Matrix3x3& rhs) const; - //! Calculates (this->GetTranspose() * rhs). Matrix3x3 TransposedMultiply(const Matrix3x3& rhs) const; //! Post-multiplies the matrix by a vector. Vector3 operator*(const Vector3& rhs) const; - Matrix3x3 operator+(const Matrix3x3& rhs) const; - Matrix3x3 operator-(const Matrix3x3& rhs) const; - - Matrix3x3 operator*(float multiplier) const; - Matrix3x3 operator/(float divisor) const; + //! Operator for matrix-matrix addition. + //! @{ + [[nodiscard]] Matrix3x3 operator+(const Matrix3x3& rhs) const; + Matrix3x3& operator+=(const Matrix3x3& rhs); + //! @} - Matrix3x3 operator-() const; + //! Operator for matrix-matrix substraction. + //! @{ + [[nodiscard]] Matrix3x3 operator-(const Matrix3x3& rhs) const; + Matrix3x3& operator-=(const Matrix3x3& rhs); + //! @} + //! Operator for matrix-matrix multiplication. + //! @{ + [[nodiscard]] Matrix3x3 operator*(const Matrix3x3& rhs) const; Matrix3x3& operator*=(const Matrix3x3& rhs); - Matrix3x3& operator+=(const Matrix3x3& rhs); - Matrix3x3& operator-=(const Matrix3x3& rhs); + //! @} + + //! Operator for multiplying all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix3x3 operator*(float multiplier) const; Matrix3x3& operator*=(float multiplier); + //! @} + + //! Operator for dividing all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix3x3 operator/(float divisor) const; Matrix3x3& operator/=(float divisor); + //! @} + + //! Operator for negating all matrix's elements + [[nodiscard]] Matrix3x3 operator-() const; bool operator==(const Matrix3x3& rhs) const; bool operator!=(const Matrix3x3& rhs) const; @@ -187,7 +204,10 @@ namespace AZ //! @} //! Gets the scale part of the transformation, i.e. the length of the scale components. - Vector3 RetrieveScale() const; + [[nodiscard]] Vector3 RetrieveScale() const; + + //! Gets the squared scale part of the transformation (the squared length of the basis vectors). + [[nodiscard]] Vector3 RetrieveScaleSq() const; //! Gets the scale part of the transformation as in RetrieveScale, and also removes this scaling from the matrix. Vector3 ExtractScale(); @@ -195,6 +215,9 @@ namespace AZ //! Quick multiplication by a scale matrix, equivalent to m*=Matrix3x3::CreateScale(scale). void MultiplyByScale(const Vector3& scale); + //! Returns a matrix with the reciprocal scale, keeping the same rotation and translation. + [[nodiscard]] Matrix3x3 GetReciprocalScaled() const; + //! Polar decomposition, M=U*H, U is orthogonal (unitary) and H is symmetric (hermitian). //! This function returns the orthogonal part only Matrix3x3 GetPolarDecomposition() const; @@ -241,7 +264,9 @@ namespace AZ //! Note that this is not the usual multiplication order for transformations. Vector3& operator*=(Vector3& lhs, const Matrix3x3& rhs); + //! Pre-multiplies the matrix by a scalar. Matrix3x3 operator*(float lhs, const Matrix3x3& rhs); -} + +} // namespace AZ #include diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x3.inl b/Code/Framework/AzCore/AzCore/Math/Matrix3x3.inl index ff92da1398..6b4dccf3c1 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x3.inl +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x3.inl @@ -392,14 +392,6 @@ namespace AZ } - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator*(const Matrix3x3& rhs) const - { - Matrix3x3 result; - Simd::Vec3::Mat3x3Multiply(GetSimdValues(), rhs.GetSimdValues(), result.GetSimdValues()); - return result; - } - - AZ_MATH_INLINE Matrix3x3 Matrix3x3::TransposedMultiply(const Matrix3x3& rhs) const { Matrix3x3 result; @@ -416,44 +408,45 @@ namespace AZ AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator+(const Matrix3x3& rhs) const { - return Matrix3x3(Simd::Vec3::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) - , Simd::Vec3::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()) - , Simd::Vec3::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue())); + return Matrix3x3 + ( + Simd::Vec3::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec3::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec3::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) + ); } - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator-(const Matrix3x3& rhs) const + AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator+=(const Matrix3x3& rhs) { - return Matrix3x3(Simd::Vec3::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) - , Simd::Vec3::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()) - , Simd::Vec3::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue())); + *this = *this + rhs; + return *this; } - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator*(float multiplier) const + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator-(const Matrix3x3& rhs) const { - const Simd::Vec3::FloatType mulVec = Simd::Vec3::Splat(multiplier); - return Matrix3x3(Simd::Vec3::Mul(m_rows[0].GetSimdValue(), mulVec) - , Simd::Vec3::Mul(m_rows[1].GetSimdValue(), mulVec) - , Simd::Vec3::Mul(m_rows[2].GetSimdValue(), mulVec)); + return Matrix3x3 + ( + Simd::Vec3::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec3::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec3::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) + ); } - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator/(float divisor) const + AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator-=(const Matrix3x3& rhs) { - const Simd::Vec3::FloatType divVec = Simd::Vec3::Splat(divisor); - return Matrix3x3(Simd::Vec3::Div(m_rows[0].GetSimdValue(), divVec) - , Simd::Vec3::Div(m_rows[1].GetSimdValue(), divVec) - , Simd::Vec3::Div(m_rows[2].GetSimdValue(), divVec)); + *this = *this - rhs; + return *this; } - AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator-() const + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator*(const Matrix3x3& rhs) const { - const Simd::Vec3::FloatType zeroVec = Simd::Vec3::ZeroFloat(); - return Matrix3x3(Simd::Vec3::Sub(zeroVec, m_rows[0].GetSimdValue()) - , Simd::Vec3::Sub(zeroVec, m_rows[1].GetSimdValue()) - , Simd::Vec3::Sub(zeroVec, m_rows[2].GetSimdValue())); + Matrix3x3 result; + Simd::Vec3::Mat3x3Multiply(GetSimdValues(), rhs.GetSimdValues(), result.GetSimdValues()); + return result; } @@ -464,24 +457,34 @@ namespace AZ } - AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator+=(const Matrix3x3& rhs) + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator*(float multiplier) const { - *this = *this + rhs; - return *this; + const Simd::Vec3::FloatType mulVec = Simd::Vec3::Splat(multiplier); + return Matrix3x3 + ( + Simd::Vec3::Mul(m_rows[0].GetSimdValue(), mulVec), + Simd::Vec3::Mul(m_rows[1].GetSimdValue(), mulVec), + Simd::Vec3::Mul(m_rows[2].GetSimdValue(), mulVec) + ); } - AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator-=(const Matrix3x3& rhs) + AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator*=(float multiplier) { - *this = *this - rhs; + *this = *this * multiplier; return *this; } - AZ_MATH_INLINE Matrix3x3& Matrix3x3::operator*=(float multiplier) + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator/(float divisor) const { - *this = *this * multiplier; - return *this; + const Simd::Vec3::FloatType divVec = Simd::Vec3::Splat(divisor); + return Matrix3x3 + ( + Simd::Vec3::Div(m_rows[0].GetSimdValue(), divVec), + Simd::Vec3::Div(m_rows[1].GetSimdValue(), divVec), + Simd::Vec3::Div(m_rows[2].GetSimdValue(), divVec) + ); } @@ -492,6 +495,18 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x3 Matrix3x3::operator-() const + { + const Simd::Vec3::FloatType zeroVec = Simd::Vec3::ZeroFloat(); + return Matrix3x3 + ( + Simd::Vec3::Sub(zeroVec, m_rows[0].GetSimdValue()), + Simd::Vec3::Sub(zeroVec, m_rows[1].GetSimdValue()), + Simd::Vec3::Sub(zeroVec, m_rows[2].GetSimdValue()) + ); + } + + AZ_MATH_INLINE bool Matrix3x3::operator==(const Matrix3x3& rhs) const { return (Simd::Vec3::CmpAllEq(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) @@ -552,6 +567,12 @@ namespace AZ } + AZ_MATH_INLINE Vector3 Matrix3x3::RetrieveScaleSq() const + { + return Vector3(GetBasisX().GetLengthSq(), GetBasisY().GetLengthSq(), GetBasisZ().GetLengthSq()); + } + + AZ_MATH_INLINE Vector3 Matrix3x3::ExtractScale() { const Vector3 x = GetBasisX(); @@ -584,6 +605,14 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x3 Matrix3x3::GetReciprocalScaled() const + { + Matrix3x3 result = *this; + result.MultiplyByScale(RetrieveScaleSq().GetReciprocal()); + return result; + } + + AZ_MATH_INLINE void Matrix3x3::GetPolarDecomposition(Matrix3x3* orthogonalOut, Matrix3x3* symmetricOut) const { *orthogonalOut = GetPolarDecomposition(); @@ -679,8 +708,6 @@ namespace AZ AZ_MATH_INLINE Matrix3x3 operator*(float lhs, const Matrix3x3& rhs) { - const Simd::Vec3::FloatType lhsVec = Simd::Vec3::Splat(lhs); - const Simd::Vec3::FloatType* rows = rhs.GetSimdValues(); - return Matrix3x3(Simd::Vec3::Mul(lhsVec, rows[0]), Simd::Vec3::Mul(lhsVec, rows[1]), Simd::Vec3::Mul(lhsVec, rows[2])); + return rhs * lhs; } -} +} // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h index 09f443c1cf..a18f1e7565 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.h @@ -225,23 +225,38 @@ namespace AZ //! Sets the three basis vectors and the translation. void SetBasisAndTranslation(const Vector3& basisX, const Vector3& basisY, const Vector3& basisZ, const Vector3& translation); - //! Operator for matrix-matrix multiplication. - [[nodiscard]] Matrix3x4 operator*(const Matrix3x4& rhs) const; - - //! Compound assignment operator for matrix-matrix multiplication. - Matrix3x4& operator*=(const Matrix3x4& rhs); - //! Operator for matrix-matrix addition. + //! @{ [[nodiscard]] Matrix3x4 operator+(const Matrix3x4& rhs) const; - - //! Compound assignment operator for matrix-matrix addition. Matrix3x4& operator+=(const Matrix3x4& rhs); + //! @} + + //! Operator for matrix-matrix substraction. + //! @{ + [[nodiscard]] Matrix3x4 operator-(const Matrix3x4& rhs) const; + Matrix3x4& operator-=(const Matrix3x4& rhs); + //! @} + + //! Operator for matrix-matrix multiplication. + //! @{ + [[nodiscard]] Matrix3x4 operator*(const Matrix3x4& rhs) const; + Matrix3x4& operator*=(const Matrix3x4& rhs); + //! @} //! Operator for multiplying all matrix's elements with a scalar - [[nodiscard]] Matrix3x4 operator*(float scalar) const; + //! @{ + [[nodiscard]] Matrix3x4 operator*(float multiplier) const; + Matrix3x4& operator*=(float multiplier); + //! @} - //! Compound assignment operator for multiplying all matrix's elements with a scalar - Matrix3x4& operator*=(float scalar); + //! Operator for dividing all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix3x4 operator/(float divisor) const; + Matrix3x4& operator/=(float divisor); + //! @} + + //! Operator for negating all matrix's elements + [[nodiscard]] Matrix3x4 operator-() const; //! Operator for transforming a Vector3. [[nodiscard]] Vector3 operator*(const Vector3& rhs) const; @@ -353,6 +368,10 @@ namespace AZ Vector4 m_rows[RowCount]; }; + + //! Pre-multiplies the matrix by a scalar. + Matrix3x4 operator*(float lhs, const Matrix3x4& rhs); + } // namespace AZ #include diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl index 232e8a5b30..781dcf9b66 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl +++ b/Code/Framework/AzCore/AzCore/Math/Matrix3x4.inl @@ -472,6 +472,42 @@ namespace AZ } + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator+(const Matrix3x4& rhs) const + { + return Matrix3x4 + ( + Simd::Vec4::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec4::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec4::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) + ); + } + + + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator+=(const Matrix3x4& rhs) + { + *this = *this + rhs; + return *this; + } + + + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator-(const Matrix3x4& rhs) const + { + return Matrix3x4 + ( + Simd::Vec4::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec4::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec4::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) + ); + } + + + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator-=(const Matrix3x4& rhs) + { + *this = *this - rhs; + return *this; + } + + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator*(const Matrix3x4& rhs) const { Matrix3x4 result; @@ -487,43 +523,56 @@ namespace AZ } - AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator+(const Matrix3x4& rhs) const + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator*(float multiplier) const { + const Simd::Vec4::FloatType mulVec = Simd::Vec4::Splat(multiplier); return Matrix3x4 ( - Simd::Vec4::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), - Simd::Vec4::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), - Simd::Vec4::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) + Simd::Vec4::Mul(m_rows[0].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[1].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[2].GetSimdValue(), mulVec) ); } - AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator+=(const Matrix3x4& rhs) + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator*=(float multiplier) { - *this = *this + rhs; + *this = *this * multiplier; return *this; } - AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator*(float scalar) const + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator/(float divisor) const { - const Vector4 vector4Scalar(scalar); + const Simd::Vec4::FloatType divVec = Simd::Vec4::Splat(divisor); return Matrix3x4 ( - Simd::Vec4::Mul(m_rows[0].GetSimdValue(), vector4Scalar.GetSimdValue()), - Simd::Vec4::Mul(m_rows[1].GetSimdValue(), vector4Scalar.GetSimdValue()), - Simd::Vec4::Mul(m_rows[2].GetSimdValue(), vector4Scalar.GetSimdValue()) + Simd::Vec4::Div(m_rows[0].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[1].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[2].GetSimdValue(), divVec) ); } - AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator*=(float scalar) + AZ_MATH_INLINE Matrix3x4& Matrix3x4::operator/=(float divisor) { - *this = *this * scalar; + *this = *this / divisor; return *this; } + AZ_MATH_INLINE Matrix3x4 Matrix3x4::operator-() const + { + const Simd::Vec4::FloatType zeroVec = Simd::Vec4::ZeroFloat(); + return Matrix3x4 + ( + Simd::Vec4::Sub(zeroVec, m_rows[0].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[1].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[2].GetSimdValue()) + ); + } + + AZ_MATH_INLINE Vector3 Matrix3x4::operator*(const Vector3& rhs) const { return Vector3 @@ -711,4 +760,10 @@ namespace AZ { return reinterpret_cast(m_rows); } + + + AZ_MATH_INLINE Matrix3x4 operator*(float lhs, const Matrix3x4& rhs) + { + return rhs * lhs; + } } // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix4x4.h b/Code/Framework/AzCore/AzCore/Math/Matrix4x4.h index 1612f8c962..a94b3c7ae2 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix4x4.h +++ b/Code/Framework/AzCore/AzCore/Math/Matrix4x4.h @@ -171,14 +171,38 @@ namespace AZ void SetTranslation(const Vector3& v); //! @} - Matrix4x4 operator+(const Matrix4x4& rhs) const; + //! Operator for matrix-matrix addition. + //! @{ + [[nodiscard]] Matrix4x4 operator+(const Matrix4x4& rhs) const; Matrix4x4& operator+=(const Matrix4x4& rhs); + //! @} - Matrix4x4 operator-(const Matrix4x4& rhs) const; + //! Operator for matrix-matrix substraction. + //! @{ + [[nodiscard]] Matrix4x4 operator-(const Matrix4x4& rhs) const; Matrix4x4& operator-=(const Matrix4x4& rhs); + //! @} - Matrix4x4 operator*(const Matrix4x4& rhs) const; + //! Operator for matrix-matrix multiplication. + //! @{ + [[nodiscard]] Matrix4x4 operator*(const Matrix4x4& rhs) const; Matrix4x4& operator*=(const Matrix4x4& rhs); + //! @} + + //! Operator for multiplying all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix4x4 operator*(float multiplier) const; + Matrix4x4& operator*=(float multiplier); + //! @} + + //! Operator for dividing all matrix's elements with a scalar + //! @{ + [[nodiscard]] Matrix4x4 operator/(float divisor) const; + Matrix4x4& operator/=(float divisor); + //! @} + + //! Operator for negating all matrix's elements + [[nodiscard]] Matrix4x4 operator-() const; //! Post-multiplies the matrix by a vector. //! Assumes that the w-component of the Vector3 is 1.0. @@ -222,7 +246,10 @@ namespace AZ //! @} //! Gets the scale part of the transformation, i.e. the length of the scale components. - Vector3 RetrieveScale() const; + [[nodiscard]] Vector3 RetrieveScale() const; + + //! Gets the squared scale part of the transformation (the squared length of the basis vectors). + [[nodiscard]] Vector3 RetrieveScaleSq() const; //! Gets the scale part of the transformation as in RetrieveScale, and also removes this scaling from the matrix. Vector3 ExtractScale(); @@ -230,6 +257,9 @@ namespace AZ //! Quick multiplication by a scale matrix, equivalent to m*=Matrix4x4::CreateScale(scale). void MultiplyByScale(const Vector3& scale); + //! Returns a matrix with the reciprocal scale, keeping the same rotation and translation. + [[nodiscard]] Matrix4x4 GetReciprocalScaled() const; + bool IsClose(const Matrix4x4& rhs, float tolerance = Constants::Tolerance) const; bool operator==(const Matrix4x4& rhs) const; @@ -270,6 +300,10 @@ namespace AZ //! Pre-multiplies the matrix by a vector in-place. //! Note that this is not the usual multiplication order for transformations. Vector4& operator*=(Vector4& lhs, const Matrix4x4& rhs); -} + + //! Pre-multiplies the matrix by a scalar. + Matrix4x4 operator*(float lhs, const Matrix4x4& rhs); + +} // namespace AZ #include diff --git a/Code/Framework/AzCore/AzCore/Math/Matrix4x4.inl b/Code/Framework/AzCore/AzCore/Math/Matrix4x4.inl index 3c4572accd..e32ebe31af 100644 --- a/Code/Framework/AzCore/AzCore/Math/Matrix4x4.inl +++ b/Code/Framework/AzCore/AzCore/Math/Matrix4x4.inl @@ -480,20 +480,12 @@ namespace AZ AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator+(const Matrix4x4& rhs) const { return Matrix4x4 - ( Simd::Vec4::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) - , Simd::Vec4::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()) - , Simd::Vec4::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) - , Simd::Vec4::Add(m_rows[3].GetSimdValue(), rhs.m_rows[3].GetSimdValue())); - } - - - AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator-(const Matrix4x4& rhs) const - { - return Matrix4x4 - ( Simd::Vec4::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()) - , Simd::Vec4::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()) - , Simd::Vec4::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()) - , Simd::Vec4::Sub(m_rows[3].GetSimdValue(), rhs.m_rows[3].GetSimdValue())); + ( + Simd::Vec4::Add(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec4::Add(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec4::Add(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()), + Simd::Vec4::Add(m_rows[3].GetSimdValue(), rhs.m_rows[3].GetSimdValue()) + ); } AZ_MATH_INLINE Matrix4x4& Matrix4x4::operator+=(const Matrix4x4& rhs) @@ -502,6 +494,18 @@ namespace AZ return *this; } + + AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator-(const Matrix4x4& rhs) const + { + return Matrix4x4 + ( + Simd::Vec4::Sub(m_rows[0].GetSimdValue(), rhs.m_rows[0].GetSimdValue()), + Simd::Vec4::Sub(m_rows[1].GetSimdValue(), rhs.m_rows[1].GetSimdValue()), + Simd::Vec4::Sub(m_rows[2].GetSimdValue(), rhs.m_rows[2].GetSimdValue()), + Simd::Vec4::Sub(m_rows[3].GetSimdValue(), rhs.m_rows[3].GetSimdValue()) + ); + } + AZ_MATH_INLINE Matrix4x4& Matrix4x4::operator-=(const Matrix4x4& rhs) { *this = *this - rhs; @@ -523,6 +527,59 @@ namespace AZ } + AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator*(float multiplier) const + { + const Simd::Vec4::FloatType mulVec = Simd::Vec4::Splat(multiplier); + return Matrix4x4 + ( + Simd::Vec4::Mul(m_rows[0].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[1].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[2].GetSimdValue(), mulVec), + Simd::Vec4::Mul(m_rows[3].GetSimdValue(), mulVec) + ); + } + + + AZ_MATH_INLINE Matrix4x4& Matrix4x4::operator*=(float multiplier) + { + *this = *this * multiplier; + return *this; + } + + + AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator/(float divisor) const + { + const Simd::Vec4::FloatType divVec = Simd::Vec4::Splat(divisor); + return Matrix4x4 + ( + Simd::Vec4::Div(m_rows[0].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[1].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[2].GetSimdValue(), divVec), + Simd::Vec4::Div(m_rows[3].GetSimdValue(), divVec) + ); + } + + + AZ_MATH_INLINE Matrix4x4& Matrix4x4::operator/=(float divisor) + { + *this = *this / divisor; + return *this; + } + + + AZ_MATH_INLINE Matrix4x4 Matrix4x4::operator-() const + { + const Simd::Vec4::FloatType zeroVec = Simd::Vec4::ZeroFloat(); + return Matrix4x4 + ( + Simd::Vec4::Sub(zeroVec, m_rows[0].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[1].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[2].GetSimdValue()), + Simd::Vec4::Sub(zeroVec, m_rows[3].GetSimdValue()) + ); + } + + AZ_MATH_INLINE Vector3 Matrix4x4::operator*(const Vector3& rhs) const { return Vector3(Simd::Vec4::Mat4x4TransformPoint3(GetSimdValues(), rhs.GetSimdValue())); @@ -595,6 +652,12 @@ namespace AZ } + AZ_MATH_INLINE Vector3 Matrix4x4::RetrieveScaleSq() const + { + return Vector3(GetBasisX().GetLengthSq(), GetBasisY().GetLengthSq(), GetBasisZ().GetLengthSq()); + } + + AZ_MATH_INLINE Vector3 Matrix4x4::ExtractScale() { Vector4 x = GetBasisX(); @@ -619,6 +682,14 @@ namespace AZ } + AZ_MATH_INLINE Matrix4x4 Matrix4x4::GetReciprocalScaled() const + { + Matrix4x4 result = *this; + result.MultiplyByScale(RetrieveScaleSq().GetReciprocal()); + return result; + } + + AZ_MATH_INLINE bool Matrix4x4::IsClose(const Matrix4x4& rhs, float tolerance) const { const Simd::Vec4::FloatType vecTolerance = Simd::Vec4::Splat(tolerance); @@ -702,4 +773,10 @@ namespace AZ lhs = lhs * rhs; return lhs; } -} + + + AZ_MATH_INLINE Matrix4x4 operator*(float lhs, const Matrix4x4& rhs) + { + return rhs * lhs; + } +} // namespace AZ diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp index a849cfdaab..efa0ee531c 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x3Tests.cpp @@ -14,6 +14,7 @@ #include #include #include +#include using namespace AZ; @@ -251,19 +252,19 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 * m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(66.0f, 72.0f, 78.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(156.0f, 171.0f, 186.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(246.0f, 270.0f, 294.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(66.0f, 72.0f, 78.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(156.0f, 171.0f, 186.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(246.0f, 270.0f, 294.0f))); Matrix3x3 m4 = m1; m4 *= m2; - AZ_TEST_ASSERT(m4.GetRow(0).IsClose(Vector3(66.0f, 72.0f, 78.0f))); - AZ_TEST_ASSERT(m4.GetRow(1).IsClose(Vector3(156.0f, 171.0f, 186.0f))); - AZ_TEST_ASSERT(m4.GetRow(2).IsClose(Vector3(246.0f, 270.0f, 294.0f))); + EXPECT_THAT(m4.GetRow(0), IsClose(Vector3(66.0f, 72.0f, 78.0f))); + EXPECT_THAT(m4.GetRow(1), IsClose(Vector3(156.0f, 171.0f, 186.0f))); + EXPECT_THAT(m4.GetRow(2), IsClose(Vector3(246.0f, 270.0f, 294.0f))); m3 = m1.TransposedMultiply(m2); - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(138.0f, 150.0f, 162.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(168.0f, 183.0f, 198.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(198.0f, 216.0f, 234.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(138.0f, 150.0f, 162.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(168.0f, 183.0f, 198.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(198.0f, 216.0f, 234.0f))); } TEST(MATH_Matrix3x3, TestVectorMultiplication) @@ -277,11 +278,11 @@ namespace UnitTest m2.SetRow(1, 10.0f, 11.0f, 12.0f); m2.SetRow(2, 13.0f, 14.0f, 15.0f); - AZ_TEST_ASSERT((m1 * Vector3(1.0f, 2.0f, 3.0f)).IsClose(Vector3(14.0f, 32.0f, 50.0f))); + EXPECT_THAT((m1 * Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(14.0f, 32.0f, 50.0f))); Vector3 v1(1.0f, 2.0f, 3.0f); - AZ_TEST_ASSERT((v1 * m1).IsClose(Vector3(30.0f, 36.0f, 42.0f))); + EXPECT_THAT((v1 * m1), IsClose(Vector3(30.0f, 36.0f, 42.0f))); v1 *= m1; - AZ_TEST_ASSERT(v1.IsClose(Vector3(30.0f, 36.0f, 42.0f))); + EXPECT_THAT(v1, IsClose(Vector3(30.0f, 36.0f, 42.0f))); } TEST(MATH_Matrix3x3, TestSum) @@ -296,15 +297,15 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 + m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(14.0f, 16.0f, 18.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(20.0f, 22.0f, 24.0f))); m3 = m1; m3 += m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(14.0f, 16.0f, 18.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(20.0f, 22.0f, 24.0f))); } TEST(MATH_Matrix3x3, TestDifference) @@ -319,14 +320,14 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 - m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); m3 = m1; m3 -= m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(-6.0f, -6.0f, -6.0f))); } TEST(MATH_Matrix3x3, TestScalarMultiplication) @@ -341,18 +342,18 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 * 2.0f; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = m1; m3 *= 2.0f; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = 2.0f * m1; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); } TEST(MATH_Matrix3x3, TestScalarDivision) @@ -367,18 +368,32 @@ namespace UnitTest m2.SetRow(2, 13.0f, 14.0f, 15.0f); Matrix3x3 m3 = m1 / 0.5f; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); m3 = m1; m3 /= 0.5f; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(2.0f, 4.0f, 6.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(8.0f, 10.0f, 12.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(14.0f, 16.0f, 18.0f))); - m3 = -m1; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector3(-1.0f, -2.0f, -3.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector3(-4.0f, -5.0f, -6.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector3(-7.0f, -8.0f, -9.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector3(2.0f, 4.0f, 6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector3(8.0f, 10.0f, 12.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector3(14.0f, 16.0f, 18.0f))); + } + + TEST(MATH_Matrix3x3, TestNegation) + { + Matrix3x3 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f); + m1.SetRow(1, 4.0f, 5.0f, 6.0f); + m1.SetRow(2, 7.0f, 8.0f, 9.0f); + EXPECT_THAT(-(-m1), IsClose(m1)); + EXPECT_THAT(-Matrix3x3::CreateZero(), IsClose(Matrix3x3::CreateZero())); + + Matrix3x3 m2 = -m1; + EXPECT_THAT(m2.GetRow(0), IsClose(Vector3(-1.0f, -2.0f, -3.0f))); + EXPECT_THAT(m2.GetRow(1), IsClose(Vector3(-4.0f, -5.0f, -6.0f))); + EXPECT_THAT(m2.GetRow(2), IsClose(Vector3(-7.0f, -8.0f, -9.0f))); + + Matrix3x3 m3 = m1 + (-m1); + EXPECT_THAT(m3, IsClose(Matrix3x3::CreateZero())); } TEST(MATH_Matrix3x3, TestTranspose) @@ -425,11 +440,33 @@ namespace UnitTest TEST(MATH_Matrix3x3, TestScaleAccess) { Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(40.0f)) * Matrix3x3::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); - AZ_TEST_ASSERT(m1.RetrieveScale().IsClose(Vector3(2.0f, 3.0f, 4.0f))); - AZ_TEST_ASSERT(m1.ExtractScale().IsClose(Vector3(2.0f, 3.0f, 4.0f))); - AZ_TEST_ASSERT(m1.RetrieveScale().IsClose(Vector3::CreateOne())); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); + EXPECT_THAT(m1.ExtractScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3::CreateOne())); m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); - AZ_TEST_ASSERT(m1.RetrieveScale().IsClose(Vector3(3.0f, 4.0f, 5.0f))); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(3.0f, 4.0f, 5.0f))); + } + + TEST(MATH_Matrix3x3, TestScaleSqAccess) + { + Matrix3x3 m1 = Matrix3x3::CreateRotationX(DegToRad(40.0f)) * Matrix3x3::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(4.0f, 9.0f, 16.0f))); + m1.ExtractScale(); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3::CreateOne())); + m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(9.0f, 16.0f, 25.0f))); + } + + TEST(MATH_Matrix3x3, TestReciprocalScaled) + { + Matrix3x3 orthogonalMatrix = Matrix3x3::CreateRotationX(DegToRad(40.0f)); + EXPECT_THAT(orthogonalMatrix.GetReciprocalScaled(), IsClose(orthogonalMatrix)); + const AZ::Vector3 scale(2.8f, 0.7f, 1.3f); + AZ::Matrix3x3 scaledMatrix = orthogonalMatrix; + scaledMatrix.MultiplyByScale(scale); + AZ::Matrix3x3 reciprocalScaledMatrix = orthogonalMatrix; + reciprocalScaledMatrix.MultiplyByScale(scale.GetReciprocal()); + EXPECT_THAT(scaledMatrix.GetReciprocalScaled(), IsClose(reciprocalScaledMatrix)); } TEST(MATH_Matrix3x3, TestPolarDecomposition) diff --git a/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp index 353b46874b..0bb64411e6 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix3x4Tests.cpp @@ -467,53 +467,136 @@ namespace UnitTest EXPECT_THAT(matrix.Multiply3x3(axisDirection), IsClose(forwardDirection)); } - TEST(MATH_Matrix3x4, MultiplyByMatrix3x4) - { - const AZ::Matrix3x4 matrix1 = AZ::Matrix3x4::CreateFromValue(1.2f); - const AZ::Matrix3x4 matrix2 = AZ::Matrix3x4::CreateDiagonal(AZ::Vector3(1.3f, 1.5f, 0.4f)); - const AZ::Matrix3x4 matrix3 = AZ::Matrix3x4::CreateFromQuaternionAndTranslation( - AZ::Quaternion(0.42f, 0.46f, -0.66f, 0.42f), AZ::Vector3(2.8f, -3.7f, 1.6f)); - const AZ::Matrix3x4 matrix4 = AZ::Matrix3x4::CreateRotationX(-0.7f) * AZ::Matrix3x4::CreateScale(AZ::Vector3(0.6f, 1.3f, 0.7f)); - AZ::Matrix3x4 matrix5 = matrix1; - matrix5 *= matrix4; - const AZ::Vector3 vector(1.9f, 2.3f, 0.2f); - EXPECT_TRUE((matrix1 * (matrix2 * matrix3)).IsClose((matrix1 * matrix2) * matrix3)); - EXPECT_THAT((matrix3 * matrix4) * vector, IsClose(matrix3 * (matrix4 * vector))); - EXPECT_TRUE((matrix2 * AZ::Matrix3x4::Identity()).IsClose(matrix2)); - EXPECT_TRUE((matrix3 * AZ::Matrix3x4::Identity()).IsClose(AZ::Matrix3x4::Identity() * matrix3)); - EXPECT_TRUE(matrix5.IsClose(matrix1 * matrix4)); - } - - TEST(MATH_Matrix3x4, AddMatrix3x4) - { - const AZ::Matrix3x4 matrix1 = AZ::Matrix3x4::CreateFromValue(1.2f); - const AZ::Matrix3x4 matrix2 = AZ::Matrix3x4::CreateDiagonal(AZ::Vector3(1.3f, 1.5f, 0.4f)); - const AZ::Matrix3x4 matrix3 = AZ::Matrix3x4::CreateFromQuaternionAndTranslation( - AZ::Quaternion(0.42f, 0.46f, -0.66f, 0.42f), AZ::Vector3(2.8f, -3.7f, 1.6f)); - const AZ::Matrix3x4 matrix4 = AZ::Matrix3x4::CreateRotationX(-0.7f) * AZ::Matrix3x4::CreateScale(AZ::Vector3(0.6f, 1.3f, 0.7f)); - AZ::Matrix3x4 matrix5 = matrix1; - matrix5 += matrix4; - EXPECT_THAT(matrix1 + (matrix2 + matrix3), IsClose((matrix1 + matrix2) + matrix3)); - EXPECT_THAT(matrix2 + AZ::Matrix3x4::CreateZero(), IsClose(matrix2)); - EXPECT_THAT(matrix3 + AZ::Matrix3x4::CreateZero(), IsClose(AZ::Matrix3x4::CreateZero() + matrix3)); - EXPECT_THAT(matrix3 + matrix3, IsClose(matrix3 * 2.0f)); - EXPECT_THAT(matrix5, IsClose(matrix1 + matrix4)); - } - - TEST(MATH_Matrix3x4, MultiplyByScalar) - { - const AZ::Vector4 row0(1.488f, 2.56f, 0.096f, 2.3f); - const AZ::Vector4 row1(0.384f, -1.92f, 0.428f, -1.6f); - const AZ::Vector4 row2(1.28f, -2.4f, -0.24f, 3.7f); - const float scalar = 3.2f; - const AZ::Vector4 row0Result = row0 * scalar; - const AZ::Vector4 row1Result = row1 * scalar; - const AZ::Vector4 row2Result = row2 * scalar; - AZ::Matrix3x4 matrix = AZ::Matrix3x4::CreateFromRows(row0, row1, row2); - EXPECT_THAT(matrix * 0.0f, IsClose(AZ::Matrix3x4::CreateZero())); - EXPECT_THAT(matrix * 1.0f, IsClose(matrix)); - EXPECT_THAT(matrix * scalar, IsClose(AZ::Matrix3x4::CreateFromRows(row0Result, row1Result, row2Result))); - EXPECT_THAT(matrix * 2.0f, IsClose(matrix + matrix)); + TEST(MATH_Matrix3x4, TestMatrixMultiplication) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + AZ::Matrix3x4 m3 = m1 * m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(74.0f, 80.0f, 86.0f, 96.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(206.0f, 224.0f, 242.0f, 268.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(338.0f, 368.0f, 398.0f, 440.0f))); + AZ::Matrix3x4 m4 = m1; + m4 *= m2; + EXPECT_THAT(m4.GetRow(0), IsClose(AZ::Vector4(74.0f, 80.0f, 86.0f, 96.0f))); + EXPECT_THAT(m4.GetRow(1), IsClose(AZ::Vector4(206.0f, 224.0f, 242.0f, 268.0f))); + EXPECT_THAT(m4.GetRow(2), IsClose(AZ::Vector4(338.0f, 368.0f, 398.0f, 440.0f))); + } + + TEST(MATH_Matrix3x4, TestSum) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + + AZ::Matrix3x4 m3 = m1 + m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(8.0f, 10.0f, 12.0f, 14.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(16.0f, 18.0f, 20.0f, 22.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(24.0f, 26.0f, 28.0f, 30.0f))); + + m3 = m1; + m3 += m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(8.0f, 10.0f, 12.0f, 14.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(16.0f, 18.0f, 20.0f, 22.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(24.0f, 26.0f, 28.0f, 30.0f))); + } + + TEST(MATH_Matrix3x4, TestDifference) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + + AZ::Matrix3x4 m3 = m1 - m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + m3 = m1; + m3 -= m2; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + } + + TEST(MATH_Matrix3x4, TestScalarMultiplication) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + + AZ::Matrix3x4 m3 = m1 * 2.0f; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + m3 = m1; + m3 *= 2.0f; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + m3 = 2.0f * m1; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + } + + TEST(MATH_Matrix3x4, TestScalarDivision) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + AZ::Matrix3x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + + AZ::Matrix3x4 m3 = m1 / 0.5f; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + m3 = m1; + m3 /= 0.5f; + EXPECT_THAT(m3.GetRow(0), IsClose(AZ::Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(AZ::Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(AZ::Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + } + + TEST(MATH_Matrix3x4, TestNegation) + { + AZ::Matrix3x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + EXPECT_THAT(-(-m1), IsClose(m1)); + EXPECT_THAT(-AZ::Matrix3x4::CreateZero(), IsClose(AZ::Matrix3x4::CreateZero())); + + AZ::Matrix3x4 m2 = -m1; + EXPECT_THAT(m2.GetRow(0), IsClose(AZ::Vector4(-1.0f, -2.0f, -3.0f, -4.0f))); + EXPECT_THAT(m2.GetRow(1), IsClose(AZ::Vector4(-5.0f, -6.0f, -7.0f, -8.0f))); + EXPECT_THAT(m2.GetRow(2), IsClose(AZ::Vector4(-9.0f, -10.0f, -11.0f, -12.0f))); + + AZ::Matrix3x4 m3 = m1 + (-m1); + EXPECT_THAT(m3, IsClose(AZ::Matrix3x4::CreateZero())); } TEST(MATH_Matrix3x4, MultiplyByVector3) diff --git a/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp b/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp index 851de490d0..a9baa3ddea 100644 --- a/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp +++ b/Code/Framework/AzCore/Tests/Math/Matrix4x4Tests.cpp @@ -246,16 +246,16 @@ namespace UnitTest m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); Matrix4x4 m3 = m1 * m2; - AZ_TEST_ASSERT(m3.GetRow(0).IsClose(Vector4(150.0f, 160.0f, 170.0f, 180.0f))); - AZ_TEST_ASSERT(m3.GetRow(1).IsClose(Vector4(358.0f, 384.0f, 410.0f, 436.0f))); - AZ_TEST_ASSERT(m3.GetRow(2).IsClose(Vector4(566.0f, 608.0f, 650.0f, 692.0f))); - AZ_TEST_ASSERT(m3.GetRow(3).IsClose(Vector4(774.0f, 832.0f, 890.0f, 948.0f))); + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(150.0f, 160.0f, 170.0f, 180.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(358.0f, 384.0f, 410.0f, 436.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(566.0f, 608.0f, 650.0f, 692.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(774.0f, 832.0f, 890.0f, 948.0f))); Matrix4x4 m4 = m1; m4 *= m2; - AZ_TEST_ASSERT(m4.GetRow(0).IsClose(Vector4(150.0f, 160.0f, 170.0f, 180.0f))); - AZ_TEST_ASSERT(m4.GetRow(1).IsClose(Vector4(358.0f, 384.0f, 410.0f, 436.0f))); - AZ_TEST_ASSERT(m4.GetRow(2).IsClose(Vector4(566.0f, 608.0f, 650.0f, 692.0f))); - AZ_TEST_ASSERT(m4.GetRow(3).IsClose(Vector4(774.0f, 832.0f, 890.0f, 948.0f))); + EXPECT_THAT(m4.GetRow(0), IsClose(Vector4(150.0f, 160.0f, 170.0f, 180.0f))); + EXPECT_THAT(m4.GetRow(1), IsClose(Vector4(358.0f, 384.0f, 410.0f, 436.0f))); + EXPECT_THAT(m4.GetRow(2), IsClose(Vector4(566.0f, 608.0f, 650.0f, 692.0f))); + EXPECT_THAT(m4.GetRow(3), IsClose(Vector4(774.0f, 832.0f, 890.0f, 948.0f))); } TEST(MATH_Matrix4x4, TestVectorMultiplication) @@ -265,18 +265,148 @@ namespace UnitTest m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); - AZ_TEST_ASSERT((m1 * Vector3(1.0f, 2.0f, 3.0f)).IsClose(Vector3(18.0f, 46.0f, 74.0f))); - AZ_TEST_ASSERT((m1 * Vector4(1.0f, 2.0f, 3.0f, 4.0f)).IsClose(Vector4(30.0f, 70.0f, 110.0f, 150.0f))); - AZ_TEST_ASSERT(m1.TransposedMultiply3x3(Vector3(1.0f, 2.0f, 3.0f)).IsClose(Vector3(38.0f, 44.0f, 50.0f))); - AZ_TEST_ASSERT(m1.Multiply3x3(Vector3(1.0f, 2.0f, 3.0f)).IsClose(Vector3(14.0f, 38.0f, 62.0f))); + EXPECT_THAT((m1 * Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(18.0f, 46.0f, 74.0f))); + EXPECT_THAT((m1 * Vector4(1.0f, 2.0f, 3.0f, 4.0f)), IsClose(Vector4(30.0f, 70.0f, 110.0f, 150.0f))); + EXPECT_THAT(m1.TransposedMultiply3x3(Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(38.0f, 44.0f, 50.0f))); + EXPECT_THAT(m1.Multiply3x3(Vector3(1.0f, 2.0f, 3.0f)), IsClose(Vector3(14.0f, 38.0f, 62.0f))); Vector3 v1(1.0f, 2.0f, 3.0f); - AZ_TEST_ASSERT((v1 * m1).IsClose(Vector3(51.0f, 58.0f, 65.0f))); + EXPECT_THAT((v1 * m1), IsClose(Vector3(51.0f, 58.0f, 65.0f))); v1 *= m1; - AZ_TEST_ASSERT(v1.IsClose(Vector3(51.0f, 58.0f, 65.0f))); + EXPECT_THAT(v1, IsClose(Vector3(51.0f, 58.0f, 65.0f))); Vector4 v2(1.0f, 2.0f, 3.0f, 4.0f); - AZ_TEST_ASSERT((v2 * m1).IsClose(Vector4(90.0f, 100.0f, 110.0f, 120.0f))); + EXPECT_THAT((v2 * m1), IsClose(Vector4(90.0f, 100.0f, 110.0f, 120.0f))); v2 *= m1; - AZ_TEST_ASSERT(v2.IsClose(Vector4(90.0f, 100.0f, 110.0f, 120.0f))); + EXPECT_THAT(v2, IsClose(Vector4(90.0f, 100.0f, 110.0f, 120.0f))); + } + + TEST(MATH_Matrix4x4, TestSum) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + Matrix4x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); + + Matrix4x4 m3 = m1 + m2; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(8.0f, 10.0f, 12.0f, 14.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(16.0f, 18.0f, 20.0f, 22.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(24.0f, 26.0f, 28.0f, 30.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(32.0f, 34.0f, 36.0f, 38.0f))); + + m3 = m1; + m3 += m2; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(8.0f, 10.0f, 12.0f, 14.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(16.0f, 18.0f, 20.0f, 22.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(24.0f, 26.0f, 28.0f, 30.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(32.0f, 34.0f, 36.0f, 38.0f))); + } + + TEST(MATH_Matrix4x4, TestDifference) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + Matrix4x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); + + Matrix4x4 m3 = m1 - m2; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + m3 = m1; + m3 -= m2; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(-6.0f, -6.0f, -6.0f, -6.0f))); + } + + TEST(MATH_Matrix4x4, TestScalarMultiplication) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + Matrix4x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); + + Matrix4x4 m3 = m1 * 2.0f; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + m3 = m1; + m3 *= 2.0f; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + m3 = 2.0f * m1; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + } + + TEST(MATH_Matrix4x4, TestScalarDivision) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + Matrix4x4 m2; + m2.SetRow(0, 7.0f, 8.0f, 9.0f, 10.0f); + m2.SetRow(1, 11.0f, 12.0f, 13.0f, 14.0f); + m2.SetRow(2, 15.0f, 16.0f, 17.0f, 18.0f); + m2.SetRow(3, 19.0f, 20.0f, 21.0f, 22.0f); + + Matrix4x4 m3 = m1 / 0.5f; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + m3 = m1; + m3 /= 0.5f; + EXPECT_THAT(m3.GetRow(0), IsClose(Vector4(2.0f, 4.0f, 6.0f, 8.0f))); + EXPECT_THAT(m3.GetRow(1), IsClose(Vector4(10.0f, 12.0f, 14.0f, 16.0f))); + EXPECT_THAT(m3.GetRow(2), IsClose(Vector4(18.0f, 20.0f, 22.0f, 24.0f))); + EXPECT_THAT(m3.GetRow(3), IsClose(Vector4(26.0f, 28.0f, 30.0f, 32.0f))); + } + + TEST(MATH_Matrix4x4, TestNegation) + { + Matrix4x4 m1; + m1.SetRow(0, 1.0f, 2.0f, 3.0f, 4.0f); + m1.SetRow(1, 5.0f, 6.0f, 7.0f, 8.0f); + m1.SetRow(2, 9.0f, 10.0f, 11.0f, 12.0f); + m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); + EXPECT_THAT(-(-m1), IsClose(m1)); + EXPECT_THAT(-Matrix4x4::CreateZero(), IsClose(Matrix4x4::CreateZero())); + + Matrix4x4 m2 = -m1; + EXPECT_THAT(m2.GetRow(0), IsClose(Vector4(-1.0f, -2.0f, -3.0f, -4.0f))); + EXPECT_THAT(m2.GetRow(1), IsClose(Vector4(-5.0f, -6.0f, -7.0f, -8.0f))); + EXPECT_THAT(m2.GetRow(2), IsClose(Vector4(-9.0f, -10.0f, -11.0f, -12.0f))); + EXPECT_THAT(m2.GetRow(3), IsClose(Vector4(-13.0f, -14.0f, -15.0f, -16.0f))); + + Matrix4x4 m3 = m1 + (-m1); + EXPECT_THAT(m3, IsClose(Matrix4x4::CreateZero())); } TEST(MATH_Matrix4x4, TestTranspose) @@ -368,4 +498,36 @@ namespace UnitTest m1.SetRow(3, 13.0f, 14.0f, 15.0f, 16.0f); AZ_TEST_ASSERT(m1.GetDiagonal() == Vector4(1.0f, 6.0f, 11.0f, 16.0f)); } + + TEST(MATH_Matrix4x4, TestScaleAccess) + { + Matrix4x4 m1 = Matrix4x4::CreateRotationX(DegToRad(40.0f)) * Matrix4x4::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); + EXPECT_THAT(m1.ExtractScale(), IsClose(Vector3(2.0f, 3.0f, 4.0f))); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3::CreateOne())); + m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); + EXPECT_THAT(m1.RetrieveScale(), IsClose(Vector3(3.0f, 4.0f, 5.0f))); + } + + TEST(MATH_Matrix4x4, TestScaleSqAccess) + { + Matrix4x4 m1 = Matrix4x4::CreateRotationX(DegToRad(40.0f)) * Matrix4x4::CreateScale(Vector3(2.0f, 3.0f, 4.0f)); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(4.0f, 9.0f, 16.0f))); + m1.ExtractScale(); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3::CreateOne())); + m1.MultiplyByScale(Vector3(3.0f, 4.0f, 5.0f)); + EXPECT_THAT(m1.RetrieveScaleSq(), IsClose(Vector3(9.0f, 16.0f, 25.0f))); + } + + TEST(MATH_Matrix4x4, TestReciprocalScaled) + { + Matrix4x4 orthogonalMatrix = Matrix4x4::CreateRotationX(DegToRad(40.0f)); + EXPECT_THAT(orthogonalMatrix.GetReciprocalScaled(), IsClose(orthogonalMatrix)); + const AZ::Vector3 scale(2.8f, 0.7f, 1.3f); + AZ::Matrix4x4 scaledMatrix = orthogonalMatrix; + scaledMatrix.MultiplyByScale(scale); + AZ::Matrix4x4 reciprocalScaledMatrix = orthogonalMatrix; + reciprocalScaledMatrix.MultiplyByScale(scale.GetReciprocal()); + EXPECT_THAT(scaledMatrix.GetReciprocalScaled(), IsClose(reciprocalScaledMatrix)); + } } diff --git a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp index 35fa1136f9..e2e425fb57 100644 --- a/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp +++ b/Gems/ScriptCanvasTesting/Code/Source/Nodes/Nodeables/ValuePointerReferenceExample.cpp @@ -69,7 +69,7 @@ namespace ScriptCanvasTesting void PropertyExample::In() { - for (auto& num : Numbers) + for ([[maybe_unused]] auto& num : Numbers) { AZ_TracePrintf("ScriptCanvas", "%f", num); } From 5a60cb15fc018ad3d4102ada557bee835687e6cf Mon Sep 17 00:00:00 2001 From: hnusrath <82476875+hnusrath@users.noreply.github.com> Date: Tue, 4 May 2021 19:15:36 +0100 Subject: [PATCH 091/185] Spec-5799 Add PhysX tests to Main Suite to run under 3 min (#368) * Spec-5799 Add PhysX tests to Main Suite to run under 3 min Adding 12 tests to Main Suite from Periodic Suite. Moved 1 test case to Sandbox Suite as it was failing and needs to be investigated. Run results on local : 12 passed, 1 warning in 172.31s (0:02:52) Test Case list in Main suite: test_C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC test_C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies test_C4044459_Material_DynamicFriction test_C15425929_Undo_Redo test_C4976243_Collision_SameCollisionGroupDiffCollisionLayers test_C14654881_CharacterController_SwitchLevels test_C17411467_AddPhysxRagdollComponent test_C12712453_ScriptCanvas_MultipleRaycastNode test_C4982593_PhysXCollider_CollisionLayerTest test_C18243586_Joints_HingeLeadFollowerCollide test_C19578021_ShapeCollider_CanBeAdded test_C4982803_Enable_PxMesh_Option Test moved to Sandbox Suite : test_C13895144_Ragdoll_ChangeLevel * Delete .gitignore * Revert "Delete .gitignore" This reverts commit 9540e000c85e2a2015fbb8251f0a3248494349b0. Revert the modification of adding the buildoutput folder. * Spec-5799:Fixing Cyclinder ShapeCollider test and adding it to Main Suite Changes : 1. Fixed and Added test C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain to TestSuite_Main.py and updated the level for the test. 2. Removed test test_C19578021_ShapeCollider_CanBeAdded from Main suite back to Periodic Suite * Update TestSuite_Periodic.py Adding xfail to test case test_C13895144_Ragdoll_ChangeLevel as the previous change had overridden Sean Cove's change with commit 95a44c481ad42f059f926f21072cedbc12210a3c * Update TestSuite_Sandbox.py Removing test case test_C13895144_Ragdoll_ChangeLevel and moving it to Periodic Suite as the previous change had overridden Sean Cove's change with commit 95a44c481ad42f059f926f21072cedbc12210a3c Co-authored-by: amzn-sean <75276488+amzn-sean@users.noreply.github.com> --- ...rShapeCollider_CollidesWithPhysXTerrain.py | 53 ++++++--- .../Gem/PythonTests/physics/TestSuite_Main.py | 57 +++++++++ .../PythonTests/physics/TestSuite_Periodic.py | 112 ++++++------------ .../PythonTests/physics/TestSuite_Sandbox.py | 98 +++++++-------- ...rShapeCollider_CollidesWithPhysXTerrain.ly | 4 +- 5 files changed, 179 insertions(+), 145 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py b/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py index d8e0a6769c..60fa9dc44d 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py +++ b/AutomatedTesting/Gem/PythonTests/physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.py @@ -20,7 +20,10 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. class Tests(): enter_game_mode = ("Entered game mode", "Failed to enter game mode") find_cylinder = ("Cylinder entity found", "Cylinder entity not found") - find_terrain = ("Terrain found", "Terrain not found") + create_terrain = ("Terrain entity created successfully", "Failed to create Terrain Entity") + find_terrain = ("Terrain entity found", "Terrain entity not found") + add_physx_shape_collider = ("Added PhysX Shape Collider", "Failed to add PhysX Shape Collider") + add_box_shape = ("Added Box Shape", "Failed to add Box Shape") cylinder_above_terrain = ("Cylinder position above ground", "Cylinder is not above the ground") time_out = ("No time out occurred", "A time out occurred, please validate level setup") touched_ground = ("Touched ground before time out", "Did not touch ground before time out") @@ -40,11 +43,12 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(): Once game mode is entered, the cylinder should fall toward and collide with the terrain. Steps: - 1) Open level and enter game mode - 2) Retrieve entities and positions - 3) Wait for cylinder to collide with terrain OR time out - 4) Exit game mode - 5) Close the editor + 1) Open level and create terrain Entity. + 2) Enter Game Mode. + 3) Retrieve entities and positions + 4) Wait for cylinder to collide with terrain OR time out + 5) Exit game mode + 6) Close the editor :return: """ @@ -54,29 +58,48 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(): import ImportPathHelper as imports imports.init() - + from editor_python_test_tools.editor_entity_utils import EditorEntity import azlmbr.legacy.general as general import azlmbr.bus + import azlmbr.math as math from editor_python_test_tools.utils import Report from editor_python_test_tools.utils import TestHelper as helper # Global time out TIME_OUT = 1.0 - # 1) Open level / Enter game mode + # 1) Open level helper.init_idle() helper.open_level("Physics", "C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain") + + # Create terrain entity + terrain = EditorEntity.create_editor_entity_at([30.0, 30.0, 33.96], "Terrain") + Report.result(Tests.create_terrain, terrain.id.IsValid()) + + terrain.add_component("PhysX Shape Collider") + Report.result(Tests.add_physx_shape_collider, terrain.has_component("PhysX Shape Collider")) + + box_shape_component = terrain.add_component("Box Shape") + Report.result(Tests.add_box_shape, terrain.has_component("Box Shape")) + + box_shape_component.set_component_property_value("Box Shape|Box Configuration|Dimensions", + math.Vector3(1024.0, 1024.0, 0.01)) + + # 2)Enter game mode helper.enter_game_mode(Tests.enter_game_mode) - # 2) Retrieve entities and positions + # 3) Retrieve entities and positions cylinder_id = general.find_game_entity("PhysX_Cylinder") Report.critical_result(Tests.find_cylinder, cylinder_id.IsValid()) + + + terrain_id = general.find_game_entity("Terrain") + Report.critical_result(Tests.find_terrain, terrain_id.IsValid()) - terrain_id = general.find_game_entity("PhysX_Terrain") - Report.critical_result(Tests.find_terrain, terrain_id.IsValid()) - cylinder_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTM", cylinder_id).GetPosition() - terrain_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTM", terrain_id).GetPosition() + cylinder_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", cylinder_id) + #Cylinder position is 64,84,35 + terrain_pos = azlmbr.components.TransformBus(azlmbr.bus.Event, "GetWorldTranslation", terrain_id) Report.info_vector3(cylinder_pos, "Cylinder:") Report.info_vector3(terrain_pos, "Terrain:") Report.critical_result( @@ -104,13 +127,13 @@ def C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(): handler.connect(cylinder_id) handler.add_callback("OnCollisionBegin", on_collision_begin) - # 3) Wait for the cylinder to hit the ground OR time out + # 4) Wait for the cylinder to hit the ground OR time out test_completed = helper.wait_for_condition((lambda: TouchGround.value), TIME_OUT) Report.critical_result(Tests.time_out, test_completed) Report.result(Tests.touched_ground, TouchGround.value) - # 4) Exit game mode + # 5) Exit game mode helper.exit_game_mode(Tests.exit_game_mode) diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py index 67e855a00e..f81445fe03 100644 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Main.py @@ -34,4 +34,61 @@ class TestAutomation(TestAutomationBase): def test_C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC(self, request, workspace, editor, launcher_platform): from . import C111111_RigidBody_EnablingGravityWorksUsingNotificationsPoC as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies(self, request, workspace, editor, launcher_platform): + from . import C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C4044459_Material_DynamicFriction(self, request, workspace, editor, launcher_platform): + from . import C4044459_Material_DynamicFriction as test_module + self._run_test(request, workspace, editor, test_module) + + @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) + + @revert_physics_config + def test_C4976243_Collision_SameCollisionGroupDiffCollisionLayers(self, request, workspace, editor, + launcher_platform): + from . import C4976243_Collision_SameCollisionGroupDiffCollisionLayers as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C14654881_CharacterController_SwitchLevels(self, request, workspace, editor, launcher_platform): + from . import C14654881_CharacterController_SwitchLevels as test_module + self._run_test(request, workspace, editor, test_module) + + def test_C17411467_AddPhysxRagdollComponent(self, request, workspace, editor, launcher_platform): + from . import C17411467_AddPhysxRagdollComponent as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C12712453_ScriptCanvas_MultipleRaycastNode(self, request, workspace, editor, launcher_platform): + from . import C12712453_ScriptCanvas_MultipleRaycastNode as test_module + # Fixme: unexpected_lines = ["Assert"] + test_module.Lines.unexpected + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + @fm.file_override('physxsystemconfiguration.setreg','C4982593_PhysXCollider_CollisionLayer.setreg', 'AutomatedTesting/Registry') + def test_C4982593_PhysXCollider_CollisionLayerTest(self, request, workspace, editor, launcher_platform): + from . import C4982593_PhysXCollider_CollisionLayerTest as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C18243586_Joints_HingeLeadFollowerCollide(self, request, workspace, editor, launcher_platform): + from . import C18243586_Joints_HingeLeadFollowerCollide as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C4982803_Enable_PxMesh_Option(self, request, workspace, editor, launcher_platform): + from . import C4982803_Enable_PxMesh_Option as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain(self, request, workspace, editor, launcher_platform): + from . import C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain as test_module self._run_test(request, workspace, editor, test_module) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py index 39ed85a65a..4f91f539ee 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Periodic.py @@ -52,11 +52,6 @@ class TestAutomation(TestAutomationBase): from . import C4976207_PhysXRigidBodies_KinematicBehavior as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies(self, request, workspace, editor, launcher_platform): - from . import C5932041_PhysXForceRegion_LocalSpaceForceOnRigidBodies as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C5932042_PhysXForceRegion_LinearDamping(self, request, workspace, editor, launcher_platform): from . import C5932042_PhysXForceRegion_LinearDamping as test_module @@ -92,11 +87,6 @@ class TestAutomation(TestAutomationBase): from . import C4976194_RigidBody_PhysXComponentIsValid as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C4044459_Material_DynamicFriction(self, request, workspace, editor, launcher_platform): - from . import C4044459_Material_DynamicFriction as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C5932045_ForceRegion_Spline(self, request, workspace, editor, launcher_platform): from . import C5932045_ForceRegion_Spline as test_module @@ -208,26 +198,11 @@ class TestAutomation(TestAutomationBase): from . import C18981526_Material_RestitutionCombinePriority as test_module self._run_test(request, workspace, editor, test_module) - @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) - - @revert_physics_config - def test_C15308217_NoCrash_LevelSwitch(self, request, workspace, editor, launcher_platform): - from . import C15308217_NoCrash_LevelSwitch as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C12868580_ForceRegion_SplineModifiedTransform(self, request, workspace, editor, launcher_platform): from . import C12868580_ForceRegion_SplineModifiedTransform as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C4976243_Collision_SameCollisionGroupDiffCollisionLayers(self, request, workspace, editor, launcher_platform): - from . import C4976243_Collision_SameCollisionGroupDiffCollisionLayers as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C12712455_ScriptCanvas_ShapeCastVerification(self, request, workspace, editor, launcher_platform): from . import C12712455_ScriptCanvas_ShapeCastVerification as test_module @@ -248,17 +223,6 @@ class TestAutomation(TestAutomationBase): from . import C6131473_StaticSlice_OnDynamicSliceSpawn as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C4982798_Collider_ColliderRotationOffset(self, request, workspace, editor, launcher_platform): - from . import C4982798_Collider_ColliderRotationOffset as test_module - self._run_test(request, workspace, editor, test_module) - - @revert_physics_config - def test_C12712453_ScriptCanvas_MultipleRaycastNode(self, request, workspace, editor, launcher_platform): - from . import C12712453_ScriptCanvas_MultipleRaycastNode as test_module - # Fixme: unexpected_lines = ["Assert"] + test_module.Lines.unexpected - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C5959808_ForceRegion_PositionOffset(self, request, workspace, editor, launcher_platform): from . import C5959808_ForceRegion_PositionOffset as test_module @@ -275,7 +239,7 @@ class TestAutomation(TestAutomationBase): def test_C13895144_Ragdoll_ChangeLevel(self, request, workspace, editor, launcher_platform): from . import C13895144_Ragdoll_ChangeLevel as test_module self._run_test(request, workspace, editor, test_module) - + @revert_physics_config def test_C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody(self, request, workspace, editor, launcher_platform): from . import C5968759_ForceRegion_ExertsSeveralForcesOnRigidBody as test_module @@ -305,11 +269,6 @@ class TestAutomation(TestAutomationBase): from . import C5296614_PhysXMaterial_ColliderShape as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C6090547_ForceRegion_ParentChildForceRegions(self, request, workspace, editor, launcher_platform): - from . import C6090547_ForceRegion_ParentChildForceRegions as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C4982595_Collider_TriggerDisablesCollision(self, request, workspace, editor, launcher_platform): from . import C4982595_Collider_TriggerDisablesCollision as test_module @@ -320,11 +279,6 @@ class TestAutomation(TestAutomationBase): from . import C14976307_Gravity_SetGravityWorks as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C14654881_CharacterController_SwitchLevels(self, request, workspace, editor, launcher_platform): - from . import C14654881_CharacterController_SwitchLevels as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C15556261_PhysXMaterials_CharacterControllerMaterialAssignment(self, request, workspace, editor, launcher_platform): from . import C15556261_PhysXMaterials_CharacterControllerMaterialAssignment as test_module @@ -374,18 +328,6 @@ class TestAutomation(TestAutomationBase): from . import C4044461_Material_Restitution as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - @fm.file_override('physxsystemconfiguration.setreg','C4982593_PhysXCollider_CollisionLayer.setreg', 'AutomatedTesting/Registry') - def test_C4982593_PhysXCollider_CollisionLayerTest(self, request, workspace, editor, launcher_platform): - from . import C4982593_PhysXCollider_CollisionLayerTest as test_module - self._run_test(request, workspace, editor, test_module) - - @revert_physics_config - @fm.file_override('physxsystemconfiguration.setreg','C3510644_Collider_CollisionGroups.setreg', 'AutomatedTesting/Registry') - def test_C3510644_Collider_CollisionGroups(self, request, workspace, editor, launcher_platform): - from . import C3510644_Collider_CollisionGroups as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config @fm.file_override('physxdefaultsceneconfiguration.setreg','C14902097_ScriptCanvas_PreUpdateEvent.setreg', 'AutomatedTesting/Registry') def test_C14902097_ScriptCanvas_PreUpdateEvent(self, request, workspace, editor, launcher_platform): @@ -415,11 +357,6 @@ class TestAutomation(TestAutomationBase): from . import C18243589_Joints_BallSoftLimitsConstrained as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C18243586_Joints_HingeLeadFollowerCollide(self, request, workspace, editor, launcher_platform): - from . import C18243586_Joints_HingeLeadFollowerCollide as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C18243591_Joints_BallLeadFollowerCollide(self, request, workspace, editor, launcher_platform): from . import C18243591_Joints_BallLeadFollowerCollide as test_module @@ -441,21 +378,11 @@ class TestAutomation(TestAutomationBase): from . import C14861500_DefaultSetting_ColliderShape as test_module self._run_test(request, workspace, editor, test_module) - @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 def test_C19723164_ShapeCollider_WontCrashEditor(self, request, workspace, editor, launcher_platform): from . import C19723164_ShapeColliders_WontCrashEditor as test_module self._run_test(request, workspace, editor, test_module) - @revert_physics_config - def test_C4982803_Enable_PxMesh_Option(self, request, workspace, editor, launcher_platform): - from . import C4982803_Enable_PxMesh_Option as test_module - self._run_test(request, workspace, editor, test_module) - @revert_physics_config def test_C4982800_PhysXColliderShape_CanBeSelected(self, request, workspace, editor, launcher_platform): from . import C4982800_PhysXColliderShape_CanBeSelected as test_module @@ -471,10 +398,6 @@ class TestAutomation(TestAutomationBase): from . import C4982802_PhysXColliderShape_CanBeSelected as test_module self._run_test(request, workspace, editor, test_module) - def test_C17411467_AddPhysxRagdollComponent(self, request, workspace, editor, launcher_platform): - from . import C17411467_AddPhysxRagdollComponent as test_module - self._run_test(request, workspace, editor, test_module) - def test_C12905528_ForceRegion_WithNonTriggerCollider(self, request, workspace, editor, launcher_platform): from . import C12905528_ForceRegion_WithNonTriggerCollider as test_module # Fixme: expected_lines = ["[Warning] (PhysX Force Region) - Please ensure collider component marked as trigger exists in entity"] @@ -522,4 +445,35 @@ class TestAutomation(TestAutomationBase): def test_C100000_RigidBody_EnablingGravityWorksPoC(self, request, workspace, editor, launcher_platform): from . import C100000_RigidBody_EnablingGravityWorksPoC as test_module - self._run_test(request, workspace, editor, test_module) \ No newline at end of file + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + @fm.file_override('physxsystemconfiguration.setreg','C3510644_Collider_CollisionGroups.setreg', 'AutomatedTesting/Registry') + def test_C3510644_Collider_CollisionGroups(self, request, workspace, editor, launcher_platform): + from . import C3510644_Collider_CollisionGroups as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C4982798_Collider_ColliderRotationOffset(self, request, workspace, editor, launcher_platform): + from . import C4982798_Collider_ColliderRotationOffset as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C15308217_NoCrash_LevelSwitch(self, request, workspace, editor, launcher_platform): + from . import C15308217_NoCrash_LevelSwitch as test_module + self._run_test(request, workspace, editor, test_module) + + @revert_physics_config + def test_C6090547_ForceRegion_ParentChildForceRegions(self, request, workspace, editor, launcher_platform): + from . import C6090547_ForceRegion_ParentChildForceRegions as test_module + self._run_test(request, workspace, editor, test_module) + + @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 + 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) diff --git a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py index 39bc4c8188..e829726ba9 100755 --- a/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py +++ b/AutomatedTesting/Gem/PythonTests/physics/TestSuite_Sandbox.py @@ -1,49 +1,49 @@ -""" -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. - -""" - -# This suite consists of all test cases that are passing and have been verified. - -import pytest -import os -import sys - -from .FileManagement import FileManagement as fm -from ly_test_tools import LAUNCHERS - -sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') - -from base import TestAutomationBase - - -revert_physics_config = fm.file_revert_list(['physxdebugconfiguration.setreg', 'physxdefaultsceneconfiguration.setreg', 'physxsystemconfiguration.setreg'], 'AutomatedTesting/Registry') - - -@pytest.mark.SUITE_sandbox -@pytest.mark.parametrize("launcher_platform", ['windows_editor']) -@pytest.mark.parametrize("project", ["AutomatedTesting"]) -class TestAutomation(TestAutomationBase): - - ## Seems to be flaky, need to investigate - def test_C19536274_GetCollisionName_PrintsName(self, request, workspace, editor, launcher_platform): - from . import C19536274_GetCollisionName_PrintsName as test_module - # Fixme: expected_lines=["Layer Name: Right"] - self._run_test(request, workspace, editor, test_module) - - ## Seems to be flaky, need to investigate - def test_C19536277_GetCollisionName_PrintsNothing(self, request, workspace, editor, launcher_platform): - from . import C19536277_GetCollisionName_PrintsNothing as test_module - # All groups present in the PhysX Collider that could show up in test - # Fixme: collision_groups = ["All", "None", "All_NoTouchBend", "All_3", "None_1", "All_NoTouchBend_1", "All_2", "None_1_1", "All_NoTouchBend_1_1", "All_1", "None_1_1_1", "All_NoTouchBend_1_1_1", "All_4", "None_1_1_1_1", "All_NoTouchBend_1_1_1_1", "GroupLeft", "GroupRight"] - # Fixme: for group in collision_groups: - # Fixme: unexpected_lines.append(f"GroupName: {group}") - # Fixme: expected_lines=["GroupName: "] - self._run_test(request, workspace, editor, test_module) \ No newline at end of file +""" +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. + +""" + +# This suite consists of all test cases that are passing and have been verified. + +import pytest +import os +import sys + +from .FileManagement import FileManagement as fm +from ly_test_tools import LAUNCHERS + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/../automatedtesting_shared') + +from base import TestAutomationBase + + +revert_physics_config = fm.file_revert_list(['physxdebugconfiguration.setreg', 'physxdefaultsceneconfiguration.setreg', 'physxsystemconfiguration.setreg'], 'AutomatedTesting/Registry') + + +@pytest.mark.SUITE_sandbox +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +class TestAutomation(TestAutomationBase): + + ## Seems to be flaky, need to investigate + def test_C19536274_GetCollisionName_PrintsName(self, request, workspace, editor, launcher_platform): + from . import C19536274_GetCollisionName_PrintsName as test_module + # Fixme: expected_lines=["Layer Name: Right"] + self._run_test(request, workspace, editor, test_module) + + ## Seems to be flaky, need to investigate + def test_C19536277_GetCollisionName_PrintsNothing(self, request, workspace, editor, launcher_platform): + from . import C19536277_GetCollisionName_PrintsNothing as test_module + # All groups present in the PhysX Collider that could show up in test + # Fixme: collision_groups = ["All", "None", "All_NoTouchBend", "All_3", "None_1", "All_NoTouchBend_1", "All_2", "None_1_1", "All_NoTouchBend_1_1", "All_1", "None_1_1_1", "All_NoTouchBend_1_1_1", "All_4", "None_1_1_1_1", "All_NoTouchBend_1_1_1_1", "GroupLeft", "GroupRight"] + # Fixme: for group in collision_groups: + # Fixme: unexpected_lines.append(f"GroupName: {group}") + # Fixme: expected_lines=["GroupName: "] + self._run_test(request, workspace, editor, test_module) diff --git a/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly b/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly index ba141251d5..d618bf1873 100644 --- a/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly +++ b/AutomatedTesting/Levels/Physics/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain/C24308873_CylinderShapeCollider_CollidesWithPhysXTerrain.ly @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:231d5ac32c95334eeb1cbf77ea0bceae1d8010de3290dfdbd991abb46d18bae6 -size 6844 +oid sha256:83af66a6db4ff2b4df7212099b661a96668cfb326d8984e41b16506ec0062141 +size 5844 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 092/185] 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 bba4867f718583954315d872331549537f17f294 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Tue, 4 May 2021 13:37:41 -0700 Subject: [PATCH 093/185] For got to add 012_Parallax_POM_Cutout.material --- .../012_Parallax_POM_Cutout.material | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material diff --git a/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material new file mode 100644 index 0000000000..fb862dc5d3 --- /dev/null +++ b/Gems/Atom/TestData/TestData/Materials/StandardPbrTestCases/012_Parallax_POM_Cutout.material @@ -0,0 +1,26 @@ +{ + "description": "", + "materialType": "Materials/Types/StandardPBR.materialtype", + "parentMaterial": "", + "propertyLayoutVersion": 3, + "properties": { + "baseColor": { + "textureMap": "TestData/Textures/TextureHaven/4k_castle_brick_02_red/4k_castle_brick_02_red_bc.png" + }, + "opacity": { + "alphaSource": "Split", + "mode": "Cutout", + "textureMap": "TestData/Textures/checker8x8_512.png" + }, + "parallax": { + "algorithm": "POM", + "enable": true, + "factor": 0.10000000149011612, + "quality": "High", + "textureMap": "TestData/Textures/TextureHaven/4k_castle_brick_02_red/4k_castle_brick_02_red_disp.png" + }, + "uv": { + "scale": 0.5 + } + } +} \ No newline at end of file From afcbe4e02b64b5a4820f99a01d843a6f8a27f570 Mon Sep 17 00:00:00 2001 From: AMZN-koppersr <82230785+AMZN-koppersr@users.noreply.github.com> Date: Tue, 4 May 2021 13:51:08 -0700 Subject: [PATCH 094/185] Small updates based on PR feedback. --- .../AzCore/AzCore/Serialization/Json/JsonSerialization.h | 3 +++ .../Tests/Serialization/Json/BaseJsonSerializerTests.cpp | 6 +++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h index b92eae7d6b..cf73d8dc56 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonSerialization.h @@ -49,6 +49,9 @@ namespace AZ //! Note on pointers: The Json Serialization assumes that are always constructed, so a default JSON value of "{}" is interpret as //! creating a new default instance even if the default value is a null pointer. A JSON Null needs to be explicitly stored in //! the JSON Document in order to default or explicitly set a pointer to null. + //! Note on pointer memory: Objects created/destroyed by the Json Serialization for pointers require that the AZ_CLASS_ALLOCATOR is + //! declared and the object is created using aznew or memory is allocated using azmalloc. Without these the application may + //! crash if the Json Serialization tries to create or destroy an object pointed to by a pointer. class JsonSerialization final { public: diff --git a/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp b/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp index 62622ef7ab..08de21b54f 100644 --- a/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp +++ b/Code/Framework/AzCore/Tests/Serialization/Json/BaseJsonSerializerTests.cpp @@ -140,7 +140,7 @@ namespace JsonSerializationTests ASSERT_NE(nullptr, ptrValue); EXPECT_EQ(42, *ptrValue); - azfree(ptrValue, AZ::SystemAllocator, sizeof(int), AZStd::alignment_of::value); + azfree(ptrValue, AZ::SystemAllocator, sizeof(int), alignof(int)); } TEST_F(BaseJsonSerializerTests, ContinueLoading_DefaultToNullPointer_ValueLoadedCorrectly) @@ -155,7 +155,7 @@ namespace JsonSerializationTests EXPECT_EQ(Processing::Completed, result.GetProcessing()); ASSERT_NE(nullptr, ptrValue); - azfree(ptrValue, AZ::SystemAllocator, sizeof(int), AZStd::alignment_of::value); + azfree(ptrValue, AZ::SystemAllocator, sizeof(int), alignof(int)); } TEST_F(BaseJsonSerializerTests, ContinueLoading_NullDeletesObject_ValueLoadedCorrectly) @@ -163,7 +163,7 @@ namespace JsonSerializationTests using namespace AZ::JsonSerializationResult; rapidjson::Value json(rapidjson::kNullType); - int* ptrValue = reinterpret_cast(azmalloc(sizeof(int), AZStd::alignment_of::value, AZ::SystemAllocator)); + int* ptrValue = reinterpret_cast(azmalloc(sizeof(int), alignof(int), AZ::SystemAllocator)); ResultCode result = ContinueLoading(&ptrValue, azrtti_typeid(), json, *m_jsonDeserializationContext, Flags::ResolvePointer); From 9e105fb7694b4fb8722b3a826919e409baab939f Mon Sep 17 00:00:00 2001 From: Chris Galvan Date: Tue, 4 May 2021 16:52:36 -0500 Subject: [PATCH 095/185] [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 f5f035122b7c61470961fcda226e3aa575b28c8e Mon Sep 17 00:00:00 2001 From: sharmajs-amzn <82233357+sharmajs-amzn@users.noreply.github.com> Date: Tue, 4 May 2021 15:00:02 -0700 Subject: [PATCH 096/185] {LYN-3229} Update AssImp package with latest AssImp 3rd party source changes (#545) (#554) --- cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake | 2 +- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 620995a85b..4056242a47 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -14,7 +14,7 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARG ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev7-multiplatform TARGETS assimplib PACKAGE_HASH def855c89d8210db3040f1cb6ec837141ab9b8e74c158eae7c03d50160fcf30b) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev8-multiplatform TARGETS assimplib PACKAGE_HASH 21dce424eccf5a2626ff0841e72092fa4ff9407a64b851e5eed9895926ce309d) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index 290508b348..e06eadcbea 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -14,7 +14,7 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev7-multiplatform TARGETS assimplib PACKAGE_HASH def855c89d8210db3040f1cb6ec837141ab9b8e74c158eae7c03d50160fcf30b) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev8-multiplatform TARGETS assimplib PACKAGE_HASH 21dce424eccf5a2626ff0841e72092fa4ff9407a64b851e5eed9895926ce309d) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index bdc93d9a0e..939948d501 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -14,7 +14,7 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) -ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev7-multiplatform TARGETS assimplib PACKAGE_HASH def855c89d8210db3040f1cb6ec837141ab9b8e74c158eae7c03d50160fcf30b) +ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev8-multiplatform TARGETS assimplib PACKAGE_HASH 21dce424eccf5a2626ff0841e72092fa4ff9407a64b851e5eed9895926ce309d) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) 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 097/185] 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 3b8264016ab5ef9a88256d49f47fbc447012b831 Mon Sep 17 00:00:00 2001 From: jonbeer Date: Tue, 4 May 2021 15:06:34 -0700 Subject: [PATCH 098/185] Updating testing --- .../Code/Tests/PhysXColliderPrefabTests.cpp | 157 ++++++++++++------ 1 file changed, 110 insertions(+), 47 deletions(-) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp index d489ac2990..f6a913b61d 100644 --- a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp @@ -13,12 +13,12 @@ #include #include + #include -#include -#include -#include -#include -#include +#include +#include +#include +#include #include #include @@ -26,101 +26,164 @@ #include #include #include -#include -#include -#include -#include namespace PhysX { - class PhysXColliderPrefabTest + class PhysXColliderPrefabTests : public ::testing::Test { protected: - void SetUp() override - { - - } - - void TearDown() override - { - - } - - }; - TEST_F(PhysXColliderPrefabTest, JsonStoreAndLoadPhysicsObjectsWithPrefabTest) + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsTypes_ValuesNotNull) { + //create a prefab for storing data AzToolsFramework::Prefab::PrefabDom prefabDom; //material selection Physics::MaterialSelection materialSelection; - AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), materialSelection); + AZ::JsonSerializationResult::ResultCode result + = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), materialSelection); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Material Selection", prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); Physics::MaterialSelection newSelection; - AZ::JsonSerialization::Load(newSelection, prefabDom); + result = AZ::JsonSerialization::Load(newSelection, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_EQ(materialSelection.GetMaterialId(), newSelection.GetMaterialId()); //collider configuration Physics::ColliderConfiguration colliderConfig; - AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfig); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfig); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); Physics::ColliderConfiguration newConfig; - AZ::JsonSerialization::Load(newConfig, prefabDom); + result = AZ::JsonSerialization::Load(newConfig, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_EQ(colliderConfig.m_collisionLayer, newConfig.m_collisionLayer); + } + + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsTypes_PointersNotNull) + { + //create a prefab for storing data + AzToolsFramework::Prefab::PrefabDom prefabDom; //shared pointer - collider configuration - defaults only auto colliderConfigPtr = AZStd::make_shared(); AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), colliderConfigPtr); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); colliderConfigPtr = nullptr; - AZ::JsonSerialization::Load(colliderConfigPtr, prefabDom); + result = AZ::JsonSerialization::Load(colliderConfigPtr, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_NE(nullptr, colliderConfigPtr); + //shared pointer - shape configuration - defaults only + auto shapeConfigPtr = AZStd::make_shared(); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeConfigPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + shapeConfigPtr = nullptr; + result = AZ::JsonSerialization::Load(shapeConfigPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, shapeConfigPtr); + + + } + + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_NonDefaultPhysicsTypes_PointersNotNull) + { + //create a prefab for storing data + AzToolsFramework::Prefab::PrefabDom prefabDom; + //shared pointer - collider configuration - non default auto updatedColliderConfigPtr = AZStd::make_shared(); updatedColliderConfigPtr->m_isTrigger = true; - AZ::JsonSerializationResult::ResultCode result2 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedColliderConfigPtr); + AZ::JsonSerializationResult::ResultCode result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedColliderConfigPtr); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Collider Configuration", prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); updatedColliderConfigPtr = nullptr; - AZ::JsonSerialization::Load(updatedColliderConfigPtr, prefabDom); + result = AZ::JsonSerialization::Load(updatedColliderConfigPtr, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_NE(nullptr, updatedColliderConfigPtr); - //shared pointer - shape configuration - defaults only - auto shapeConfigPtr = AZStd::make_shared(); - AZ::JsonSerializationResult::ResultCode result3 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeConfigPtr); - - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Shape Configuration", prefabDom); - - shapeConfigPtr = nullptr; - AZ::JsonSerialization::Load(shapeConfigPtr, prefabDom); - - EXPECT_NE(nullptr, shapeConfigPtr); - //shared pointer - shape configuration - non default auto updatedShapeConfigPtr = AZStd::make_shared(); updatedShapeConfigPtr->m_radius = 2.0f; - AZ::JsonSerializationResult::ResultCode result4 = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedShapeConfigPtr); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), updatedShapeConfigPtr); - AzToolsFramework::Prefab::PrefabDomUtils::PrintPrefabDomValue("Shape Configuration", prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); updatedShapeConfigPtr = nullptr; - AZ::JsonSerialization::Load(updatedShapeConfigPtr, prefabDom); + result = AZ::JsonSerialization::Load(updatedShapeConfigPtr, prefabDom); + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_NE(nullptr, updatedColliderConfigPtr); } + + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsColliderComponents_PointersNotNull) + { + //create a prefab for storing data + AzToolsFramework::Prefab::PrefabDom prefabDom; + + //shared pointer - box collider - defaults only + auto boxColliderPtr = AZStd::make_shared(); + AZ::JsonSerializationResult::ResultCode result + = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), boxColliderPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + boxColliderPtr = nullptr; + result = AZ::JsonSerialization::Load(boxColliderPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, boxColliderPtr); + + //shared pointer - sphere collider - defaults only + auto sphereColliderPtr = AZStd::make_shared(); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), sphereColliderPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + sphereColliderPtr = nullptr; + result = AZ::JsonSerialization::Load(sphereColliderPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, sphereColliderPtr); + + //shared pointer - capsule collider - defaults only + auto capsuleColliderPtr = AZStd::make_shared(); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), capsuleColliderPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + capsuleColliderPtr = nullptr; + result = AZ::JsonSerialization::Load(capsuleColliderPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, capsuleColliderPtr); + + //shared pointer - shape collider - defaults only + auto shapeColliderPtr = AZStd::make_shared(); + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeColliderPtr); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + + shapeColliderPtr = nullptr; + result = AZ::JsonSerialization::Load(shapeColliderPtr, prefabDom); + + EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); + EXPECT_NE(nullptr, shapeColliderPtr); + } } From cd93df4ca80ec35344d281c253e97528bc897f8a Mon Sep 17 00:00:00 2001 From: greerdv Date: Tue, 4 May 2021 23:15:51 +0100 Subject: [PATCH 099/185] hiding button to add non-uniform scale when there already is a NUS component on the entity --- .../ToolsComponents/TransformComponent.cpp | 53 +++++++++++++++---- .../ToolsComponents/TransformComponent.h | 4 +- 2 files changed, 44 insertions(+), 13 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp index a025c02c32..e20c114b20 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.cpp @@ -1217,10 +1217,47 @@ namespace AzToolsFramework destinationComponent->SetWorldTM(const_cast(sourceComponent)->GetWorldTM()); } + AZ::Component* TransformComponent::FindPresentOrPendingComponent(AZ::Uuid componentUuid) + { + // first check if the component is present and valid + AZ::Component* foundComponent = GetEntity()->FindComponent(componentUuid); + if (foundComponent) + { + return foundComponent; + } + + // then check to see if there's a component pending because it's in an invalid state + AZStd::vector pendingComponents; + AzToolsFramework::EditorPendingCompositionRequestBus::Event(GetEntityId(), + &AzToolsFramework::EditorPendingCompositionRequests::GetPendingComponents, pendingComponents); + + for (const auto pendingComponent : pendingComponents) + { + if (pendingComponent->RTTI_IsTypeOf(componentUuid)) + { + return pendingComponent; + } + } + + return nullptr; + } + + AZ::Crc32 TransformComponent::AddNonUniformScaleButtonVisibility() + { + // if there is a non-uniform scale component already, hide altogether + if (FindPresentOrPendingComponent(EditorNonUniformScaleComponent::TYPEINFO_Uuid())) + { + return AZ::Edit::PropertyVisibility::Hide; + } + + // otherwise, just show children + return AZ::Edit::PropertyVisibility::ShowChildrenOnly; + } + AZ::Crc32 TransformComponent::OnAddNonUniformScaleButtonPressed() { // if there is already a non-uniform scale component, do nothing - if (GetEntity()->FindComponent()) + if (FindPresentOrPendingComponent(EditorNonUniformScaleComponent::TYPEINFO_Uuid())) { return AZ::Edit::PropertyRefreshLevels::None; } @@ -1232,17 +1269,11 @@ namespace AzToolsFramework AzToolsFramework::EntityCompositionRequestBus::BroadcastResult(outcome, &AzToolsFramework::EntityCompositionRequests::AddComponentsToEntities, entityList, componentsToAdd); - AZStd::vector pendingComponents; - AzToolsFramework::EditorPendingCompositionRequestBus::Event(GetEntityId(), - &AzToolsFramework::EditorPendingCompositionRequests::GetPendingComponents, pendingComponents); - AZ::ComponentId nonUniformScaleComponentId = AZ::InvalidComponentId; - for (const auto pendingComponent : pendingComponents) + auto nonUniformScaleComponent = FindPresentOrPendingComponent(EditorNonUniformScaleComponent::RTTI_Type()); + if (nonUniformScaleComponent) { - if (pendingComponent->RTTI_IsTypeOf(AzToolsFramework::Components::EditorNonUniformScaleComponent::RTTI_Type())) - { - nonUniformScaleComponentId = pendingComponent->GetId(); - } + nonUniformScaleComponentId = nonUniformScaleComponent->GetId(); } if (!outcome.IsSuccess() || nonUniformScaleComponentId == AZ::InvalidComponentId) @@ -1300,7 +1331,7 @@ namespace AzToolsFramework Attribute(AZ::Edit::Attributes::AutoExpand, true)-> DataElement(AZ::Edit::UIHandlers::Default, &TransformComponent::m_addNonUniformScaleButton, "", "")-> Attribute(AZ::Edit::Attributes::AutoExpand, true)-> - Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)-> + Attribute(AZ::Edit::Attributes::Visibility, &TransformComponent::AddNonUniformScaleButtonVisibility)-> Attribute(AZ::Edit::Attributes::ChangeNotify, &TransformComponent::OnAddNonUniformScaleButtonPressed)-> DataElement(AZ::Edit::UIHandlers::ComboBox, &TransformComponent::m_parentActivationTransformMode, "Parent activation", "Configures relative transform behavior when parent activates.")-> diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h index dd8c7b8693..7a0675187a 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h @@ -37,8 +37,6 @@ namespace AzToolsFramework public: AZ_TYPE_INFO(AddNonUniformScaleButton, "{92ECB8B6-DD25-4FC0-A5EE-4CEBAF51A780}") static void Reflect(AZ::ReflectContext* context); - private: - void OnAddNonUniformScaleButtonPressed() {}; }; /// Manages transform data as separate vector fields for editing purposes. @@ -238,6 +236,8 @@ namespace AzToolsFramework void CheckApplyCachedWorldTransform(const AZ::Transform& parentWorld); + AZ::Component* FindPresentOrPendingComponent(AZ::Uuid componentUuid); + AZ::Crc32 AddNonUniformScaleButtonVisibility(); AZ::Crc32 OnAddNonUniformScaleButtonPressed(); // Drives transform behavior when parent activates. See AZ::TransformConfig::ParentActivationTransformMode for details. From 71039186ab353f32638e2baaf4c3091220e66bfb Mon Sep 17 00:00:00 2001 From: dmcdiar Date: Tue, 4 May 2021 15:18:48 -0700 Subject: [PATCH 100/185] 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 36e3c80df435b89c14124844741cf947ac7fa3de Mon Sep 17 00:00:00 2001 From: jonbeer Date: Tue, 4 May 2021 15:41:23 -0700 Subject: [PATCH 101/185] Fixing spacing --- Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp index f6a913b61d..4287ce17db 100644 --- a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp @@ -96,8 +96,6 @@ namespace PhysX EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); EXPECT_NE(nullptr, shapeConfigPtr); - - } TEST_F(PhysXColliderPrefabTests, StoreAndLoad_NonDefaultPhysicsTypes_PointersNotNull) From d4f19cb0b5ebbc06d701559b53823d4d9ecda353 Mon Sep 17 00:00:00 2001 From: nvsickle Date: Tue, 4 May 2021 15:53:40 -0700 Subject: [PATCH 102/185] 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 103/185] 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 | 132 ++++++++++-------- .../NetworkEntity/NetworkEntityManager.h | 7 +- .../NetworkEntity/NetworkSpawnableLibrary.cpp | 1 - .../Pipeline/NetworkPrefabProcessor.cpp | 5 +- 7 files changed, 118 insertions(+), 60 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; - } + return returnList; + } - const uint32_t entityIndex = prefabEntryId.m_entityOffset; + const uint32_t entityIndex = prefabEntryId.m_entityOffset; - if (entityIndex == PrefabEntityId::AllIndices) - { - return CreateEntitiesImmediate(*netSpawnable, netEntityRole); - } + 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; - } + 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::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()); + 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* netBindComponent = clone->FindComponent(); + if (netBindComponent) + { + netBindComponent->PreInit(clone, prefabEntryId, netEntityId, netEntityRole); + + auto* transformComponent = clone->FindComponent(); + if (transformComponent) { - netBindComponent->PreInit(clone, prefabEntryId, netEntityId, netEntityRole); + transformComponent->SetWorldTM(transform); + } - auto* transformComponent = clone->FindComponent(); - if (transformComponent) - { - transformComponent->SetWorldTM(transform); - } + if (autoActivate == AutoActivate::DoNotActivate) + { + clone->SetRuntimeActiveByDefault(false); + } - if (autoActivate == AutoActivate::DoNotActivate) - { - clone->SetRuntimeActiveByDefault(false); - } + AzFramework::GameEntityContextRequestBus::Broadcast(&AzFramework::GameEntityContextRequestBus::Events::AddGameEntity, clone); - 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 88b524d868ab61369e74334823f858a46e2da158 Mon Sep 17 00:00:00 2001 From: Chris Santora Date: Tue, 4 May 2021 16:00:06 -0700 Subject: [PATCH 104/185] ATOM-14495 "POM Height Bias" (continued) Added Height Offset support to StandardMultilayerPBR.materialtype. In order to make this work, I updated the GetDepth callback function to support the option of returning absolute depth values rather than relative depth values. Although I could have done transformations inside the GetDepth function, having this as absolute cleans things up a lot. StandardMultilayerPBR_Parallax.lua functor code now populates the MaterialSRG with displacement min/max values, instead of having to normalize the depth factors for each layer. I think this is easier to understand and work with. Added Height Offset to each layer of StandardMultilayerPBR. Updated the naming and description for the parallax factor in each layer, to match the other material types. I removed the global "factor" material property because it doesn't seem applicable anymore since we have per-layer height offset. We can always add some form of this later if customers ask for it. Squashed commit of the following: commit 8df460800ff7058f9fbb01f995efdd5ab53d3d2c Author: Chris Santora Date: Tue May 4 13:35:27 2021 -0700 Found a workaround for the DXC compiler bug commit 5d81617285eb42bb7b48eb060234d2cb89249e34 Author: Chris Santora Date: Tue May 4 12:27:22 2021 -0700 Local WIP changes to get a DepthResult struct set up for the GetDepth functions. --- .../Materials/Types/EnhancedPBR_Common.azsli | 2 +- .../Types/EnhancedPBR_ForwardPass.azsl | 2 +- .../Types/StandardMultilayerPBR.materialtype | 75 ++++++--- .../Types/StandardMultilayerPBR_Common.azsli | 21 ++- ...tandardMultilayerPBR_DepthPass_WithPS.azsl | 5 +- .../StandardMultilayerPBR_ForwardPass.azsl | 16 +- .../Types/StandardMultilayerPBR_Parallax.lua | 52 ++++--- ...StandardMultilayerPBR_ParallaxPerLayer.lua | 3 +- ...tandardMultilayerPBR_Shadowmap_WithPS.azsl | 5 +- .../Materials/Types/StandardPBR_Common.azsli | 3 +- .../Types/StandardPBR_ForwardPass.azsl | 2 +- .../Atom/Features/ParallaxMapping.azsli | 146 ++++++++++++++---- .../Types/AutoBrick_ForwardPass.azsl | 4 +- 13 files changed, 244 insertions(+), 92 deletions(-) diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli index 314f15e8e1..4fc98dcf8b 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_Common.azsli @@ -105,7 +105,7 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial } // Callback function for ParallaxMapping.azsli -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl index 09a16556d6..173312c82e 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/EnhancedPBR_ForwardPass.azsl @@ -193,7 +193,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float if(o_parallax_highlightClipping && displacementIsClipped) { - baseColor = lerp(baseColor, float3(1.0,0.0,1.0), 0.5); + ApplyParallaxClippingHighlight(baseColor); } // ------- Metallic ------- diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype index 780a055c78..e2119dcf12 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR.materialtype @@ -356,19 +356,6 @@ "id": "m_parallaxUvIndex" } }, - { - "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values for all layers.", - "type": "Float", - "defaultValue": 1.0, - "min": 0.0, - "softMax": 2.0, - "connection": { - "type": "ShaderInput", - "id": "m_parallaxMainDepthFactor" - } - }, { "id": "algorithm", "displayName": "Algorithm", @@ -403,6 +390,17 @@ "type": "ShaderOption", "id": "o_parallax_enablePixelDepthOffset" } + }, + { + "id": "showClipping", + "displayName": "Show Clipping", + "description": "Highlight areas where the heightmap is clipped by the mesh surface.", + "type": "Bool", + "defaultValue": false, + "connection": { + "type": "ShaderOption", + "id": "o_parallax_highlightClipping" + } } ], "uv": [ @@ -1271,8 +1269,8 @@ }, { "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -1282,6 +1280,19 @@ "id": "m_layer1_m_depthFactor" } }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_layer1_m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", @@ -1964,8 +1975,8 @@ }, { "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -1975,6 +1986,19 @@ "id": "m_layer2_m_depthFactor" } }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_layer2_m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", @@ -2657,8 +2681,8 @@ }, { "id": "factor", - "displayName": "Factor", - "description": "Strength factor for scaling the depth values", + "displayName": "Heightmap Scale", + "description": "The total height of the heightmap in local model units.", "type": "Float", "defaultValue": 0.0, "min": 0.0, @@ -2668,6 +2692,19 @@ "id": "m_layer3_m_depthFactor" } }, + { + "id": "offset", + "displayName": "Offset", + "description": "Adjusts the overall displacement amount in local model units.", + "type": "Float", + "defaultValue": 0.0, + "softMin": -0.1, + "softMax": 0.1, + "connection": { + "type": "ShaderInput", + "id": "m_layer3_m_depthOffset" + } + }, { "id": "invert", "displayName": "Invert", diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli index 93cf9fdb7c..ba0eaf2ac1 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Common.azsli @@ -60,7 +60,10 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial float4 m_pad3; // [GFX TODO][ATOM-14595] This is a workaround for a data stomping bug. Remove once it's fixed. uint m_parallaxUvIndex; - float m_parallaxMainDepthFactor; + + // These are used to limit the heightmap intersection search range to the narrowest band possible, to give the best quality result. + float m_displacementMin; // The lowest displacement value possible from all layers combined + float m_displacementMax; // The highest displacement value possible from all layers combined float3x3 m_uvMatrix; float4 m_pad4; // [GFX TODO][ATOM-14595] This is a workaround for a data stomping bug. Remove once it's fixed. @@ -211,7 +214,7 @@ void GetDepth_Setup(float3 vertexBlendMask) } // Callback function for ParallaxMapping.azsli -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { float3 layerDepthValues = float3(0,0,0); @@ -223,8 +226,9 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer1_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.r = SampleDepthOrHeightMap(MaterialSrg::m_layer1_m_depthInverted, MaterialSrg::m_layer1_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy); + layerDepthValues.r = SampleDepthOrHeightMap(MaterialSrg::m_layer1_m_depthInverted, MaterialSrg::m_layer1_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; layerDepthValues.r *= MaterialSrg::m_layer1_m_depthFactor; + layerDepthValues.r -= MaterialSrg::m_layer1_m_depthOffset; } if(o_layer2_o_useDepthMap) @@ -235,8 +239,9 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer2_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.g = SampleDepthOrHeightMap(MaterialSrg::m_layer2_m_depthInverted, MaterialSrg::m_layer2_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy); + layerDepthValues.g = SampleDepthOrHeightMap(MaterialSrg::m_layer2_m_depthInverted, MaterialSrg::m_layer2_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; layerDepthValues.g *= MaterialSrg::m_layer2_m_depthFactor; + layerDepthValues.g -= MaterialSrg::m_layer2_m_depthOffset; } if(o_layer3_o_useDepthMap) @@ -247,8 +252,9 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) layerUv = mul(MaterialSrg::m_layer3_m_uvMatrix, float3(uv, 1.0)).xy; } - layerDepthValues.b = SampleDepthOrHeightMap(MaterialSrg::m_layer3_m_depthInverted, MaterialSrg::m_layer3_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy); + layerDepthValues.b = SampleDepthOrHeightMap(MaterialSrg::m_layer3_m_depthInverted, MaterialSrg::m_layer3_m_depthMap, MaterialSrg::m_sampler, layerUv, uv_ddx, uv_ddy).m_depth; layerDepthValues.b *= MaterialSrg::m_layer3_m_depthFactor; + layerDepthValues.b -= MaterialSrg::m_layer3_m_depthOffset; } // Note, when the blend source is BlendMaskSource::VertexColors, parallax will not be able to blend correctly between layers. It will end up using the same blend mask values @@ -256,7 +262,6 @@ float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) // you have a small depth factor relative to the size of the blend transition. float3 blendMaskValues = GetBlendMaskValues(uv, s_blendMaskFromVertexStream); - float3 depth = BlendLayers(layerDepthValues.r, layerDepthValues.g, layerDepthValues.b, blendMaskValues); - - return depth; + float depth = BlendLayers(layerDepthValues.r, layerDepthValues.g, layerDepthValues.b, blendMaskValues); + return DepthResultAbsolute(depth); } diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl index bc8045f412..ae156d7313 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_DepthPass_WithPS.azsl @@ -115,8 +115,9 @@ PSDepthOutput MainPS(VSDepthOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float parallaxMainDepthOffset = 0.0; - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, + float parallaxOverallOffset = MaterialSrg::m_displacementMax; + float parallaxOverallFactor = MaterialSrg::m_displacementMax - MaterialSrg::m_displacementMin; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], parallaxOverallFactor, parallaxOverallOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl index 3f49152c1c..df7ca7dc16 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ForwardPass.azsl @@ -148,12 +148,14 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float if(o_debugDrawMode == DebugDrawMode::DepthMaps) { GetDepth_Setup(IN.m_blendMask); - float depth = GetDepth(IN.m_uv[MaterialSrg::m_parallaxUvIndex], float2(0,0), float2(0,0)); + float depth = GetNormalizedDepth(-MaterialSrg::m_displacementMax, -MaterialSrg::m_displacementMin, IN.m_uv[MaterialSrg::m_parallaxUvIndex], float2(0,0), float2(0,0)); return MakeDebugOutput(IN, float3(depth,depth,depth)); } // ------- Parallax ------- + bool displacementIsClipped = false; + // Parallax mapping's non uniform uv transformations break screen space subsurface scattering, disable it when subsurface scatteirng is enabled if(ShouldHandleParallax()) { @@ -162,10 +164,11 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float parallaxMainDepthOffset = 0.0; - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, + float parallaxOverallOffset = MaterialSrg::m_displacementMax; + float parallaxOverallFactor = MaterialSrg::m_displacementMax - MaterialSrg::m_displacementMin; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], parallaxOverallFactor, parallaxOverallOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, - IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); + IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth, displacementIsClipped); // Adjust directional light shadow coorinates for parallax correction if(o_parallax_enablePixelDepthOffset) @@ -227,6 +230,11 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float float3 layer2_baseColor = BlendBaseColor(layer2_sampledColor, MaterialSrg::m_layer2_m_baseColor.rgb, MaterialSrg::m_layer2_m_baseColorFactor, o_layer2_o_baseColorTextureBlendMode, o_layer2_o_baseColor_useTexture); float3 layer3_baseColor = BlendBaseColor(layer3_sampledColor, MaterialSrg::m_layer3_m_baseColor.rgb, MaterialSrg::m_layer3_m_baseColorFactor, o_layer3_o_baseColorTextureBlendMode, o_layer3_o_baseColor_useTexture); float3 baseColor = BlendLayers(layer1_baseColor, layer2_baseColor, layer3_baseColor, blendMaskValues); + + if(o_parallax_highlightClipping && displacementIsClipped) + { + ApplyParallaxClippingHighlight(baseColor); + } // ------- Metallic ------- diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Parallax.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Parallax.lua index 522121c96f..8880a4b842 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Parallax.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Parallax.lua @@ -20,10 +20,12 @@ function GetMaterialPropertyDependencies() "layer1_parallax.enable", "layer2_parallax.enable", "layer3_parallax.enable", - "parallax.factor", "layer1_parallax.factor", "layer2_parallax.factor", - "layer3_parallax.factor" + "layer3_parallax.factor", + "layer1_parallax.offset", + "layer2_parallax.offset", + "layer3_parallax.offset" } end @@ -31,6 +33,23 @@ function GetShaderOptionDependencies() return {"o_parallax_feature_enabled"} end +function MergeRange(heightMinMax, offset, factor) + top = offset + bottom = offset - factor + + if(heightMinMax[1] == nil) then + heightMinMax[1] = top + else + heightMinMax[1] = math.max(heightMinMax[1], top) + end + + if(heightMinMax[0] == nil) then + heightMinMax[0] = bottom + else + heightMinMax[0] = math.min(heightMinMax[0], bottom) + end +end + function Process(context) local enableParallax = context:GetMaterialPropertyValue_bool("parallax.enable") local enable1 = context:GetMaterialPropertyValue_bool("layer1_parallax.enable") @@ -39,30 +58,25 @@ function Process(context) enableParallax = enableParallax and (enable1 or enable2 or enable3) context:SetShaderOptionValue_bool("o_parallax_feature_enabled", enableParallax) - -- Smaller values for the main parallax factor used in GetParallaxOffset() give better quality. - -- So increase the per-layer parallax factors by normalizing them, and reduce the main factor accordingly. if(enableParallax) then local factorLayer1 = context:GetMaterialPropertyValue_float("layer1_parallax.factor") local factorLayer2 = context:GetMaterialPropertyValue_float("layer2_parallax.factor") local factorLayer3 = context:GetMaterialPropertyValue_float("layer3_parallax.factor") - local mainFactor = context:GetMaterialPropertyValue_float("parallax.factor") - maxLayerFactor = 0.0 - if(enable1) then maxLayerFactor = math.max(maxLayerFactor, factorLayer1) end - if(enable2) then maxLayerFactor = math.max(maxLayerFactor, factorLayer2) end - if(enable3) then maxLayerFactor = math.max(maxLayerFactor, factorLayer3) end + local offsetLayer1 = context:GetMaterialPropertyValue_float("layer1_parallax.offset") + local offsetLayer2 = context:GetMaterialPropertyValue_float("layer2_parallax.offset") + local offsetLayer3 = context:GetMaterialPropertyValue_float("layer3_parallax.offset") + + local heightMinMax = {nil, nil} + if(enable1) then MergeRange(heightMinMax, offsetLayer1, factorLayer1) end + if(enable2) then MergeRange(heightMinMax, offsetLayer2, factorLayer2) end + if(enable3) then MergeRange(heightMinMax, offsetLayer3, factorLayer3) end - if(maxLayerFactor < 0.0001) then + if(heightMinMax[1] - heightMinMax[0] < 0.0001) then context:SetShaderOptionValue_bool("o_parallax_feature_enabled", false) else - factorLayer1 = factorLayer1 / maxLayerFactor - factorLayer2 = factorLayer2 / maxLayerFactor - factorLayer3 = factorLayer3 / maxLayerFactor - mainFactor = mainFactor * maxLayerFactor; - context:SetShaderConstant_float("m_layer1_m_depthFactor", factorLayer1) - context:SetShaderConstant_float("m_layer2_m_depthFactor", factorLayer2) - context:SetShaderConstant_float("m_layer3_m_depthFactor", factorLayer3) - context:SetShaderConstant_float("m_parallaxMainDepthFactor", mainFactor) + context:SetShaderConstant_float("m_displacementMin", heightMinMax[0]) + context:SetShaderConstant_float("m_displacementMax", heightMinMax[1]) end end end @@ -76,8 +90,8 @@ function ProcessEditor(context) end context:SetMaterialPropertyVisibility("parallax.parallaxUv", visibility) - context:SetMaterialPropertyVisibility("parallax.factor", visibility) context:SetMaterialPropertyVisibility("parallax.algorithm", visibility) context:SetMaterialPropertyVisibility("parallax.quality", visibility) context:SetMaterialPropertyVisibility("parallax.pdo", visibility) + context:SetMaterialPropertyVisibility("parallax.showClipping", visibility) end diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ParallaxPerLayer.lua b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ParallaxPerLayer.lua index a1695e827b..119dfed436 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ParallaxPerLayer.lua +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_ParallaxPerLayer.lua @@ -42,7 +42,8 @@ function ProcessEditor(context) if(not enable or textureMap == nil) then visibility = MaterialPropertyVisibility_Hidden end - + context:SetMaterialPropertyVisibility("parallax.factor", visibility) + context:SetMaterialPropertyVisibility("parallax.offset", visibility) context:SetMaterialPropertyVisibility("parallax.invert", visibility) end diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl index 6fa721ef47..325937b228 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardMultilayerPBR_Shadowmap_WithPS.azsl @@ -114,8 +114,9 @@ PSDepthOutput MainPS(VertexOutput IN, bool isFrontFace : SV_IsFrontFace) float3x3 uvMatrix = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrix : CreateIdentity3x3(); float3x3 uvMatrixInverse = MaterialSrg::m_parallaxUvIndex == 0 ? MaterialSrg::m_uvMatrixInverse : CreateIdentity3x3(); - float parallaxMainDepthOffset = 0.0; - GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], MaterialSrg::m_parallaxMainDepthFactor, parallaxMainDepthOffset, + float parallaxOverallOffset = MaterialSrg::m_displacementMax; + float parallaxOverallFactor = MaterialSrg::m_displacementMax - MaterialSrg::m_displacementMin; + GetParallaxInput(IN.m_normal, tangents[MaterialSrg::m_parallaxUvIndex], bitangents[MaterialSrg::m_parallaxUvIndex], parallaxOverallFactor, parallaxOverallOffset, ObjectSrg::GetWorldMatrix(), uvMatrix, uvMatrixInverse, IN.m_uv[MaterialSrg::m_parallaxUvIndex], IN.m_worldPosition, depth); diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli index ee1533cf16..2e2ad742cb 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_Common.azsli @@ -94,11 +94,12 @@ ShaderResourceGroup MaterialSrg : SRG_PerMaterial } // Callback function for ParallaxMapping.azsli -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { return SampleDepthOrHeightMap(MaterialSrg::m_depthInverted, MaterialSrg::m_depthMap, MaterialSrg::m_sampler, uv, uv_ddx, uv_ddy); } + COMMON_OPTIONS_PARALLAX() bool ShouldHandleParallax() diff --git a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl index 4d12eb181d..acc355bc41 100644 --- a/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl +++ b/Gems/Atom/Feature/Common/Assets/Materials/Types/StandardPBR_ForwardPass.azsl @@ -157,7 +157,7 @@ PbrLightingOutput ForwardPassPS_Common(VSOutput IN, bool isFrontFace, out float if(o_parallax_highlightClipping && displacementIsClipped) { - baseColor = lerp(baseColor, float3(1.0,0.0,1.0), 0.5); + ApplyParallaxClippingHighlight(baseColor); } // ------- Metallic ------- diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli index 8027443f9a..1d2beb0f10 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/ParallaxMapping.azsli @@ -23,25 +23,104 @@ option bool o_parallax_feature_enabled; option bool o_parallax_highlightClipping; option bool o_parallax_shadow; +// I tried to make this an enum class, but ran into some DXC bug when compiling to SPIRV. +enum DepthResultCode +{ + DepthResultCode_Invalid, + DepthResultCode_Normalized, //!< The result is in range [0,1], where 0 is the top of the heightmap and 1 is the bottom of the heightmap. + DepthResultCode_Absolute //!< The result is tangent space units (the same as world units if there's no mesh scaling), where 0 is at the mesh surface and positive values are below the surface. +}; + +//! The return value for the GetDepth() callback function below. +struct DepthResult +{ + DepthResultCode m_resultCode; + float m_depth; +}; + +//! Convenience function for making a DepthResult with Code::Normalized +DepthResult DepthResultNormalized(float depth) +{ + DepthResult result; + result.m_resultCode = DepthResultCode_Normalized; + result.m_depth = depth; + return result; +} + +//! Convenience function for making a DepthResult with Code::Absolute +DepthResult DepthResultAbsolute(float depth) +{ + DepthResult result; + result.m_resultCode = DepthResultCode_Absolute; + result.m_depth = depth; + return result; +} + //! The client shader must define this function. //! This allows the client shader to implement special depth map sampling, for example procedurally generating or blending depth maps. +//! In simple cases though, the implementation of GetDepth() can simply call SampleDepthOrHeightMap(). //! @param uv the UV coordinates to use for sampling //! @param uv_ddx will be set to ddx_fine(uv) //! @param uv_ddy will be set to ddy_fine(uv) -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy); +//! @return see struct DepthResult +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy); //! Convenience function that can be used to implement GetDepth(). //! @param isHeightmap indicates whether to sample the map is a height map rather than a depth map. -float SampleDepthOrHeightMap(bool isHeightmap, Texture2D map, sampler mapSampler, float2 uv, float2 uv_ddx, float2 uv_ddy) +//! @return see struct DepthResult. In this case it will always contain a Code::Normalized result. +DepthResult SampleDepthOrHeightMap(bool isHeightmap, Texture2D map, sampler mapSampler, float2 uv, float2 uv_ddx, float2 uv_ddy) { - return abs((isHeightmap * 1.0) - map.SampleGrad(mapSampler, uv, uv_ddx, uv_ddy).r); + DepthResult result; + result.m_resultCode = DepthResultCode_Normalized; + result.m_depth = abs((isHeightmap * 1.0) - map.SampleGrad(mapSampler, uv, uv_ddx, uv_ddy).r); + return result; } -float GetClampedDepth(float minSampledDepth, float2 uv, float2 uv_ddx, float2 uv_ddy) +//! Calls GetDepth() and then normalizes the result if it isn't normalized already. +//! @param startDepth is the high point, which corresponds to a normalized depth value of 0. +//! @param stopDepth is the low point, which corresponds to a normalized depth value of 1. +//! @param inverseDepthRange is an optimization, and must be set to "1.0 / (stopDepth - startDepth)". +//! @param uv the UV coordinates to use for sampling +//! @param uv_ddx must be set to ddx_fine(uv) +//! @param uv_ddy must be set to ddy_fine(uv) +//! @param a depth value in the range [0,1] +float GetNormalizedDepth(float startDepth, float stopDepth, float inverseDepthRange, float2 uv, float2 uv_ddx, float2 uv_ddy) { - float sampledDepthValue = GetDepth(uv, uv_ddx, uv_ddy); - sampledDepthValue = max(sampledDepthValue, minSampledDepth); - return sampledDepthValue; + // startDepth can be less than 0, representing a displacement above the mesh surface. + // But since we don't currently support any vertex displacement, negative depth values would cause various + // problems especially when PDO is enabled, like parallax surfaces clipping through foreground geometry, and parallax + // surfaces disappearing at low angles. So we clamp all depth values to a minimum of 0. + + float normalizedDepth = 0.0; + + DepthResult depthResult = GetDepth(uv, uv_ddx, uv_ddy); + + if(stopDepth - startDepth > 0.0001) + { + if(DepthResultCode_Normalized == depthResult.m_resultCode) + { + float minNormalizedDepth = -startDepth * inverseDepthRange; + normalizedDepth = max(depthResult.m_depth, minNormalizedDepth); + } + else if(DepthResultCode_Absolute == depthResult.m_resultCode) + { + float clampedAbsoluteDepth = max(depthResult.m_depth, 0.0); + normalizedDepth = (clampedAbsoluteDepth - startDepth) * inverseDepthRange; + } + } + + return normalizedDepth; +} + +float GetNormalizedDepth(float startDepth, float stopDepth, float2 uv, float2 uv_ddx, float2 uv_ddy) +{ + float inverseDepthRange = 1.0 / (stopDepth - startDepth); + return GetNormalizedDepth(startDepth, stopDepth, inverseDepthRange, uv, uv_ddx, uv_ddy); +} + +void ApplyParallaxClippingHighlight(inout float3 baseColor) +{ + baseColor = lerp(baseColor, float3(1.0, 0.0, 1.0), 0.5); } struct ParallaxOffset @@ -55,7 +134,7 @@ struct ParallaxOffset ParallaxOffset BasicParallaxMapping(float depthFactor, float2 uv, float3 dirToCameraTS) { // the amount to shift - float2 delta = dirToCameraTS.xy * GetDepth(uv, ddx_fine(uv), ddy_fine(uv)) * depthFactor; + float2 delta = dirToCameraTS.xy * GetNormalizedDepth(0, depthFactor, uv, ddx_fine(uv), ddy_fine(uv)) * depthFactor; ParallaxOffset result; @@ -89,25 +168,23 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo float2 ddx_uv = ddx_fine(uv); float2 ddy_uv = ddy_fine(uv); + + float depthSearchStart = -depthOffset; + float depthSearchEnd = depthSearchStart + depthFactor; + float inverseDepthFactor = 1.0 / depthFactor; + // This is the relative position at which we begin searching for intersection. // It is adjusted according to the depthOffset, raising or lowering the whole surface by depthOffset units. float3 parallaxOffset = dirToCameraTS.xyz * dirToCameraZInverse * depthOffset; - // Note that depthOffset can raise the heightmap toward (and potentially above) the surface of the mesh. - // We will clamp the heightmap samples to prevent displacements that lie above the surface, which would cause various - // problems especially when PDO is enabled, like parallax surfaces clipping through foreground geometry, and parallax - // surfaces disappearing at low angles. - float minSampledDepth = depthOffset / depthFactor; - minSampledDepth = clamp(minSampledDepth, 0, 1); - // Get an initial heightmap sample to start the intersection search, starting at our initial parallaxOffset position. - float currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); + float currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); float prevSample; - // Note that when depthOffset > 0, we could actually narrow the search so that instead of going through the entire [0,1] range - // of the heightmap, we could go through the range [minSampledDepth,1]. This would give more accurate results and fewer artifacts - // in case where depthOffset is significant. But for the sake of simplicity we currently search the whole range in all cases. + // Note that when depthOffset < 0, we could actually narrow the search so that instead of going through the entire [depthSearchStart,depthSearchEnd] range + // of the heightmap, we could go through the range [0,depthSearchEnd]. This would give more accurate results and fewer artifacts + // in case where the magnitude of depthOffset is significant. But for the sake of simplicity we currently search the whole range in all cases. // Do a basic search for the intersect step while(currentSample > currentStep) @@ -116,7 +193,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo parallaxOffset += delta; prevSample = currentSample; - currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } // Depending on the algorithm, we refine the result of the above search @@ -156,7 +233,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo parallaxOffset += reliefDelta * depthSign; currentStep += reliefStep * depthSign; - currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } } break; @@ -184,7 +261,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo parallaxOffset += adjustedDelta; prevSample = currentSample; - currentSample = GetClampedDepth(minSampledDepth, uv + parallaxOffset.xy, ddx_uv, ddy_uv); + currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, uv + parallaxOffset.xy, ddx_uv, ddy_uv); } } break; @@ -197,17 +274,24 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo // can be noticeably above the surface and still needs to be clamped here. The main case is when depthFactor==0 and depthOffset>1. if(parallaxOffset.z > 0.0) { - result.m_isClipped = o_parallax_highlightClipping; parallaxOffset = float3(0,0,0); } - // Extra check to report whether the heightmap is clipped. Inaccuracies in the intersection search make it difficult to rely on - // parallaxOffset.z to determine whether clipping has occurred. The most accurate way to report clipping is to sample the - // heightmap one last time at the final adjusted UV. Since that's expensive, we only do it when the o_parallax_highlightClipping - // option is set. - else if (o_parallax_highlightClipping) + + if (o_parallax_highlightClipping) { - float sampledDepthValue = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); - result.m_isClipped = sampledDepthValue < minSampledDepth; + // The most accurate way to report clipping is to sample the heightmap one last time at the final adjusted UV. + // (trying to do it based on parallaxOffset.z values just leads to too many edge cases) + + DepthResult depthResult = GetDepth(uv + parallaxOffset.xy, ddx_uv, ddy_uv); + + if(DepthResultCode_Normalized == depthResult.m_resultCode) + { + result.m_isClipped = lerp(depthSearchStart, depthSearchEnd, depthResult.m_depth) < 0; + } + else if(DepthResultCode_Absolute == depthResult.m_resultCode) + { + result.m_isClipped = depthResult.m_depth < 0.0; + } } if(o_parallax_shadow && any(dirToLightTS)) @@ -233,7 +317,7 @@ ParallaxOffset AdvancedParallaxMapping(float depthFactor, float depthOffset, flo } shadowUV += shadowDelta; - currentSample = GetClampedDepth(minSampledDepth, shadowUV, ddx_uv, ddy_uv); + currentSample = GetNormalizedDepth(depthSearchStart, depthSearchEnd, inverseDepthFactor, shadowUV, ddx_uv, ddy_uv); currentStep -= step; } diff --git a/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl b/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl index fd11d0d8cd..c90b1d1446 100644 --- a/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl +++ b/Gems/Atom/TestData/TestData/Materials/Types/AutoBrick_ForwardPass.azsl @@ -119,12 +119,12 @@ void GetSurfaceShape(float2 uv, out float depth, out float3 normal) } // Callback function for ParallaxMapping.azsli -float GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) +DepthResult GetDepth(float2 uv, float2 uv_ddx, float2 uv_ddy) { float depth; float3 normal; GetSurfaceShape(uv, depth, normal); - return depth; + return DepthResultNormalized(depth); } ForwardPassOutput AutoBrick_ForwardPassPS(VSOutput IN) From 0791d1d05f84dc1aff1f91759cfcb8f9aee98400 Mon Sep 17 00:00:00 2001 From: Mike Chang <62353586+amzn-changml@users.noreply.github.com> Date: Tue, 4 May 2021 16:09:26 -0700 Subject: [PATCH 105/185] Set default CDN for 3p system to production Cloudfront --- cmake/3rdPartyPackages.cmake | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cmake/3rdPartyPackages.cmake b/cmake/3rdPartyPackages.cmake index b3545fd415..60d8b4e20d 100644 --- a/cmake/3rdPartyPackages.cmake +++ b/cmake/3rdPartyPackages.cmake @@ -32,7 +32,8 @@ include(cmake/LySet.cmake) # also allowed: # "s3://bucketname" (it will use LYPackage_S3Downloader.cmake to download it from a s3 bucket) -set(LY_PACKAGE_SERVER_URLS "" CACHE STRING "Server URLS to fetch packages from") +# https://d2c171ws20a1rv.cloudfront.net will be the current "production" CDN until formally moved to the public O3DE repo +set(LY_PACKAGE_SERVER_URLS "https://d2c171ws20a1rv.cloudfront.net" CACHE STRING "Server URLS to fetch packages from") # Note: if you define the "LY_PACKAGE_SERVER_URLS" environment variable # it will be added to this value in the front, so that users can set # an env var and use that as an "additional" set of servers beyond the default set. From 5e6d058a43434b938c067adbd94b7b643a91c9d3 Mon Sep 17 00:00:00 2001 From: jonbeer Date: Tue, 4 May 2021 18:23:02 -0700 Subject: [PATCH 106/185] Removing default case to fix crash and updating tests --- .../Serialization/Json/JsonDeserializer.cpp | 4 +- .../Code/Tests/PhysXColliderPrefabTests.cpp | 44 +++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp index 8d0da9e54a..9e0ab80dd1 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp @@ -33,10 +33,10 @@ namespace AZ "Target object for Json Serialization is pointing to nothing during loading."); } - if (IsExplicitDefault(value)) + /*if (IsExplicitDefault(value)) { return context.Report(Tasks::ReadField, Outcomes::DefaultsUsed, "Value has an explicit default."); - } + }*/ BaseJsonSerializer* serializer = context.GetRegistrationContext()->GetSerializerForType(typeId); if (serializer) diff --git a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp index 4287ce17db..5748fca931 100644 --- a/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp +++ b/Gems/PhysX/Code/Tests/PhysXColliderPrefabTests.cpp @@ -36,7 +36,7 @@ namespace PhysX protected: }; - TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsTypes_ValuesNotNull) + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsTypes_ValuesEqual) { //create a prefab for storing data AzToolsFramework::Prefab::PrefabDom prefabDom; @@ -130,58 +130,58 @@ namespace PhysX EXPECT_NE(nullptr, updatedColliderConfigPtr); } - TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsColliderComponents_PointersNotNull) + TEST_F(PhysXColliderPrefabTests, StoreAndLoad_DefaultPhysicsColliderComponents_ValuesEqual) { //create a prefab for storing data AzToolsFramework::Prefab::PrefabDom prefabDom; //shared pointer - box collider - defaults only - auto boxColliderPtr = AZStd::make_shared(); + BoxColliderComponent boxColliderComponent; AZ::JsonSerializationResult::ResultCode result - = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), boxColliderPtr); + = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), boxColliderComponent); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - boxColliderPtr = nullptr; - result = AZ::JsonSerialization::Load(boxColliderPtr, prefabDom); + BoxColliderComponent newBoxColliderComponent; + result = AZ::JsonSerialization::Load(newBoxColliderComponent, prefabDom); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - EXPECT_NE(nullptr, boxColliderPtr); + EXPECT_EQ(newBoxColliderComponent.GetCollisionLayerName(), boxColliderComponent.GetCollisionLayerName()); //shared pointer - sphere collider - defaults only - auto sphereColliderPtr = AZStd::make_shared(); - result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), sphereColliderPtr); + SphereColliderComponent sphereColliderComponent; + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), sphereColliderComponent); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - sphereColliderPtr = nullptr; - result = AZ::JsonSerialization::Load(sphereColliderPtr, prefabDom); + SphereColliderComponent newSphereColliderComponent; + result = AZ::JsonSerialization::Load(newSphereColliderComponent, prefabDom); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - EXPECT_NE(nullptr, sphereColliderPtr); + EXPECT_EQ(newSphereColliderComponent.GetCollisionLayerName(), sphereColliderComponent.GetCollisionLayerName()); //shared pointer - capsule collider - defaults only - auto capsuleColliderPtr = AZStd::make_shared(); - result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), capsuleColliderPtr); + CapsuleColliderComponent capsuleColliderComponent; + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), capsuleColliderComponent); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - capsuleColliderPtr = nullptr; - result = AZ::JsonSerialization::Load(capsuleColliderPtr, prefabDom); + CapsuleColliderComponent newCapsuleColliderComponent; + result = AZ::JsonSerialization::Load(newCapsuleColliderComponent, prefabDom); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - EXPECT_NE(nullptr, capsuleColliderPtr); + EXPECT_EQ(newCapsuleColliderComponent.GetCollisionLayerName(), capsuleColliderComponent.GetCollisionLayerName()); //shared pointer - shape collider - defaults only - auto shapeColliderPtr = AZStd::make_shared(); - result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeColliderPtr); + ShapeColliderComponent shapeColliderComponent; + result = AZ::JsonSerialization::Store(prefabDom, prefabDom.GetAllocator(), shapeColliderComponent); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - shapeColliderPtr = nullptr; - result = AZ::JsonSerialization::Load(shapeColliderPtr, prefabDom); + ShapeColliderComponent newShapeColliderComponent; + result = AZ::JsonSerialization::Load(newShapeColliderComponent, prefabDom); EXPECT_EQ(AZ::JsonSerializationResult::Processing::Completed, result.GetProcessing()); - EXPECT_NE(nullptr, shapeColliderPtr); + EXPECT_EQ(newShapeColliderComponent.GetCollisionLayerName(), shapeColliderComponent.GetCollisionLayerName()); } } From 7963924b6ac528e710565356862c41efa53566e4 Mon Sep 17 00:00:00 2001 From: jonbeer Date: Tue, 4 May 2021 18:27:09 -0700 Subject: [PATCH 107/185] Removing extra commented code --- .../AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp index 9e0ab80dd1..88d698b352 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp +++ b/Code/Framework/AzCore/AzCore/Serialization/Json/JsonDeserializer.cpp @@ -33,11 +33,6 @@ namespace AZ "Target object for Json Serialization is pointing to nothing during loading."); } - /*if (IsExplicitDefault(value)) - { - return context.Report(Tasks::ReadField, Outcomes::DefaultsUsed, "Value has an explicit default."); - }*/ - BaseJsonSerializer* serializer = context.GetRegistrationContext()->GetSerializerForType(typeId); if (serializer) { From ceb7ac333a1e58941606dc401fded753522662ff Mon Sep 17 00:00:00 2001 From: balibhan Date: Wed, 5 May 2021 12:31:43 +0530 Subject: [PATCH 108/185] 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 109/185] 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 e1f7d04bc251c4e9e04853fa735c9549b4021876 Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 5 May 2021 13:10:01 +0100 Subject: [PATCH 110/185] adding icon for non-uniform scale component --- .../Icons/Components/NonUniformScale.svg | 27 +++++++++++++++++++ .../EditorNonUniformScaleComponent.cpp | 2 ++ 2 files changed, 29 insertions(+) create mode 100644 Assets/Editor/Icons/Components/NonUniformScale.svg diff --git a/Assets/Editor/Icons/Components/NonUniformScale.svg b/Assets/Editor/Icons/Components/NonUniformScale.svg new file mode 100644 index 0000000000..f377232d62 --- /dev/null +++ b/Assets/Editor/Icons/Components/NonUniformScale.svg @@ -0,0 +1,27 @@ + + + Icons / Toolbar / Non Uniform Scaling + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp index d28f23c847..67f8212f5e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/EditorNonUniformScaleComponent.cpp @@ -41,6 +41,8 @@ namespace AzToolsFramework ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::RemoveableByUser, true) ->Attribute(AZ::Edit::Attributes::DraggableByUser, false) + ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/NonUniformScale.svg") + ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/NonUniformScale.svg") ->DataElement( AZ::Edit::UIHandlers::Default, &EditorNonUniformScaleComponent::m_scale, "Non-uniform Scale", "Non-uniform scale for this entity only (does not propagate through hierarchy)") From 9e2975ba3cb81a819ddd06c7704a0ce09a8cdb0e Mon Sep 17 00:00:00 2001 From: pereslav Date: Wed, 5 May 2021 14:19:23 +0100 Subject: [PATCH 111/185] 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 112/185] 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 45cbe4767f18de76cb11b0cbce0f0316f21d6362 Mon Sep 17 00:00:00 2001 From: greerdv Date: Wed, 5 May 2021 15:14:50 +0100 Subject: [PATCH 113/185] adding comment to AddNonUniformScaleButton --- .../AzToolsFramework/ToolsComponents/TransformComponent.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h index 7a0675187a..783ecfc84f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ToolsComponents/TransformComponent.h @@ -32,6 +32,8 @@ namespace AzToolsFramework { namespace Components { + // this is a workaround for a bug which causes the button to appear with incorrect placement if added directly + // to the transform component class AddNonUniformScaleButton { public: From d7b796fd73a14e4951abeb1d18e5ed075e35e6e6 Mon Sep 17 00:00:00 2001 From: bosnichd Date: Wed, 5 May 2021 09:07:28 -0600 Subject: [PATCH 114/185] 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() -{ - if (!m_pHelperMtl) - { - m_pHelperMtl = GetIEditor()->Get3DEngine()->GetMaterialManager()->LoadMaterial(HELPER_MATERIAL); - } - return m_pHelperMtl; -}; - ////////////////////////////////////////////////////////////////////////// -IStatObj* CIconManager::GetObject(EStatObject object) +IStatObj* CIconManager::GetObject(EStatObject) { - 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